Python Crash Course 7 - Input and While
I’m YouKoutaku. These codes are from the book python_Crash_Course, 2nd edition. I learned python and took these notes for this book.
7.Input and While
7.1 input()
input(prompt)
1
2
message = input("Tell me something, and I will repeat it back to you:")
print(message)
1
Yes
7.1.1
1
2
name = input("Please enter your name:")
print(f"\n Hello,{name}!")
1
Hello,Yang Guangze!
1
2
3
4
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\n What is your first name?"
name = input(prompt)
print(f"\nHello,{name}!")
1
Hello,Eric!
1
2
3
4
5
### input() to get int number
age = input("How old are you?")
print(type(age))
age = int(age)
print(type(age))
1
2
<class 'str'>
<class 'int'>
1
2
# %= reminder
4%3
1
1
7.2 while loop
7.2.1 sample
1
2
3
4
5
num = 1
while num <= 5:
print(num)
num +=1
1
2
3
4
5
1
2
3
4
5
7.2.2 exit loop
1
2
3
4
5
6
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
message = ""
while message != 'quit':
message = input(prompt)
print(message)
1
2
3
4
Y
Yang
Hello
quit
1
2
3
4
5
6
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
1
2
3
Y
Yang
Hello
7.2.3 use flag in while
1
2
3
4
5
6
7
8
9
10
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
1
2
3
4
5
6
Hello
can
you
here
me
Ok
7.2.4 break in loop
1
2
3
4
5
6
7
8
9
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
while True:
message = input(prompt)
if message == 'quit':
break
else:
print(message)
1
2
3
4
5
H
e
l
l
o
7.2.5 continue in loop
1
2
3
4
5
6
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue
print(num)
1
2
3
4
5
1
3
5
7
9
7.2.6 avoid infinity loop
1
2
3
x = 1
while x < 5:
print(x)
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
1
1
1
1
1
.
.
.
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Input In [22], in <cell line: 2>()
1 x = 1
2 while x < 5:
----> 3 print(x)
File c:\Users\ygz19\AppData\Local\Programs\Python\Python310\lib\site-packages\ipykernel\iostream.py:528, in OutStream.write(self, string)
518 def write(self, string: str) -> Optional[int]: # type:ignore[override]
519 """Write to current stream after encoding if necessary
520
521 Returns
(...)
525
526 """
--> 528 if not isinstance(string, str):
529 raise TypeError(f"write() argument must be str, not {type(string)}")
531 if self.echo is not None:
KeyboardInterrupt:
7.3 using while to process list and dictionary
7.3.1 move the element in list
1
2
3
4
5
6
7
8
9
10
11
12
13
#stack: first in,last out
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
print("\nThe following users hav been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
1
2
3
4
5
6
7
8
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users hav been confirmed:
Candace
Brian
Alice
7.3.2 deletee all of the elements in list
1
2
3
4
5
6
7
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
1
2
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
7.3.3 using input to add dictionary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
rs = {}
active = True
while active:
name = input("\nWhat is your name?")
r = input("Which mountain would you like to climb someday?")
rs[name] = r
repeat = input("Would you like to let another person respond?(y/n)")
if repeat == 'n':
active = False
print("\n-- Poll Results ---")
for name, r in rs.items():
print(f"{name} would like to climb {r}.")
1
2
3
-- Poll Results ---
Y would like to climb L.
yang would like to climb l.
This post is licensed under CC BY 4.0 by the author.