python学习笔记之(三)7.1用户输入

1.函数input()可以让程序暂停,等待用户输入一些文本。获取到用户输入之后,将其存入一个变量之中,方便你之后的调用。

message = input("please input somthing, and I will repeat in back to you :")
print(message)
----------
result:
    please input somthing, and I will repeat in back to you :1
    1

2.使用input函数返回的是字符串类型的数据, 不能与整形的数据比较。若你试图让用户输入的数据与某一数值比较的话,可调用函数int().有点类似于C语言中强转的意味,把input返回的数据类型强转为整形数据。
示例1.

age = input("How old are you: ")
age  = int(age)
if age >= 18:
    print("True")
----------
Result:
    How old are you: 19
    True

示例2.

height = input("How tall are you, in inches?")
height = int(height)
if height > 37:
    print("\nYou're tall enough to ride.")
else:
    print("\nYou're too short to ride.")
----------
Result:
    How tall are you, in inches?88

    You're tall enough to ride.

3.求膜·运算符(%取余)

4.使用while循环
示例1.当用户输入“quit”时,退出程序。while是一个等待循环,若输入的为‘quit’则跳过while循环内容,程序结束。

prompt = "\nTell me something, Enter 'quit' to end the program: "
message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)
----------
Result:
    Tell me something, Enter 'quit' to end the program: aaaa
    aaaa

    Tell me something, Enter 'quit' to end the program: quit
    Process finished with exit code 0

程序中有很多不同的情况会阻止程序运行,若都用while + and 判断太蠢了。此时,我们可以设置一个标志位,while只需判断该标志位即可做出判断。
示例2.

prompt = "\nTell me something, Enter 'quit' to end the program: "
flag = False
while flag != True:
    message = input(prompt)
    if message != 'quit':
        print(message)
    else:
        flag = Tru
----------
Result:
    Tell me something, Enter 'quit' to end the program: jj
    jj

    Tell me something, Enter 'quit' to end the program: quit

    Process finished with exit code 0

**4.使用break退出循环
break可退出当前循环,执行循环之后的代码。
示例1.**

prompt = "\n Please 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(city.title())

----------
Result:
    Please enter the name of a city you have visited:
    (Enter 'quit' when you are finished) aaaa
    Aaaa

    Please enter the name of a city you have visited:
    (Enter 'quit' when you are finished)quit

    Process finished with exit code 0

continue 跳出当前循环并返回到到循环开头

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值