《python编程:从入门到实践的》第七章:用户输入和while循环的例题代码

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

#汽车租赁 :编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如 “Let me see if I can find you a Subaru”
car = input('请问你想租什么车: ')
print('我想租:'+car)
print('--------------------')

#餐馆订位 :编写一个程序,询问用户有多少人用餐。如果超过 8 人,就打印一条消息,指出没有空桌;否则指出有空桌
num = input('请问有几个人: ')
num = int(num)
if num > 8:
    print('抱歉,没有空桌了')
elif num <= 8:
    print('还有空桌')
print('--------------------')

#10 的整数倍 :让用户输入一个数字,并指出这个数字是否是 10 的整数倍。
a = input('请输入数字: ')
a = int(a)
if a % 10 == 0 and a != 0:
    print('是10的整数倍')
else:
    print('不是10的整数倍')

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

#比萨配料 :编写一个循环,提示用户输入一系列的比萨配料,并在用户输入 'quit' 时结束循环。
# 每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料
tiaoliao = '请问你要什么配料: '
active = True
while active == True:
    pizza = input(tiaoliao)
    if pizza == 'quit':
        active = False
    else:
        print('会添加配料'+pizza+'的')

例2:

#电影票 :有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众免费; 3~12 岁的观众为 10 美元;超过 12 岁的观众为 15 美元。
# 请编写一个循环,在其中询问用户的年龄,并指出其票价。

num = '请问你的年龄是多少: '
while True:
    age = input(num)
    age = int(age)
    if age < 3 and age >0:
        print('免费的')
    elif age >= 3 and age <= 12:
        print('10元')
    elif age > 12 and age < 120:
        print('15元')
    else:
        break

例3:

#条件循环和continue的使用
num = ''
while num != 'a':
    num = input('请输入: ')
    if num == 'A':
        continue
    print('你输入了:'+num)

例4:

#熟食店 :创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。
# 遍历列表 sandwich_orders ,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich ,并将其移到列表 finished_sandwiches 。
# 所有三明治都制作好后,打印一条消息,将这些三明治列出来
#并且要删除列表中所有的元素a

sandwich_orders = ['a','c','a','f','a','y']
finished_sandwiches = []
#删除列表中所有的元素a
print('要删除a')
while 'a' in sandwich_orders:
    sandwich_orders.remove('a')

#将列表sandwich_orders移到列表 finished_sandwiches
while sandwich_orders:
    sandwich = sandwich_orders.pop()
    print('I made your:'+sandwich)
    finished_sandwiches.append(sandwich)
for fin in finished_sandwiches:
    print(fin)

例5:

#梦想的度假胜地 :编写一个程序,调查用户梦想的度假胜地。使用类似于 “If you could visit one place in the world, where would you go?” 的提示,
# 并编写一个打印调查结果的代码块。

diaocha = {}
active = True
while active:
    name = input('你的名字: ')
    city = input('喜欢的城市: ')
    diaocha[name] = city

    tiwen = input('是否继续,是/否:')
    if tiwen == '否':
        active = False
for a,b in diaocha.items():
    print(a+'喜欢的城市是:'+b)

《python编程:从入门到实践的》第八章:函数的例题代码

猜你喜欢

转载自blog.csdn.net/qq_41917061/article/details/108845274
今日推荐