关于Python语法

时间:2015-10-04 15:56:59

标签: python python-3.x user-input

def get_input():

    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''
    #pass # REPLACE THIS WITH YOUR CODE

    n = input ("Enter the number 1,2 and 3? ")

    while n > 0 and n < 4:
        print("Invalid Input, give the  number between 1 to 3")
        n = input ("Enter the number 1,2 or 3? ")
    return (n)


get_input()

我没有得到答案而且它没有工作,我正在寻找这样的答案,

Give me one of 1,2 or 3: sid
Invalid input!
Give me one of 1,2 or 3: 34
Invalid input!
Give me one of 1,2 or 3: -7
Invalid input!
Give me one of 1,2 or 3: 0
Invalid input!
Give me one of 1,2 or 3: 2

Process finished with exit code 0

1 个答案:

答案 0 :(得分:3)

input()内置函数返回类型str的值。

正如函数get_input()声明后的(doc)字符串中所指定的那样:

  

您需要进行类型转换。

因此,您必须将其包装在int()中以将其转换为整数int

n = int(input("Enter the number 1,2 or 3? "))

然后您可以使用比较运算符来评估in是否符合接受值的合格范围:

   # Your comparisons are mixed.
   # You can use the in operator which is intuitive and expressive
   while n not in [1, 2, 3]:
        print("Invalid Input, give the  number between 1 to 3")

        # remember to wrap it in an int() call again
        n = int(input ("Enter the number 1,2 or 3? "))
    return (n)

如果您提供数字,这可以完美地运作:

Enter the number 1,2 and 3? 10
Invalid Input, give the  number between 1 to 3
Enter the number 1,2 and 3? -1
Invalid Input, give the  number between 1 to 3
Enter the number 1,2 and 3? 15
Invalid Input, give the  number between 1 to 3
Enter the number 1,2 and 3? 104
Invalid Input, give the  number between 1 to 3

但如果您提供单个字符或字符串(类型str),则会收到错误消息:

Enter the number 1,2 and 3? a

ValueError: invalid literal for int() with base 10: 'a'

这超出了问题的范围,但您可以want to look into it

无论如何,你的条件让我失望..

您可能正在使用Python 2print_function通过__future__导入。 (或者不同类型之间的比较会在TypeError语句中引发while

检查你的python python -V版本[在命令行中]和:

如果使用python 2而不是input()使用raw_input()

n = int(raw_input("Enter the number 1, 2, 3: ")

如果我错了并且你确实在使用Python 3.x,请按照说明使用int(input())