Python -day 7

用户输入和while循环

函数input() :让程序暂停运行,等待用户输入一些文本。接收1个参数:即要向用户显示的提示或说明。
1 >>> message = input("Tell me something, and I will repeat it back to you: ")
2 >>> print(message)
3 Tell me something, and I will repeat it back to you: Hello everyone!
4 Hello everyone!
函数int() :将括号内的参数字符串转换为数值。
1 >>> age = input("How old are you? ")
2 >>> print(age)
3 
4 >>> age = int(age)
5 >>> print(age >= 18)
6 How old are you? 21
7 21
8 True
求模运算符(%):将两个数相除并返回余数。
while循环:
使用break语句退出循环。
 1 >>> prompt = "\nPlease enter the name of a city you have visited: "
 2 >>> prompt += "\n(Enter 'quit' when you are finished.)"
 3 >>> while True:
 4 >>>     city = input(prompt)
 5 >>>     if city == 'quit':
 6 >>>         break
 7 >>>     else:
 8 >>>         print("I'd love to go to " + city.title() + "!")
 9 Please enter the name of a city you have visited: 
10 (Enter 'quit' when you are finished.)New York
11 I'd love to go to New York!
12 
13 Please enter the name of a city you have visited: 
14 (Enter 'quit' when you are finished.)quit
使用continue语句:不再执行余下的代码,返回到循环的开头并根据条件测试结果决定是否继续执行循环。
 1 >>> current_number = 0
 2 >>> while current_number < 10:
 3 >>>     current_number += 1
 4 >>>     if current_number % 2 == 0:
 5 >>>         continue
 6 >>>     print(current_number)
 7 1
 8 3
 9 5
10 7
11 9
使用while循环来处理列表和字典;
1 >>> pets = ['peg', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
2 >>> print(pets)
3 >>> while 'cat' in pets:
4 >>>     pets.remove('cat')
5 >>> print(pets)
6 ['peg', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
7 ['peg', 'dog', 'goldfish', 'rabbit']

转载于:https://www.cnblogs.com/Molzx/p/10502820.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值