关于Python语法

2024-04-18 10:00:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: orandofthe答案numberinputget
1条回答
网友
1楼 · 发布于 2024-04-18 10:00:15

^{}内置函数返回类型为str的值。你知道吗

在函数get_input()声明之后的(doc)字符串中指定:

You will need a type conversion.

所以,必须将它包装在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 2和通过__future__导入的print_function。(或者不同类型之间的比较会在while语句中引发TypeError)。你知道吗

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

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

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

如果我错了,而您确实在使用Python 3.x,请按说明使用int(input())。你知道吗

相关问题 更多 >