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']
posted @ 2019-03-09 20:19  Molzx  阅读(150)  评论(0编辑  收藏  举报