Python Interview Questions 8

66. """Module for demonstrating files."""
import sys
def main(filename):
  f = open(filename, mode='rt', encoding='utf-8')
  for line in f:
      sys.stdout.write(line)
  f.close()

if __name__ == '__main__':
  main(sys.argv[1])

67. Write a function to add two numbers
def add_numbers(*args):
    total = 0
    for a in args:
        total += a
    print (total)

add_numbers(3)
add_numbers(3, 42)

68.  How to un-pack arguments
def health_calculator(age, apples_ate, cigs_smoked):
    answer = (100-age) + (apples_ate * 3.5) - (cigs_smoked * 2)
    print(answer)

data = [27,20,0]
health_calculator(data[0],data[1],data[2])
health_calculator(*data)


  
69. Example of continue
numbersTaken = [2,5,12,33,17]
print ("Here are the numbers that are still available:")
for n in range(1,20):
    if n in numbersTaken:
        continue
    print(n)

70. Example of default arg
def get_gender(sex='Unknown'):
    if sex is "m":
        sex = "Male"
    elif sex is "f":
        sex = "Female"
    print(sex)

get_gender('m')
get_gender('f')
get_gender()

No comments:

Post a Comment