《Python从入门到实践》第七章 输入和while

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

intput()函数接受一个参数,即要向用户显示的提示,让用户知道该输入什么样的信息,程序等待用户输入,并在用户按回车键后继续运行,用户的输入被赋给变量

name = input("Please enter your name.\n")
print(f"Hello,{name}")

使用input()函数的时候,应当指定清晰易懂的提示,准确指出希望用户提供什么样的信息

有时候提示超过一行,可以先将提示赋给一个变量,再将这个变量传递给input()函数,这样即便提示超过一行,input()语句也会非常清晰

prompt = ("If you share your name, we can personalize the messages "
          "you see.")
prompt += "\nWhat's your first name?\n"
name = input(prompt)
print(f"Hello,{name}")

在使用input()函数时,Python会将用户输入解读为字符串,这个时候如果试图将输入作为数来使用,就会引发错误。为了解决这个问题,可以使用函数int()将输入的字符串转换为数值,确保能够成功的将输入作为数进行使用。

age = input("How old are you? ")
print(age)
if int(age) > 10:
    print("emmmm")

又例如下面:

height = input("How tall are you, in inches?\n")
height = int(height)

if height >= 48:
    print("\n You're tall enough to ride!")
else:
    print("You'll be able to ride when you're a little order")

所以在将数值输入用于计算和比较前,务必将其转换为数值表示。

求模运算符:%

number = input("Enter a number, and I will tell you it's even "
               "or odd\n")
number = int(number)
if number % 2 == 0:
    print(f"The number {number} is even.")
else:
    print(f"The number {number} is even.")

求模运算符不会指出一个数是另一个数的多少倍,只能指出余数是多少,可以用来判断奇数偶数。

练习7.1

request = input("which kind of car do you want?\n")
print(f"Let me see if I can find you a {request}")

练习7.2

number = input("How many people for this lunch?\n")
number = int(number)
if number >=8:
    print("There is no table left")
else:
    print("welcome here for lunch")

练习7.3

number = input("please input a number\n")
number = int(number)
if number % 10 == 0:
    print(f"{number} 是10的倍数")
else:
    print(f"{number}不是10的倍数")

while循环

current_number = 1
numbers = []
while current_number <= 5:
    numbers.append(current_number)
    print(current_number)
    current_number += 1
print(numbers)

只要条件满足,循环就会进行下去

也可以实现让用户选择何时退出:

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

使用标志:使用一个标记来判断程序是否应该继续运行。

prompt = "Tell me something, and I will repeat it back to you\n"
prompt += "Enter 'quit' to end the program\n"

active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

使用break退出循环:

prompt = "Tell me something, and I will repeat it back to you\n"
prompt += "Enter 'quit' to end the program\n"


while True:
    message = input(prompt)
    if message == 'quit':
       break
    else:
        print(message)

在所有Python循环中都可使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环。

在循环中使用continue:

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

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

避免无限循环:

要避免编写无限循环,务必对每个while循环进行测试,确保它们按照预期那样结束

练习7.4

active = True
while active:
    integrity = input("which integrity you want?\n"
                      "if you have finished booking,"
                      "please enter 'quit'\n")
    if integrity == 'quit':
        print("OK, we will prepare your pizza right now")
        active = False
    else:
        print(f"Add {integrity} into the pizza!")

练习7.5

while True:
    question = "How old are you?\n"
    age = input(question)
    age = int(age)
    if age < 3:
        print("it's free for you, puppy")
    elif 3 <= age <12:
        print("please pay 10 dollars for your ticket")
    else:
        print("please pay 15 dollars for your ticket")

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

for循环是一种遍历列表的有效方式,但不应该在for循环中修改列表,否则将导致Python难易跟踪其中的元素,要在遍历列表的同时修改它,可使用while循环。通过将while循环与列表和字典结合起来使用,可收集、存储并组织大量的的输入,供以后查看和使用。

①在列表之间移动元素

将一个列表的元素移动到另外一个列表当中

unconfirmed_users = ['zhong', 'xiong', 'mike']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print(f"Verifying user:{current_user}")
    confirmed_users.append(current_user)

print("The following users have been verified:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

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

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

③使用用户输入充填字典

可以使用while循环提示用户输入任意多的信息

responses = {}
polling_active = True
while polling_active:
    name = input("What's your name?\n")
    response = input("Which dish you like most?\n")
    responses[name] = response
    repeat = input("Would you like to another person respond?"
                   "\n(yes/no)")
    if repeat == 'no':
        polling_active = False
    else:
        polling_active = True

for name, response in responses.items():
    print(f"{name.title()}'s favorite dish is {response}.")

练习7.8:

sandwish_orders = ['fish sandwish', 'vegetable sandwish',
                   'beef sandwish']
finished_sandwiches = []
while sandwish_orders:
    sandwish_order = sandwish_orders.pop()
    finished_sandwiches.append(sandwish_order)
    print(f"I have finished your {sandwish_order}.")

print(f"\n{finished_sandwiches}")

练习7.9:

sandwish_orders = ['fish sandwish', 'pastrami','vegetable sandwish',
                   'beef sandwish', 'pastrami', 'pastrami']
print("No pastrami left")
while 'pastrami' in sandwish_orders:
   sandwish_orders.remove('pastrami')

print(f"\n{sandwish_orders}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值