第七章 用户输入和 while 循环

7.1 函数函数input()

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。

例如下面代码

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message 中,接下来的print(message) 将输入呈现给用 户.

7.1.1 编写清晰的程序

指出用户该输入任何信息的提示都行,如下所示:

name = input("Please enter your name: ")
print("Hello, " + name + "!")

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

这便把提示分成两次输出。可以看到的结果是 

imgpng

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

函数input() 时,Python将用户输入解读为字符串。 在有些时候需要进行数字与数字之间的比较,但是字符串和整数无法进行进行比较

这时可使用函数int() ,它让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.")

利用求模运算符便可以编写代码让计算机来分便一个数字是偶数还是奇数。

ps:如果你使用的是Python 2.7,请使用raw_input() 而不是input() 来获取输入。

7.2 while 循环

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

7.2.1 使用使用while 循环

例如下面代码,便从1输出到5,因为条件是<=5

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
7.2.2 让用户选择何时退出

我们可以定义了一个退出值,只要用户输入的不是这个值,程序就接着运行:

prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
    message = input(prompt)
    print(message)

只有用户输入quit,程序才会结束。但是其中quit也会输出 如果想要其不输出可以加入一个if测试,如

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)
    if message != 'quit':
        print(message)
7.2.3 使用标志
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
active = True
while message != 'quit':
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

如上面的代码,增加了标志active,只要它的值是True就会一直运行下去。

7.2.4 使用使用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() + "!")

只要以输入quit,程序就会立即退出。

7.2.5 在循环中使用 在循环中使用continue

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

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

只要变量的值是偶数便会跳过,从新回到循环的开头,所以输出的结果是1到10的奇数。

7.2.6 避免无限循环
x = 1
while x <= 5:
    print(x)
    x += 1

如上述的代码如果忘记输入了X+=1,程序便会一直打印1.

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

在循环,中要在遍历列表的同时对其进行修改,可使用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 删除包含特定值的所有列表元素

要删除的值在列表中只出现了一次,可以用remove()方法实现,但是要是出现了多次特定的值,就可以使用while循环。

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

这边可以循环的找出特定元素删除了。

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

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 循环和字典。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值