用户输入和while循环
一.用户输入
1.input()函数多行输入
prompt="If you tell us who you are,we can personalize the messages you see."
prompt +="\nWhat is you first name?"
name = input(prompt)
print('\nHello, ' + name + "!")
If you tell us who you are,we can personalize the messages you see.
What is you first name?John
Hello, John!
2.input()返回值
input()将传入的信息作为字符串类型,若传入数值,在进行比较大小、逻辑运算时,需要用int()函数转化为数值型。
height=input("How tall are you, in inches?")
height=int(height)
if height >= 36:
print("\nyou're tall enough to ride!"
else:
print("\nYou'll be able to ride when you're a little older.")
How tall are you, in inches?45
you're tall enough to ride!
3.使用用户输入来填充字典
responses={}
polling_active = True
while polling_active:
name = input("\nWhat's your name?")
response = input('Which mountain would you like to climb someday?')
responses[name] = response
repeat = input("Would you like to let another person respond?(yes/no) ")
if repeat == 'no':
polling_active = False
print('\n---Poll Results---')
for name,response in responses.items():
print(name + "would like to climb " + response + ".")
What's your name?Eric
Which mountain would you like to climb someday?Denali
Would you like to let another person respond?(yes/no) yes
What's your name?Lynn
Which mountain would you like to climb someday?Devil's Thumb
Would you like to let another person respond?(yes/no) no
---Poll Results---
Ericwould like to climb Denali.
Lynnwould like to climb Devil's Thumb.
二.退出while循环
1. 设置判断条件
promt = "\nTell me something,and I will repeat it back to you:"
promt +="\nEnter 'quit' to end the program."
message=""
while message != 'quit':
message = input(promt)
print(message)
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.Hello
Hello
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.quit
quit
上面的例子会输出quit,改进:
promt = "\nTell me something,and I will repeat it back to you:"
promt +="r\nEnter 'quit' to end the program."
message=""
while message != 'quit':
message = input(promt)
if message!='quit':
print(message)
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.Hello
Hello
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.quit
2.使用标志
promt = "\nTell me something,and I will repeat it back to you:"
promt +="\nEnter 'quit' to end the program."
active = True
while active:
message = input(promt)
if message == 'quit':
active=False
else:
print(message)
3.使用break退出循环
promt = "\nTell me something,and I will repeat it back to you:"
promt +="\nEnter 'quit' to end the program."
while True:
message = input(promt)
if message == 'quit':
break
else:
print(message)
4.使用continue
输出1-10中偶数
current_number=0
while current_number < 10:
current_number+=1
if current_number%2!=0:
continue
print(current_number)
2
4
6
8
10
若程序陷入无限循环时,按ctrl+c可关闭显示程序输出的终端窗口。