1. 有时候,input() 中的提示可能超过一行,在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数 input()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    prompt = "If you tell us who you are, we can personalize the message you see."
    prompt += "\nWhat is your first name? "

    name = input(prompt)
    print("\nHello, " + name + "!")

    # If you tell us who you are, we can personalize the message you see.
    # What is your first name? Eirc
    #
    # Hello, Eirc!
  1. input() 得到的是用户输入数值的字符串表示,可用 int() 获取真正的数值输入:

    1
    2
    3
    4
    5
    age = input("How old are you: ")
    print(type(age))

    # How old are you: 21
    # <class 'str'>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    height = input("How tall are you, in inches? ")
    height = int(height)

    if height > 36:
    print("\nYou're tall enough to ride!")
    else:
    print("\nYou'll be able to ride when you're a little older.")

    # How tall are you, in inches? 71
    #
    # You're tall enough to ride!

    将数值输入用于计算和比较前,务必将其转换为数值表示。

  2. 在 Python 2.7 中获取输入应使用函数 raw_input() ,这个函数也将输入解读为字符串,Python 2.7 中也包含函数 input(),但它将用户输入解读为 Python 代码,并尝试运行它们。

  3. 在复杂的程序中,如果有很多事件都会导致程序停止运行,标志很有用:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    prompt = "\nTell me something, and I will repeat it back to you:"
    prompt += "\nEnter 'quit' to end the program. "

    active = True # 设置标志
    while active:
    message = input(prompt)

    # 有两个让程序结束的事件
    if message == 'quit':
    active = False
    elif message == 'exit':
    active = False
    else:
    print(message)