else语句

if-else语句

  1. age = 17
  2. if age >= 18:
  3. print("You are old enough to vote!")
  4. print("Have you registered to vote yet?")
  5. else:
  6. print("Sorry, you are too young to vote.")
  7. print("Please register to vote as soon as you turn 18!")
  1. Sorry, you are too young to vote.
  2. Please register to vote as soon as you turn 18!

else代码块

  1. print("Give me two numbers, and I'll divide them.")
  2. print("Enter 'q' to quit.")
  3. while True:
  4. first_number = input("\nFirst number: ")
  5. if first_number == 'q':
  6. break
  7. second_number = input("Second number: ")
  8. try:
  9. answer = int(first_number) / int(second_number)
  10. except ZeroDivisionError:
  11. print("You can't divide by 0!")
  12. else:
  13. print(answer)
  1. Give me two numbers, and I'll divide them.
  2. Enter 'q' to quit.
  3. First number: 5
  4. Second number: 0
  5. You can't divide by 0!
  6. First number: 5
  7. Second number: 2
  8. 2.5
  9. First number: q

with语句

读取文件

  1. with open('pi_digits.txt') as file_object:
  2. contents = file_object.read()
  3. print(contents