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

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 = 1
while 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 = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值