Webinar Input Patterns
A look at some commons things we might do with strings from input(), and making sure we call input() the right number of times.unknown
python
2 months ago
2.6 kB
51
Indexable
# Webinar Input Patterns # input() ALWAYS returns a string # Some common patterns... # 1 Recast a numeric string into an int or float # 2 Breaking up a long string into a list of smaller strings # 3 Break up a string containing numeric chars into a list of # recast ints or floats # 4 One value tells you how many times to call input() # 5 We DON'T KNOW how many times to call input(), but we know # a sentinel value to stop # 1 Recast a numeric string into an int or float # myVar = int(input()) # float(input()) # print(type(myVar).__name__) # 2 Breaking up a long string into a list of smaller strings # "Pat Silly Doe" or "Julia Clark" # myVar = input() # strList = myVar.split() # print(strList) # 3 Break up a string containing numeric chars into a list of # recast ints or floats # 22 88 32 68 # myVar = input() # strList = myVar.split() # print(strList) # fill the basket # numList = [] # for num in strList: # # recast = int(num) # # numList.append(recast) # numList.append(int(num)) # print(numList) # 4 One value tells you HOW MANY TIMES to call input() # Any "known number of times" means a for loop # 5 # 30.0 # 50.0 # 10.0 # 100.0 # 65.0 # call input() to get the number of times # numTimes = int(input()) # # # set up a for loop to get the next inputs # # and fill a basket if needed # # floatList = [] # for num in range(numTimes): # [0, 1, 2, 3, 4] # # get the input # # nextInput = float(input()) # # floatList.append(nextInput) # floatList.append(float(input())) # print(floatList) # 5 We DON'T KNOW how many times to call input(), but we know to stop on some SENTINEL VALUE # this is a WHILE loop condition # get the first input() myVar = input() # set up a while loop to see if we should continue after this # while myVar != "quit": # whatever the sentinel value to stop is while myVar != "-1": # do your stuff # x += 1 myVar = input() # What if we had multiple sentinel values myVar = input() # create a list of the sentinel values quitCommands = ["quit", "done", "d"] # while loop while not myVar in quitCommands: # do your stuff myInput = input() # To recap our patterns... # 1 Recast a numeric string into an int or float # 2 Breaking up a long string into a list of smaller strings # 3 Break up a string containing numeric chars into a list of # recast ints or floats # 4 One value tells you how many times to call input() # 5 We DON'T KNOW how many times to call input(), but we know # a sentinel value to stop # You'll use variations on these a lot!
Editor is loading...
Leave a Comment