-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_input_while_loops.py
More file actions
319 lines (229 loc) · 9.64 KB
/
Copy pathuser_input_while_loops.py
File metadata and controls
319 lines (229 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
"""This is where I'm going to be working on the user input and while loops
section of the Python book."""
import os
def clear():
"""Clear terminal text."""
os.system('clear')
clear()
# The input() function pauses your program and waits for the user to enter some text.
# Once python receives the user's input, it assigns it to a variable to make it easier to work with.
#!!NOTE: SUBLIME TEXT AND MANY OTHER TEXT EDITORS DON'T RUN PROGRAMS THAT ASK THE USER FOR INPUT!!
#I'm going to use GitHub for this, most likely, and just paste the code here when it's done.
message = input("tell me something, and I'll repeat it back to you: ")
print(message)
# Each time you use the input function you should include a clear, easy to
# follow prompt that tells the user exaxctly what kind of info you're looking for.
# It's also good practice to have a colon and/or a space so that it's clear to the
# user where to type.
name = input("Please enter your name: ")
print(f"Hello {name}!")
# Sometimes you'll want to write a prompt that's longer than one line. You can assign your
# prompt to a variable and pass that variable to the input function. This allows you to build your
# prompt over several lines, then include a clean input() statement.
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"Hello {name}!")
# In the example above, the operator += takes the string that was assigned to prompt and
# adds the new string onto the end.
# When you use the input function, Python interprets everthing the user enters as a string.
age = input("How old are you? ")
print(f"You are {age} years old.")
# The user enters their age (a number), but when we ask Python for the value of age,
# it returns the age in quotes (or it would if it wasn't GitHub, I think)
# If all we wanted was to print the input, this is fine, but if we try to use the input
# as a number, we would get an error (again, if it wasn't GitHub, then yeah, I think so)
# When you try to use an input to do a numerical expression, Python produces an
# error because it can't compare a string to an integer. We can fix
# this by using the int() function.
age = input("How old are you? ")
age = int(age)
if age > 10:
print("True")
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 48:
print("\nYou're tall enough to ride!")
else:
print("\nSorry, but you're not tall enough to ride yet.")
# A useful tool for working with numerical info is the modulo operator (%),
# which divides one number by another and returns the remainder.
randoNumber = 4 % 3
print(randoNumber)
randoNumber = 5 % 3
print(randoNumber)
randoNumber = 6 % 3
print(randoNumber)
randoNumber = 7 % 3
print(randoNumber)
# The modulo operator doesn't tell you how many times one number fits into another,
# just what the remainder is.
# When one number is divisible by another number, the remainder is 0, so the modulo operator will
# always return 0. We can use this to determine if a number is even or odd.
number = input("Tell me a number, and I'll tell you if it's even or odd. ")
number = int(number)
if number % 2 == 0:
print(f"The number {number} is even.")
else:
print(f"The number {number} is odd.")
# RENTAL CAR PRACTICE:
rentalCar = input("What kind of car would you like? ")
print(f"Let's see if I can get you a {rentalCar}.")
# RESTAURANT SEATING PRACTICE:
seating = input("How many people are in your dinner group? ")
seating = int(seating)
if seating > 8:
print("I'm sorry, but you have to wait for a table.")
else:
print("Your table is ready!")
# MULTIPLES OF 10 PRACTICE
tenMultiples = input("Give me a number, and I'll tell you if it's a multiple of 10. ")
tenMultiples = int(tenMultiples)
if tenMultiples % 10 == 0:
print("Your number is a multiple of 10.")
else:
print("Your number is not a multiple of 10.")
# While loops run as long as, or while, a certain condition is true.
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
prompt = "\nTell me something and I'll repeat it back to you."
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# For a program that should run only as long as many conditions are true, we can define
# one variable that determines whether or not the entire program is active. This variable,
# called a flag, acts as a signal to the program. We can run our programs so that they run only
# while the value of the flag is set to True.
prompt = "\nTell me something and I'll repeat it back to you. (2nd)"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
prompt = "\nPlease enter the name of every city you have visited "
prompt += "\n(Enter quit when you are done.): "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I would love to go to {city.title()}")
# You can use break to quit a for loop that's working through a list or dictionary as well.
# We can also use the continue statement to return to the beginning of a loop based on the result of
# a conditional test
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue # Returns to start, does not execute ln 172
print (current_number)
# Every while loop needs some way to stop so it doesn't run forever.
x = 1
while x < 5: # This loop will stop after x is 5
print(x)
x += 1
# x = 1
# while x <= 5: # This loop will never end
# print (x)
# Test every while loop to make sure the program stops when it's meant to.
# A least one part of the program can break the loop or make it reach a
# false condition. If a program ever gets stuck in an infinite while loop,
# press ctr-c or close the terminal window.
# Some editors (Sublime Text, etc.) have an embedded output window. In this case,
# the editor might have to be closed to end the loop. Try clicking in the output
# window of the editor before pressing ctr-c, and the loop should cancel.
# PIZZA TOPPINGS PRACTICE
while True:
toppings = input("What topping do you want to add to your pizza? To stop, type in 'quit'. ")
if toppings != 'quit':
print(f"I'll add {toppings} to your pizza.")
else:
break
# MOVIE TICKETS PRACTICE
while True:
ticket_price = input("How old are you (Enter 'quit' when done)? ")
if ticket_price == 'quit':
break
elif int(ticket_price) < 3:
print("Your ticket is free.")
elif int(ticket_price) >= 3 and int(ticket_price) < 12:
print("Your ticket will cost $10.")
elif int(ticket_price) > 12:
print("Your ticket will cost $15.")
# To keep track of users and info, we need to use lists / dictionaries with our while loops.
# A for loop is effective for looping through a list, but you shouldn't modify a list inside
# a for loop because Python will have trouble keeping track of the items in the list.
# To modify a list as you work through it, use a while loop, which will allow you to collect,
# store, and organize lots of input to examine and report on later.
# You can also use remove() in a while loop.
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
# You can prompt for as much input as you need in each pass through a while loop.
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("What is your name? ")
response = input("What mountain would you like to climb? ")
# Store the response in the dictionary.
responses[name] = response
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond (yes / no)? ")
if repeat == 'no':
polling_active = False
# Polling is complete, show the results.
print("\n--Poll Results--")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
# DELI PRACTICE
sandwich_orders = ['veggie', 'grilled cheese', 'turkey', 'roast beef']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print(f"I'm working on your {current_sandwich} sandwich.")
finished_sandwiches.append(current_sandwich)
print("\n")
for sandwich in finished_sandwiches:
print(f"I made a {sandwich} sandwich.")
# NO PASTRAMI PRACTICE
sandwich_orders = [
'pastrami', 'veggie', 'grilled cheese', 'pastrami',
'turkey', 'roast beef', 'pastrami']
finished_sandwiches = []
print("I'm sorry, we're all out of pastrami today.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print("\n")
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print(f"I'm working on your {current_sandwich} sandwich.")
finished_sandwiches.append(current_sandwich)
print("\n")
for sandwich in finished_sandwiches:
print(f"I made a {sandwich} sandwich.")
# DREAM VACATION PRACTICE
polling = True
responses = {}
while polling:
name = input("What's your name? ")
response = input("If you could go to any place right now, where would it be? ")
# Add name and response to the dictionary
responses[name] = response
poll_again = input("Will anyone else be taking this poll (yes / no)? ")
if poll_again == 'no':
polling = False
print("\n---Poll Results---")
for name, response in responses.items():
print(f"\n{name} would like to go to {response}")