美文网首页
9 用户输入input() 和 while循环

9 用户输入input() 和 while循环

作者: 陪伴_520 | 来源:发表于2019-01-02 10:57 被阅读0次

如何实现用户输入?

!以后运行结果不在展示,实践出真知,建议自己运行一遍!

words = "Tell me something, and I will repeat it back to you: "
message = input(words)
print(message)
#那就是input()函数 --- 括号里是你所呈现给用户的提示
#这里的 message 是存放用户输入的变量

甚至是很长的语句也可以写得很简洁

words = "If you tell me who you are, we can personlize the message you see."
words += "\nWhat's your first name?"   #这儿用到了一个字符串相加
message = input(words)
if message == 'zhao':
    print("You must very NB!")
else:
    print("Hello, Mr(s)." + message.title())

对于数值型输入,input()函数是默认作为字符串类型输出的

old = input("How old are you?")
old                            #例如输入是24 ,则old带引号的‘24’
#如果我们要作为数字使用old,【会出错】
if old > 18:
    print("You are Adult")
else:
    print("You are not Adult")

我们需要把数字型输入转换一下类型

old = input("How old are you? ")
old = int(old)   #转换成int类型
if old > 18:
    print("You are Adult")
else:
    print("You are not Adult")

求模运算 --- 有时候叫取余运算 %

4 % 3   #就是取 4 / 3 的余数,结果应该是 1 

求模运算有很多用处——例如可以判断数字的奇偶

number = input("Input a number, I'll tell you if it's even or odd: ")
number = int(number)    #这一步不要忘记
if number % 2 == 0:
    print(str(number) + " is even.")
else:
    print(str(number) + " is odd.")

while循环 —— 首先看一个最基本的while循环

current_number = 0
while current_number < 520:
    current_number += 99
    print(current_number)   #从 0 到 520 需要 6 个 99🤭

更好的提示用户退出条件

prompt = "\nTell me something about your annoyance: "
prompt += "\nEnter 'q' to end the program."
message = ""   #先定义一个message以进入循环
while message != 'q':
    message = input(prompt)
    print("I just want to give you a hug.") #即使你输入q了,循环还得走一遍
注意这个程序最后退出了还是会输出一次, 怎么办呢?

来看这个上面程序的改良版

prompt = "\nTell me something about your annoyance: "
prompt += "\nEnter 'q' to end the program."
message = ""   #先定义一个message以进入循环
while message != 'q':
    message = input(prompt)
    if message != 'q':
        print("I just want to give you a hug.")
 #加个判断,只有输入不是q的时候才输出这句话

循环条件最好使用 【标志】,请看下面的对上面的改改良版!

prompt = "\nTell me something about your annoyance: "
prompt += "\nEnter 'q' to end the program."
active = True   #这会让你和别人都容易看懂
while active:
    message = input(prompt)
    if message == 'q':
        active = False
    else:
        print("I just want to give you a hug.") 

使用 break 退出整个循环 --- 终极改良版!

prompt = "\nTell me something about your annoyance: "
prompt += "\nEnter 'q' to end the program."
active = True   
while active:
    message = input(prompt)
    if message == 'q':
        break   #如果条件成立,直接退出循环
    else:
        print("I just want to give you a hug.") 

使用 continue 退出本次循环 --- 输出奇数的例子

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:   #如果当前数对 2 取余为0
        continue                  #跳过这次循环,进行下一次循环
    print(current_number)

使用while循环来处理字典和列表

1 在列表之间移动

一个 验证用户 的例子
#首先创建一个等待验证用户的列表
#以及一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

#下面验证每一个用户,直到没有未验证的用户为止
#将每个经过验证的列表都【移到】已验证用户列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
#pop()函数还记得吗?它是从末尾开始 弹出列表元素
    
    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user) 
#append()函数还记得嘛?它是从末尾开始增加列表元素

#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

2 删除包含特定值的所有列表元素

#我们要删除一个宠物列表里的【鱼】的例子
pets = ['cat', 'dog', 'cat', 'goldfish', 'rabbit', 'goldfish', 'dog']
 #假设列表里有重复元素
print(pets)

while 'goldfish' in pets:
    pets.remove('goldfish') #还记得remove()函数吗?它是按指定名称来删除数组元素
    
print(pets)

3 使用用户输入来填充字典

一个调查问卷的例子
responses = {} #一个待存储的空字典

    #设置一个标志,指出调查是否继续
polling_active = True

while polling_active:
    name = input("\nWhat's your name?") #这是循环,换行一般放在开头
    response = input("Which mountain would you like to climb someday?")
    
    #将答案存储在字典中
    responses[name] = response         #注意存储键-值对的形式
    
    #询问是否还有人参与调查
    repeat = input("Would you like to let another person respond?(yes/no)")
    if repeat == 'no':
        polling_active = False
        
    #显示调查结果
print("\n--- Poll Result ---")
for name, response in responses.items():   
    #还记得items()函数嘛?它是用于输出字典的键-值对
    print(name.title() + " would like to climb " + response + ".")

7323e0ca37540f95c27d09e35016ce2c.jpg

相关文章

网友评论

      本文标题:9 用户输入input() 和 while循环

      本文链接:https://www.haomeiwen.com/subject/henalqtx.html