首页 > 其他分享 >第七章:用户输入和while循环

第七章:用户输入和while循环

时间:2023-11-05 23:02:18浏览次数:32  
标签:prompt while 循环 第七章 print input message 输入

函数input()的工作原理

函数input()让程序暂停,一方面打印括号里的内容,并且同时等待用户输入一些文本,获取用户输入后,将其储存在一个变量里,方便你使用。

message=input('tell me something: ')
print(message)

程序等待用户输入,并在用户按回车键后继续运行

编写清晰的程序

每当你使用函数input时,都应指定清晰的提示以告诉用户需要提供什么信息——任何指出用户该输入何种信息都行

message=input('tell me something: ')
print(message)

有时候提示可能超过一行,在这种情况下,可将提示存储在一个变量里,再将这个变量传递给函数input().

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print("\nHello, " + name + "!")



If you tell us who you are, we can personalize the messages you see.
What is your first name? 888

Hello, 888!

使用int()来获取数值输入

使用函数input()时,输入会被解读为字符串

a=input()
a
'23'#输入23

这时你就可以使用int()函数将字符串转化为整数值

a=input()
a=int(a)
a

在实际中使用函数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.")

求模运算符

将两个数相除并返回余数:%,他只会指出余数是多少,而不会显示商

45%8
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.")

上面是一个判断一个数是否是偶数或者奇数的程序

while循环简介

for循环针对集合中的每个元素的一个代码块,而while循环不断地运行,直到条件不满足为止

使用while循环

例如用while循环来数数

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
1
2
3
4
5

初始值为1,每次循环+1,直到值大于5,不再运行程序

让用户选择何时退出

可使用while循环让程序在用户愿意时不断运行,例如下面的例子

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
  
message=''
while message!='quit':
    message = input(prompt)
    print(message)

在这里定义一个message变量,用于储存用户的输入,并给他一个空的字符串,让执行while循环时,有可供检查的东西,在第一次执行while之后,只要输入的不是quit,程序就会一直执行。但是这个程序最后会将quit作为一条消息打印出来。为此我们做如下修改:

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
  
active = True
while active:
    message = input(prompt)
    
    if message == 'quit':
        active = False
    else:
        print(message)

现在程序在执行前会做个简单的检查,仅在消息不是退出值时才打印它

使用标志

先前的程序中只有一个条件来判断程序是否执行,但是如有更多的条件的时候该怎么办呢?

在要求很多条件都满足的时候才继续执行时,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量就叫做标志。当标志为true时运行,并在任何事件导致标志为false时停止运行程序,这样在while语句中就只用检查一个条件——标志是否为true。

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
  
active = True
while active:
    message = input(prompt)
    
    if message == 'quit':
        active = False
    else:
        print(message)

使用break退出循环

要立刻退出while循环,不在运行后面的代码,也不管条件测试的结果如何,就要使用break语句,

prompt = "\nPlease tell me 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() + "!")

以true作为条件的循环将不断运行下去,直到遇见break语句

注意在任何循环中都可使用break语句

在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码

current_number = 0
while current_number <= 13:
    current_number+=1
    if current_number % 2==0:
        continue
    print(current_number)

这里的continue让python忽略余下的代码,并返回到循环的开头

避免无限循环

如果程序陷入无限循环,可以按Ctrl+C。确认程序至少有一个地方能让循环条件为false或者让break语句执行

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

用for循环遍历列表时不能修改列表,要在遍历列表的同时对其进行修改,可使用while循环

# Start out with some users that need to be verified,
#  and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

# Verify each user, until there are no more unconfirmed users.
#  Move each verified user into the list of confirmed users.
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    
    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)
    
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

我们首先创建一个未验证用户列表和一个用于存储已验证的用户,使用while循环和方法pop()来验证未验证用户列表,并将他们添加到已验证用户列表,直到未验证列表为空时,停止验证。

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

使用方法remove()只能够删除在列表中出现一次的元素,如果该元素多次出现,可以使用while循环来一直删除

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
    
print(pets)

在第一次删除cat之后,程序返回到while,再次删除cat,直到cat不在列表里才会停止。

使用用户输入来填充字典

可使用while循环提示用户输入任意数量的信息,下面创建一个调查程序,并把结果储存在一个字典里

responses = {}

# Set a flag to indicate that polling is active.
polling_active = True

