python你如何让用户循环输入_Python 用户输入和循环的学习

用户输入

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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值