## Lecture 2 - Input and Conditionals ## # Michelle Szucs # To download as a Python file, right-click the link # and select "Save link as..." ########## Getting user input ############ # Using input # Remember that input will store numbers as ints or floats myAge = input("What is your age? ") friendAge = input("What is your friend's age? ") # Using raw_input # After receiving the input, you have to cast it to the # correct type. This is called typecasting. # You can uncomment the following lines (and comment the part # with input) if you want to try the code this way. #myAge = int(raw_input("What is your age? ")) #friendAge = int(raw_input("What is your friend's age? ")) # These print statements check whether the inputted values # are integers. In the shell, you'll just see True or False # when you run your code. That's because the whole statement # is evaluated in the same way that we evaluate 3*5 print type(myAge) == int print type(friendAge) == int ########## Branching if/else/elif statements ######### # First, we need to check that our variables are the correct # type if we use input. # Remember that these two statements evaluate to True or False. # Therefore, the if statement can be simplified to: # if True and True: (True) # if True and False: (False) # if False and True: (False) # if False and False: (False) if (type(myAge) == int) and (type(friendAge) == int): # Code at this level of indentation only executes # if the above if statement evaluates to True if myAge > friendAge: print "You're older." # You can add a lot more code at this level of # indentation that will only be executed if # myAge > friendAge. Try it! elif myAge < friendAge: print "You're younger." # You can string together multiple elif statements. # Each elif will only be executed if none of the previous # elif statements at the same level of indentation were # True but the current elif is True. else: print "You're the same age." # Make sure you consider all possible conditions before # writing a final else statement! # If the first if statement wasn't satisfied, we know the user # inputted something other than an integer - it's a good idea # to have a sort of error message that explains why the code # didn't run. else: print "Invalid input" """(Three quotes can enclose multi-line comments). Boolean comparators: > >= < <= == != and or not """