Python编程:从入门到实践------第7章:用户输入和while循环

一、函数input()的工作原理

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

例如以下代码:

message=input("Please tell me something.\n")
print(message)

输出如下:

Please tell me something.
abc
abc

其中第一个abc为你的输入(可为任意值)

注意:使用input()时,Python将用户输入解读为字符串。若想输出数值,可通过int()。

动手试一试7-1 – 7-3

#7-1

car=input("Which car do you want to rent?")
print("Let me see if I can find a "+car+"\n")


#7-2

number=input("How many people?")
if int(number)>8:
    print("We don't have enough tables.")
else:
    print("Welcome!")
print("\n")


#7-3

num=input("Please input a number:")
if int(num)%10:
    print("no")
else:
    print("yes")

输出:

Which car do you want to rent?bmw
Let me see if I can find a bmw

How many people?9
We don't have enough tables.


Please input a number:12
no

二、while循环

1.使用while循环

运行如下代码:

number=1
while number<=5:
    print(number)
    number+=1

输出如下:

1
2
3
4
5

2.break与continue语句

break语句为退出整个循环,执行下面的语句。
continue语句为退出该次循环,回到循环判定条件。

动手试一试 7-4 – 7-7

#7-4

pizza=input("Please input a kind of food or input 'quit':")
while pizza!='quit':
    print("We will add "+pizza +" in your pizza")
    pizza=input("Please input a kind of food or input 'quit':")


#7-5

while True:
    age = int(input("How old are you? "))
    if age < 3:
        print("free")
    elif age >= 3 and age < 12:
        print("10 dollars")
    elif age >= 12:
        print("15 dollars")


#7-6 7-7

#略

输出如下:

Please input a kind of food or input 'quit':eggs
We will add eggs in your pizza
Please input a kind of food or input 'quit':meat
We will add meat in your pizza
Please input a kind of food or input 'quit':quit
How old are you? 2
free
How old are you? 5
10 dollars
How old are you? 15
15 dollars

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

for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。

1.在列表之间移动元素

假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,将其移入另一个已验证的用户列表中,代码如下:

unconfirmed_users=['zhansan','lisi','wangwu']
confirmed_users=[]

while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("Verifying user:"+current_user)
    confirmed_users.append(current_user)

print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user)

输出如下:

Verifying user:wangwu
Verifying user:lisi
Verifying user:zhansan

The following users have been confirmed:
wangwu
lisi
zhansan

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

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

print(pets)

输出如下:

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

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

responses = {}
active = True
while 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 resond?(y/n)")
    if repeat == 'y':
        continue
    elif repeat == 'n':
        break
print("\n--- Poll Results ---")

for name,response in responses.items():
    print(name+" would like to climb "+response+".")

输出如下:

What is your name?liming
Which mountain would you like to climb someday?a
Would you like to let another person resond?(y/n)y

What is your name?zhanghua
Which mountain would you like to climb someday?b
Would you like to let another person resond?(y/n)n

--- Poll Results ---
liming would like to climb a.
zhanghua would like to climb b.

动手试一试 7-8 — 7-10

#7-8

sandwich_orders=["a","b","c"]
finished_sandwiches=[]

while sandwich_orders:
    sandwich = sandwich_orders.pop()
    finished_sandwiches.append(sandwich)
    print("I made your "+sandwich+" sandwich.")


#7-9

sandwich_orders = ["a","pastrami","c","pastrami","pastrami","b"]
print("The pastrami was sold out.")
while "pastrami" in sandwich_orders:
    sandwich_orders.remove("pastrami")
print(sandwich_orders)


#7-10

travel_places = {}
while True:
    name = input("What is your name?")
    travel_places[name] = input("Where do you want to travel?")
    judge = input("Do you want to repeat?(y/n)")
    if judge == 'y':
        continue
    elif judge == 'n':
        break
for name,place in travel_places.items():
    print(name + " want to travel to " +place+".")

输出如下:

I made your c sandwich.
I made your b sandwich.
I made your a sandwich.

The pastrami was sold out.
['a', 'c', 'b']

What is your name?Liming
Where do you want to travel?Pairs
Do you want to repeat?(y/n)y
What is your name?Zhangsan
Where do you want to travel?Beijing
Do you want to repeat?(y/n)n
Liming want to travel to Pairs.
Zhangsan want to travel to Beijing.
Python编程:从入门到实践------第7章:用户输入和while循环Python编程:从入门到实践------第7章:用户输入和while循环 Landing guy_964 发布了6 篇原创文章 · 获赞 0 · 访问量 345 私信 关注
上一篇:# python编程从入门到实践 作业7


下一篇:JDK动态代理Demo代码,进一步学习分析