zoukankan      html  css  js  c++  java
  • Python Learning(7) 用户输入和while循环

    python从入门到实践

    """
    chapter7 用户输入和while循环
    
    """
    # 7.1 函数 input()的工作原理:函数input()让程序暂停运行,等待用户输入一些文本
    message = input("Tell me something, and I will repeat it back to you: ")
    print(message)
    
    # 7.1.1 编写清晰的程序
    name = input("Please enter your name: ")
    print("Hello, " + name + "!")
    
    prompt = "If you tell us who you are, we can personalize the messages you see."
    prompt += "
    What is your first name? "
    name = input(prompt)
    print("
    Hello, " + name + "!")
    
    # 7.1.2 使用 int()来获取数值输入
    height = input("How tall are you, in inches? ")
    height = int(height)
    if height >= 36:
        print("
    You're tall enough to ride!")
    else:
        print("
    You'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("
    The number " + str(number) + " is even.")
    else:
        print("
    The number " + str(number) + " is odd.")
    
    # 7.2 while 循环简介
    # 7.2.1 使用 while 循环
    number = 1
    while number <= 5:
        print(number)
        number += 1
    
    # 7.2.2 让用户选择何时退出
    prompt = "
    Tell me something, and I will repeat it back to you:"
    prompt += "
    Enter 'quit' to end the program. "
    message = ""
    while message != 'quit':
        message = input(prompt)
        print(message)
    
    # 7.2.3 使用标志 -让while循环更简洁
    prompt = "
    Tell me something, and I will repeat it back to you:"
    prompt += "
    Enter 'quit' to end the program. "
    flag = True
    while flag:
        message = input(prompt)
    
        if message == 'quit':
            flag = False
        else:
            print(message)
    
    # 7.2.4 使用 break 退出循环
    number = 1
    while number < 7:
        print(number)
        number += 1
        if number == 3:
            break
    
    print("--------------------")
    number = 1
    while number < 7:
        print(number)
        number += 1
        if number == 3:
            continue
    
    # 7.2.5 在循环中使用 continue
    # 打印10以内的所有奇数
    print("--------------------")
    number = 0
    while number < 10:
        number += 1
        if number % 2 == 0:
            continue
        print(number)
    
    # 7.2.6 避免无限循环 小心处理while循环,防止无限循环
    
    # 7.3 使用 while 循环来处理列表和字典
    # 7.3.1 在列表之间移动元素
    # 假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?
    print("--------------------")
    unconfirmed_users = ['zhangsan', 'lisi', 'wangwu']
    confirmed_users = []
    while len(unconfirmed_users) != 0:
        user = unconfirmed_users.pop()
        confirmed_users.append(user)
        print(user + "be confirmed")
    # 显示所有已验证的用户
    print("
    The following users have been confirmed:")
    for confirmed_user in confirmed_users:
        print(confirmed_user.title())
    
    # 7.3.2 删除包含特定值的所有列表元素
    print("7.3.2 --------------------")
    users = ['zhangsan', 'lisi', 'wangwu', 'zhangsan2']
    print(users)
    for user in users:
        if user.startswith("zhangsan"):
            users.remove(user)
    print(users)
    
    print("7.3.2 2--------------------")
    users = ['zhangsan', 'lisi', 'wangwu', 'zhangsan2']
    print(users)
    for user in users:
        while user.startswith("zhangsan"):
            users.remove(user)
            break  # 小心while循环带来的问题,少使用while循环
    print(users)
    
    # 7.3.3 使用用户输入来填充字典
    responses = {}
    # 设置一个标志,指出调查是否继续
    polling_active = True
    while polling_active:
        # 提示输入被调查者的名字和回答
        name = input("
    What 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("
    --- Poll Results ---")
    for name, response in responses.items():
        print(name + " would like to climb " + response + ".")
    

    练习:

    # 7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如“Let me see if I can find you a Subaru”。
    # prompt = "
    What kind of car do you want to rent? "
    # car = input(prompt)
    # print("Let me see if I can find you a " + car + "!")
    
    # 7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过 8 人,就打印一条消息,指出没有空桌;否则指出有空桌。
    # prompt = "
    How many people do you have to eat? "
    # guest_number = input(prompt)
    # if int(guest_number) > 8:
    #     print("There is no empty table here.")
    # else:
    #     print("Follow me ,pls")
    
    # 7-3 10 的整数倍:让用户输入一个数字,并指出这个数字是否是 10 的整数倍。
    # prompt = "
    input a number ,I can tell you if it is an integer multiple of 10 "
    # number = int(input(prompt))
    # if number % 10 == 0:
    #     print("it is an integer multiple of 10。 ")
    # else:
    #     print("it  is not an integer multiple of 10。 ")
    #
    
    # 7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit'时结束循环。每当用户输入一种配料后,
    # 都打印一条消息,说我们会在比萨中添加这种配料。
    # prompt = "
    请输入披萨配料: "
    # message = ""
    # while True:
    #     message = input(prompt)
    #     if 'quit' == message:
    #         break
    #     else:
    #         print("我们会在披萨中添加这种配料!")
    
    # 7-5 电影票:有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众免费;3~12 岁的观众为 10 美元;
    # 超过 12 岁的观众为 15 美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
    
    # prompt = "
    请问你今年多大: "
    # while True:
    #     age_str = input(prompt)
    #     if not str(age_str).isnumeric():
    #         break
    #     else:
    #         age = int(age_str)
    #         if age < 3:
    #             print("free!")
    #         elif age > 3 and age < 12:
    #             print("10$")
    #         else:
    #             print("15$")
    
    
    # prompt = "
    请问你今年多大: "
    # flag = True
    # while flag:
    #     age_str = input(prompt)
    #     if not str(age_str).isnumeric():
    #         flag = False
    #     else:
    #         age = int(age_str)
    #         if age < 3:
    #             print("free!")
    #         # elif age > 3 and age < 12:
    #         elif 3 < age < 12:
    #             print("10$")
    #         else:
    #             print("15$")
    
    
    # 7-8 熟食店:创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名
    # 字;再创建一个名为 finished_sandwiches 的空列表。遍历列表 sandwich_orders,对于
    # 其中的每种三明治,都打印一条消息,如 I made your tuna sandwich,并将其移到列表
    # finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
    sandwich_orders = ['三明治1', '三明治2', '三明治3']
    finished_sandwiches = []
    for sandwich in sandwich_orders:
        print("I made your tuna sandwich")
        finished_sandwiches.append(sandwich)
    print(finished_sandwiches)
    
    # 7-9 五香烟熏牛肉(pastrami)卖完了:使用为完成练习 7-8 而创建的列表
    # sandwich_orders,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样
    # 的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个 while 循环将
    # 列表 sandwich_orders 中的'pastrami'都删除。确认最终的列表 finished_sandwiches 中
    # 不包含'pastrami'
    
    sandwich_orders = ['11', 'pastrami', '22', '33', 'pastrami', '44', 'pastrami']
    finished_sandwiches = []
    
    print("Pastrami has been sold out")
    
    while 'pastrami' in sandwich_orders:
        sandwich_orders.remove('pastrami')
    
    for sandwich in sandwich_orders:
        print("I made your " + sandwich + " sandwich.")
        finished_sandwiches.append(sandwich)
    
    for sandwich in finished_sandwiches:
        print(sandwich)
    
    # 7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If
    # you could visit one place in the world, where would you go?”的提示,并编写一个打印调
    # 查结果的代码块。
    responses = {}
    polling_active = True
    while polling_active:
        name = input("
     What's u name?")
        place = input("
    If you could visit one place in the world, where would you go?")
        responses[name] = place
        # 看看是否还有人要参与调查
        repeat = input("Would you like to let another person respond? (yes/ no) ")
        if repeat == 'no':
            polling_active = False
    # 调查结束,显示结果
    print("
    --- Poll Results ---")
    for name, pl in responses.items():
        print(name + " would like to visit " + pl + ".")
    
    
  • 相关阅读:
    172. Factorial Trailing Zeroes
    96. Unique Binary Search Trees
    95. Unique Binary Search Trees II
    91. Decode Ways
    LeetCode 328 奇偶链表
    LeetCode 72 编辑距离
    LeetCode 226 翻转二叉树
    LeetCode 79单词搜索
    LeetCode 198 打家劫舍
    LeetCode 504 七进制数
  • 原文地址:https://www.cnblogs.com/DiZhang/p/12544790.html
Copyright © 2011-2022 走看看