Webinar: Input Patterns

A look at adjusting our control flow to make sure we get the input, or inputs, in the right amounts and the right data type
 avatar
unknown
python
a month ago
2.8 kB
28
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()
# strList = input() # same in one step
# print(strList)

# 3 Break up a string containing numeric chars into a list of
#       recast ints or floats
# 22 88 32 68
# myInput = input()
# strList = myInput.split()
# print(strList)

# fill the basket
# numList = []
# for num in strList:
#     # recast = int(num)
#     # numList.append(recast)
#     numList.append(int(num))
#
# print(numList)

# optional quick way to do this... a comprehension
# myNewList = [expression for something in container]
# myNewList = [int(num) for num in strList]
# print(myNewList)

# 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 loop to get the next inputs
# # and fill the basket

# var for basket???
# floatList = []
# for num in range(numTimes): # range(0, stop, 1) --> [0, 1, 2, 3, 4]
#     nextInput = float(input())
#     floatList.append(nextInput)
# 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()
myInput = input()

# set up a while loop to see if we should continue after this
# while myInput != "quit": # whatever our sentinel value is
# while myInput != "-1":
#     # do your stuff
#
#     # x += 1
#     myInput = input()

# Variation on this pattern: multiple sentinel values!
# Stop on quit, done, or d

# Use a list for multiple sentinel values
myInput = input()
quitCommands = ["quit", "done", "d"]:

while not myInput in quitCommands:
    # do your stuff
    myInput = input()

# 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



Leave a Comment