Python -- 5. 用户输入和while 循环
来源:互联网 发布:java concurrent书籍 编辑:程序博客网 时间:2024/06/06 00:42
1. 函数input() 的工作原理
函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中.
message = input("Tell me something, and I will repeat it back to you: ")print(message)
(1). 使用int() 来获取数值输入
使用函数input() 时,Python将用户输入解读为字符串。
>>> age = input("How old are you? ")How old are you? 21>>> age'21'
函数int() 将数字的字符串表示转换为数值表示
height = input("How tall are you, in inches? ")height = int(height)if height >= 36: print("\nYou're tall enough to ride!")else: print("\nYou'll be able to ride when you're a little older.")
(2).求模运算符
处理数值信息时,求模运算符 (%)是将两个数相除并返回余数
number = input("Enter a number, and I'll tell you if it's even or odd: ")number = int(number)if number % 2 == 0: print("\nThe number " + str(number) + " is even.")else: print("\nThe number " + str(number) + " is odd.")
2. while 循环简介
(1).使用while 循环
current_number = 1while current_number <= 5: print(current_number) current_number += 1
(2).使用break 退出循环
要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。
prompt = "\nPlease enter the name of a city you have visited:"prompt += "\n(Enter 'quit' when you are finished.) "while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")
(3).在循环中使用continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用
continue 语句current_number = 0while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number)
0 0
- Python -- 5. 用户输入和while 循环
- Python学习---用户输入和while循环
- 用户输入和while循环(python)
- Python学习笔记(6)-用户输入和while循环
- Python学习笔记(10)- 用户输入和while循环
- Python_用户输入和while循环
- Python学习笔记04-字典和用户输入和 while 循环
- Python编程:从入门到实践读书笔记-7 用户输入和while循环
- 【Python编程:入门到实践】第七章:用户输入和while循环
- Python自学之路第九步——用户输入和while循环
- python笔记-007-★输入和while循环
- python 循环语句while的使用——两种方法输出用户输入的数字
- Python入门到实践(7) -用户输入与while循环
- python while循环和for循环
- Python中的while循环和for循环
- Python中for循环和while循环
- Shell读取用户输入【以及循环读取验证和while循环中添加多个条件[ .. ] &&或者|| [ .. ]】
- python的while和for循环
- Mysql error 1452
- shell编程其实真的很简单(五)
- Python练手项目0015
- java 基础知识
- 浅谈KMP
- Python -- 5. 用户输入和while 循环
- 4475: [Jsoi2015]子集选取
- ps 与 top 对于cpu使用率不一致的问题
- NZT基本介绍
- 使用jaxp对XML文件进行dom解析
- win32api之添加水印
- AfxBeginThread如何安全退出
- [LeetCode]135. Candy
- HDU 2031进制转换