Python编程从入门到实践(5)学习笔记-用户输入和while

第七章,用户输入和while循环

  1 # 第七章 用户输入和while
  2 message = input("Tell me sth.and I will repeat it back to you:")
  3 print(message)
  4 
  5 # += 拼接字符串
  6 promt = "If you tell us who you are ,we can personalize the messages you see."
  7 promt += "\n What is your first name"
  8 name = input(promt)
  9 print("\nHello ," + name + '!')
 10 
 11 # int()
 12 age = input("How old are you?")
 13 print(age)
 14 
 15 # TypeError: '>=' not supported between instances of 'str' and 'int'
 16 # if age>=18:
 17 #     print("over 18")
 18 
 19 # 需要转型
 20 if int(age) > 18:
 21     print("over 18")
 22 
 23 # 求余数 求模 %
 24 # 余数1
 25 print(4 % 3)
 26 # 余数2
 27 print(5 % 3)
 28 # 余数0
 29 print(6 % 3)
 30 
 31 #
 32 number = input("Enter a number,and I'll tell you if it's even or odd")
 33 number = int(number)
 34 # 被2整除 是偶数
 35 if number % 2 == 0:
 36     print("is even")
 37 else:
 38     print("is odd")
 39 
 40 # while 循环
 41 current_number = 1
 42 while current_number <= 5:
 43     print(current_number)
 44     current_number += 1
 45 
 46 # break
 47 promt = "\nPlease enter the name of a city you have visited:"
 48 promt += "\n(Enter 'quit' when you are finished."
 49 
 50 while True:
 51     city = input(promt)
 52 
 53     if city == 'quit':
 54         break
 55     else:
 56         print("I'd love to go to " + city.title() + "!")
 57 
 58 # continue
 59 current_number = 0
 60 while current_number < 10:
 61     current_number += 1
 62     if current_number % 2 == 0:
 63         continue
 64     print(current_number)
 65 
 66 # while 循环处理列表
 67 unconfirmed_users = ['alice', 'brian', 'candace']
 68 confirmed_users = []
 69 
 70 # 参见书P78页 列表至少包含一个元素则返回True,while True继续循环
 71 # 当列表一个元素也没有则返回False ,while False 出循环
 72 while unconfirmed_users:
 73     current_user = unconfirmed_users.pop()
 74     print("Verifying user: " + current_user.title())
 75     confirmed_users.append(current_user)
 76 
 77 # 出循环
 78 print("\nThe following users have benn confirmed:")
 79 for confirmed_user in confirmed_users:
 80     print(confirmed_user.title())
 81 
 82 # 删除特定值所有列表元素
 83 pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
 84 print(pets)
 85 
 86 while 'cat' in pets:
 87     pets.remove('cat')
 88 # ['dog', 'dog', 'goldfish', 'rabbit']
 89 print(pets)
 90 
 91 # 用户输入填充字典
 92 responses = {}
 93 polling_active = True
 94 while polling_active:
 95     name = input("\nWhat is your name?")
 96     response = input("Which mountain would you like to climb someday?")
 97 
 98     responses[name] = response
 99 
100     repeat = input("Would you like to let another person respond?(yes/no)")
101     if repeat == 'no':
102         polling_active = False
103 
104 print("\n--- Poll Results ---")
105 for name, response in responses.items():
106     print(name + " would like to climb " + response + ".")

 

posted @ 2021-05-11 14:26  阿米诚  阅读(42)  评论(0编辑  收藏  举报