Python用户输入和while循环

用户输入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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值