input获取用户输入

  1. age = input("How old are you? ")

input获取到的是字符串

int()

int()函数可以转换为整数

  1. age = int(age)
  2. if age >= 16:
  3. print("You are an audlt")

对应的,float()可以转换为浮点数

Modulo Operator

取余

  1. 3 % 2 # 得到余数1

while循环

  1. prompt = "\nTell me something, and I will repeat it back to you: "
  2. prompt += "\nEnter 'quit' to end the program. "
  3. message = ""
  4. while message != 'quit':
  5. message = input(prompt)
  6. print(message)

breakcontinue的使用与在其他语言中一样

  1. prompt = "Enter a number less than 10"
  2. prompt += "\nEnter 0 to end the game: "
  3. i = 0
  4. while i < 10:
  5. guess = int(input(prompt))
  6. if guess == 0:
  7. break
  8. elif guess > 10:
  9. i += 1
  10. continue
  11. else:
  12. print("once again")

while在list和dictionary中的使用

  1. sandwich_orders = ['ham', 'pastrami', 'apple',
  2. 'beacon', 'pastrami', 'tuna', 'pastrami']
  3. finished_sandwiches = []
  4. print("The Deli has run out of Pastrami")
  5. while 'pastrami' in sandwich_orders:
  6. sandwich_orders.remove('pastrami')
  7. making = True
  8. while making:
  9. if sandwich_orders:
  10. current = sandwich_orders.pop()
  11. print(f"I made your {current} sandwiches")
  12. finished_sandwiches.append(current)
  13. else:
  14. making = False
  15. print(finished_sandwiches)
  1. responses = {}
  2. polling_active = True
  3. while polling_active:
  4. name = input("\nWhat is your name? ")
  5. response = input("Which mountain would you like to climb someday? ")
  6. responses[name] = response
  7. repeat = input("Would you like to let another person respond? (yes/no)")
  8. if repeat == 'no':
  9. polling_active = False
  10. print("\n--- Poll Results ---")
  11. for name, response in responses.items():
  12. print(f"{name} would like to climb {response}")