pythonwhile输出每一个余数_python6-while循环

一、用户输入和while循环

1、函数input()的工作原理:让程序暂停运行,等待用户输入一些文本(字符串),获取用户输入后,python将其存在变量中,方便使用。

input()接受一个参数,即要想用户显示的提示或说明,让用户知道该怎么做。

* 有时提示超过一行,可以使用拼接方式进行输出;

1 prompt="If you tell us who you are,we can personalize the message you see."

2 prompt+="\nWhat is your first name?"

3 name=input(prompt)4 print("\nHello!"+name)

* 使用int()获取数值输入;

height=int(input("Input you height(cm):"))if height>=200:print("You are so tall!")elif(height>=150&&height<200):print("Normal height")else:print("short")

* 求模运算符%:返回两数相除后的余数。

- 若可被整除,余数为0,反则输出余数;

- 可用于判断一个数是奇数还是偶数;

1 number=int(input("Enter a number ,I'll tell you if it's even or odd:"))2 if number%2==0:3 print("It's even")4 else:5 print("odd")

二、while循环

for循环用于针对集合中每个元素都一个代码块。而while则是不断运行,直到条件不满足。

1、while循环

1)使用while循环;

2)让用户选择何时退出;

3)使用标志:要求条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否都处于活动状态,该变量被称为标志。这样在while循环中只需检查一个条件,标志当前值是否为True。

1 prompt="Tell me something,and I will repeat it back ti you."

2 prompt+="\nEnter 'quit' to end the program."

3 active=True4 whileactive:5 message=input(prompt)6 if message=='quit':7 active=False8 else:9 print(message)

4)使用break退出循环——直接退出整个循环(可用于退出遍历列表/字典的for循环)

1 prompt="输入你想去的城市."

2 prompt+="\n输入'quit'退出程序."

3 whileTrue:4 city=input(prompt)5 if city=='quit':6 break

7 else:8 print(city)

5)使用continue在循环中:返回到循环开头,并依据条件测试结果决定是否继续执行循环。

1 #打印0-10中的偶数

2 number=03

4 while number<10:5 number+=1

6 if number%2==0:7 continue

6)避免无限循环

三、使用while循环处理列表和字典

for循环是种遍历列表的有效方式,但for循环中不应该修改列表,否则将导致Python难跟踪其中的元素,故可用while循环将列表和字典组合起来使用,可收集存储并组织大量输入,供以后查看和显示。

1、列表之间移动元素

情况:一个列表包含新注册的用户但还未验证的网站用户:验证这些用户后,将其从未验证的用户列表中提取出来,再将其加入到另一个已验证的用户列表中。

1 #创建待验证用户列表

2 unconfirmed_users=['alice','brian','candace']3 confirmed_users=[]4 #验证每个用户,直到没有未验证的用户为止

5 #将每个经过验证的列表都一道已验证的用户列表中

6 whileunconfirmed_users:7 current_user=unconfirmed_users.pop()8 print("Verfying user:"+current_user.title())9 confirmed_users.append(current_user)10 print("The following users have been confirmed:")11 for confirmed_user inconfirmed_users:12 print(confirmed_user.title())

2、删除包含特定值的所有列表元素

* remove()  删除值在列表中只出现过一次;

* 循环语句配合remove()使用;

1 pets=['dog','cat','duck']2 print(pets)3 while 'cat' inpets:4 pets.remove('cat')5 print(pets)

3、使用用户输入来填充字典

创建一个调查程序,其中的循环每次执行都提示输入被调查者的名字和回答,我们将收集的数据存在一个字典中,以便将回答和调查者关联起来。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值