首页 > 编程 > Python > 正文

Python -- 5. 用户输入和while 循环

2019-11-08 01:19:45
字体:
来源:转载
供稿:网友

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)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表