您的位置:首页 > 编程语言 > Python开发

Python编程:从入门到实践 学习笔记 基础知识(五)用户输入与While循环

2018-08-14 17:30 786 查看

写在前面:原书地址:http://www.ituring.com.cn/book/1861(图灵社区)

                 本博客是对书籍学习而进行总结的学习笔记,如有侵权行为必删。

1.函数input( )

可以让程序暂停运行,等待用户输入一些文本。

[code]name = input("Please enter your name")
print("Hello," name + "!")

#输出结果
Please enter your name: mama
Hello,mama!

2.求模运算符%

将两个数字相除并返回余数

4%3 = 1

6%3 = 0

3.While循环

不断运行,直到制定条件不满足为止。

[code]ads = 1
while ads <= 5:
print(ads)
ads += 1

#输出结果
1
2
3
4
5

使用break退出循环

[code]ads = "\nPlease enter the name of a city you have visited:"
ads += "\n(Enter 'quit' when you are finished.)"

while True
city = input(ads)

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.) New York
I'd love to go to New York!

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.) quit

输入 quit 执行break语句,导致Python退出循环。

 

使用continue

[code]ads = 0
while ads < 10:
ads += 1
if ads % 2 == 0:
continue

print(ads)

#输出结果
1
3
5
7
9

if语句检查ads与2求模的运算结果,为0,执行continue语句。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