while polling_active:
    # Prompt for the person's name and response.
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")
    
    # Store the response in the dictionary:
    responses[name] = response
    
    # Find out if anyone else is going to take the poll.
    repeat = input("Would you like to let another person respond? (yes/ no) ")
    if repeat == 'no':
        polling_active = False
        
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name + " would like to climb " + response + ".")

先设置一个polling_active标志,用来判断调查是否继续。接着通过一个if语句来判断是否还要继续调查,最后把这个字典给打印出来。


标签:prompt,while,循环,第七章,print,input,message,输入
From: https://blog.51cto.com/u_16285896/8196606

相关文章

  • linux 输入长命令行时不会自动换行只会回到行首,并且覆盖前面的内容。解决办法。
    CustomizeCode\e[Begincolorchanges\e[0mExitcolor-changemode0;32mSpecifythecolormodeThefirstnumberinthecolorcodespecifiesthetypeface:•0–Normal•1–Bold(bright)•2–Dim•4–UnderlinedThesecondnumberindicatesthecol......
  • 无涯教程-批处理 - 输入/输出
    有三个通用的"File",用于键盘输入,在屏幕上打印文本和在屏幕上打印错误,"StandardIn"文件,称为stdin,包含程序/脚本的输入。"StandardOut"文件称为stdout,用于写入输出以在屏幕上显示。最后,被称为stderr的"StandardErr"文件包含要在屏幕上显示的所有错误消息。这三个标准......
  • 在 Alacritty 终端中支持输入法
    TL;DR在Wayland下Alacritty对输入法(Fcitx5)支持存在问题,解决方案为设置如下两个环境变量中的任意一个:WAYLAND_DISPLAY=alacrittyWINIT_UNIX_BACKEND=x11启动时默认添加此参数在~/.local/bin(或其他在$PATH中先于/usr/bin/的目录)中添加一个名为alacritty的文件,输入......
  • Python 用户输入和字符串格式化指南
    Python允许用户输入数据。这意味着我们可以向用户询问输入。在Python3.6中,使用input()方法来获取用户输入。在Python2.7中,使用raw_input()方法来获取用户输入。以下示例要求用户输入用户名,并在输入用户名后将其打印在屏幕上:Python3.6:username=input("请输入用户名......
  • Python 用户输入和字符串格式化指南
    Python允许用户输入数据。这意味着我们可以向用户询问输入。在Python3.6中,使用input()方法来获取用户输入。在Python2.7中,使用raw_input()方法来获取用户输入。以下示例要求用户输入用户名,并在输入用户名后将其打印在屏幕上:Python3.6:username=input("请输入用户......
  • while中使用break和continue
    while中使用break和continue:count=0##计数器whileTrue:s=input('请输入内容:')ifs=='退出':print(count)print('退出!')break##退出循环if'生气'ins:print(count)continue##本次循环没结束,要求重新输入......
  • ./rmblastn: error while loading shared libraries: libzstd.so.1: cannot open shar
     001、问题, ./rmblastn命令报错如下:./rmblastn:errorwhileloadingsharedlibraries:libzstd.so.1:cannotopensharedobjectfile:Nosuchfileordirectory 002、解决方法  003、测试  参考:01、https://www.modb.pro/db/429704 ......
  • C++prime之输入输出文件
    作为一种优秀的语言,C++必然是能操作文件的,但是我们要知道,C++是不直接处理输入输出的,而是通过一族定义在标准库中的类型来处理IO的。‘流’和‘缓冲区’‘流’和‘缓冲区’C++程序把输入输出看作字节流,并且其只检查字节流,不需知道字节来自何方。管理输入包括两步:将流与输入去......
  • uniapp微信小程序表单输入框上移事件
    一、问题uniapp制作的微信小程序表单,在使用真机调试时,点击输入框输入内容时,出现输入框上移的情况二、找原因窗体高度固定,导致软键盘弹出时输入框上移三、解决办法1、uniapp官网关于软键盘弹出问题的解决方法在pages.json中配置的写输入框表单的 style"app-plus":{"......
  • [MFC]区分USB扫码枪和键盘输入的实现
    不久前在帮客户做一个生产软件,要用到扫码枪输入一定长度的条码并且有条码长度防呆,结果发现手头的扫码枪居然是模拟键盘输入将条码数据直接发送到焦点控件中的(USB口的扫码枪),比如EditControl,而由于业务要求,不允许生产线上员工手工输入条码内容,因此我将文本框设为只读,想不到扫码枪......