# Demo for input, float, int, try, except, else, while, function structure print("EXAMPLE FOR: input(); loops with while, error management with try, except, else, continue, return", end=" ") print("plus using int and float to convert strings. The built-in function", end = " ") print("input always takes in whatever you type as a string, on the surface, it is very easy to use.") Str_myInput=input("Type anything and hit return: ") print("Here is your input: " + Str_myInput) #the problem is, to the input command, 1 is a string and 3.414 is a string and 7/4/1776 is a string. #It is up to you as a programmer to vet your user's input and decide if its what you want. #For all practical purposes, this process demands a function tailored to your specific situation. #Let look at a case or two, begining with a case were you need an integer. print() print("Lets test getting an integer") def get_an_integer(Str_message): #"def" tells Python you are creating a process called a function while True: # we may have to loop through this process several times, using "while" enables the loop try: #try, except, else, finally and assert are the basic error management tools; try expects an error Int_intValue= int(input(Str_message)) #get a user input and convert that string to an integer except ValueError: #ValueError is just one of trillion kinds of errors, see https://docs.python.org/3/library/exceptions.html print("An integer is a whole number - no decimal part.") #you got an error, cycle thorugh again Str_message=("Please pick an integer from 1 to 10.") #with a slightly more explicit input message continue #go back to the top of the loop else: #if there was no error return Int_intValue #just send back the value you got break Int_GotInt = get_an_integer("Pick a number from 1 to 10: ") #when the function get_an_integer is successful #since we got back an integer, it is now up to you to do other input vetting, either her or in another function print("Good, " + str(Int_GotInt)+" is an integer.") #confirm that the input was an integer print("It's up to you to provide other code to see if the integer is between 1 and 10.") print() print("Now lets try vetting a floating point number.") #your function goes up here def get_a_float(Str_message): while True: try: Flt_gotFloat = float(input(Str_message)) except ValueError: print("You have to pick a floating point number from 1 to 100.") inmsg=("Please pick a decimal number from 1 to 100.") continue else: return Flt_gotFloat break #and your process code goes down here Flt_decimalNum = get_a_float("Pick a number from 1 to 100. ") print(str(Flt_decimalNum)+" is a floating point number.") #you have to write the code now to see if it is between 1 and 100