Python之用户输入和while循环

本文详细讲解了Python编程中用户输入的处理方法,包括input()函数的使用、数值转换、求模运算及在不同版本Python中的输入处理。此外,深入解析了while循环的工作原理,比较了与for循环的区别,展示了如何控制循环流程、处理列表和字典等数据结构。
摘要由CSDN通过智能技术生成

第七章 用户输入和while循环

7.1 函数input()的工作原理

7.1.1 编写清晰的程序
在使用函数input()时,在编写提示语时,通过在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处。

有时候,提示可能超过一行,在这种情况下,可将提示存储到一个变量中,再将该变量传递给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 + "!")

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

在使用input()函数时,Python将用户输入解读为字符串,要将其转化为数字,可使用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.")

7.1.3 求模运算符

求模运算符(%),用于将两个数相除并返回余数。

例如:判断用户输入是奇数还是偶数

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.")

7.1.4 在Python2.7中获取输入

如果使用Python2.7的话,要获取输入应使用raw_input()来提示用户输入。

若使用input(),Python将会将用户的输入解读为Python代码

7.2 while循环简介

while循环与for循环的区别:

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

7.2.1 使用while循环

简单while循环示例:

current_number = 1

while current_number

        print(current_number)

        current_number += 1

7.2.2 让用户选择何时退出

在使用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)

7.2.3 使用标志

在需要考虑很多条件都会导致程序停止运行时,可以使用标志来解决问题,通过使用标志来解决while循环中对条件的设置。

例如:

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)

7.2.4 使用break来退出循环

对于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() + "!")

注意:在任何Python循环中都可以使用break语句,例如,可使用break 语句来退出遍历列表或字典的for 循环

7.2.5 在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句

例如:打印1到10中的奇数

current_number = 0

while current_number < 10:

        ❶ current_number += 1

        if current_number % 2 == 0:

                continue

        print(current_number)

7.2.6 避免无限循环

在使用while循环时,要设置相应的退出条件。若未设置相应的退出条件,程序将陷入无限循环,如果程序陷入无限循环,可按Ctrl+ C,也可关闭显示程序输出的终端窗口。

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

7.3.1 在列表之间移动元素

在列表间移动元素,可使用while循环。

例如:

❶ unconfirmed_users = ['alice', 'brian', 'candace']

confirmed_users = []

❷ while unconfirmed_users: _

        ❸ current_user = unconfirmed_users.pop()

        print("Verifying user: " + current_user.title())

        confirmed_users.append(current_user)

        print("\nThe following users have been confirmed:")

for confirmed_user in confirmed_users:

        print(confirmed_user.title())

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

要删除包含特定值的所有列表元素,可使用while循环来删除。

例如:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']

print(pets)

while 'cat' in pets:

        pets.remove('cat')

print(pets)

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

如果要填充字典,可以使用while语句与input语句的结合来填充字典或列表

例如:

responses = {}

polling_active = True

while polling_active:

        name = input("\nWhat is 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 Results ---")

❹ for name, response in responses.items():

        print(name + " would like to climb " + response + ".")

7.4 总结

在本章中

  • 介绍了如何在程序中使用input() 来让用户提供信息
  • 介绍了如何处理文本和数字输入
  • 介绍了如何使用while 循环让程序按用户的要求不断地运行
  • 介绍了多种控制while 循环流程的方式:设置活动标志,使用break 语句以及使用continue 语句
  • 介绍了如何使用while 循环在列表之间移动元素
  • 介绍了如何从列表中删除所有包含特定值的元素;
  • 介绍了如何结合使用while 循环和字典。
  • 22
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值