用户输入
iuput()函数,接受一个参数:向用户显示的提示或说明,让用户知道该如何做。
name=input("Please enter your name:")
print("Hello, "+name+"!")
输出结果
Please enter your name:Yang
Hello, Yang!
当提示超过一行,可以将提示存储在一个变量中,再将该变量传递传递给函数input()。
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("Hello, "+name+"!")
输出结果
If you tell us who you are, we can personalize the messages you see.
What is your first name?Yang
Hello, Yang!
int将字符串转换为数值
age=input("How old are you?")
age=int(age)
print(age>18)
输出结果
How old are you?22
True
求模运算符%,将两个数相除并返回余数
print(4%3)
输出结果
1
while循环
number=1
while number<=5:
print(number)
number+=1
输出结果
1
2
3
4
5
使用break
prompt="If you tell us who you are, we can personalize the messages you see."
prompt+="\nWhat is your first name?"
while True:
name=input(prompt)
if name=='quit':
break
else:
print("Hello, "+name+"!")
输出结果
If you tell us who you are, we can personalize the messages you see.
What is your first name?Yang
Hello, Yang!
If you tell us who you are, we can personalize the messages you see.
What is your first name?Liu
Hello, Liu!
If you tell us who you are, we can personalize the messages you see.
What is your first name?quit
使用continue
number=0
while number<=5:
number+=1
if number%2==0:
continue
print(number)
输出结果
1
3
5
使用while循环来处理列表和字典
pets=['fish','dog','rabbit','fish','cat']
print(pets)
while 'fish' in pets:
pets.remove('fish')
print(pets)
输出结果
['fish', 'dog', 'rabbit', 'fish', 'cat']
['dog', 'rabbit', 'cat']