用户输入input()
message=input("Tell me your name:")
print(message)
#输出:
Tell me your name:Jick Ma
Jick Ma
使用int()获取数值输入
>>> age=input("How old are you?")
How old are you?23
>>> age
'23'
用户输入的是数字23,但是我们使用变量age的值时,返回的是’21’,用户输入的数值的字符串表示。如果使用以下打印就很明显,Python会引发错误,因为无法将字符串和数值进行比较:
>>> age=input("How old are you?")
How old are you?23
>>> age
'23'
>>> age<30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
为解决这个问题可以使用int() 函数,他让Python将输入视为数值。
>>> age=input("How old are you? ")
How old are you? 23
>>> age=int(age)
>>> age<30
True
求模运算%
求模运算符(%)将两数相除并返回余数:
>>> 5%2
1
>>> 4%2
0
>>> 9%5
4
while循环
current_number=1
while current_number<=4:
print(current_number)
current_number+=1
#结果:
1
2
3
4
使用标志
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)
在代码中添加了一个标志,把这个标志命名为active。如果用户输入’quit’,我们将active设置为False,这时候结束循环。如果不输入’quit’,那么点击Enter 就会一直输出:
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.
使用break退出循环
promt="\nPlease enter the name of a city you have visited:"
promt+="\n(Enter 'quit' when you are finished.)"
while True:
city=input(promt)
if city=='quit':
break
else:
print("I'd love to go to "+city.title()+"!")
输出:
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)LuoYang
I'd love to go to Luoyang!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)BeiJing
I'd love to go to Beijing!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)ShangHai
I'd love to go to Shanghai!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)quit
------------------
(program exited with code: 0)
在循环中使用continue
结束当前循环,但是不结束循环,继续执行
current_number=0
while current_number<10:
current_number+=1
if current_number%2==0:
continue
print(current_number)
输出:
1
3
5
7
9
[Finished in 29ms]