Python 3.4 用户输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28369736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:09:43  来源:igfitidea点击:

Python 3.4 User Input

pythonpython-3.xevaluation

提问by jahrich

I want to write a small script to tell me if the bass level is OK or not from user input.

我想写一个小脚本来告诉我用户输入的低音水平是否正常。

I am just learning user input, and this is what I have so far:

我只是在学习用户输入,这就是我目前所拥有的:

def crisp():
    bass = input("Enter bass level on a scale of 1 to 5>>")
    print ("Bass level is at") + bass
    if bass >=4:
       print ("Bass is crisp")    
    elif bass < 4:
       print ("Bass is not so crisp")

采纳答案by Ben Morris

I really don't see a problem here, but just a simple program that does this and only this would be as so:

我真的没有看到这里有问题,但只是一个简单的程序来执行此操作,并且仅此而已:

a=1
while a==1:
    try:
        bass = input('Enter Bass Level: ')
        print('Bass level is at ' + str(bass))
        if bass >=4:
            print("Bass is crisp")
        elif bass < 4:
            print('Bass is not so crisp')
        a=0
    except ValueError:
        print('Invalid Entry')
        a=1

Not much difference with a function:

与函数没有太大区别:

def Bass():
    a=1
    while a==0:
        try:
            bass = input('Enter Bass Level: ')
            print('Bass level is at ' + str(bass))
            if int(bass) >=4:
                print("Bass is crisp")
            elif bass < 4:
                print('Bass is not so crisp')
            a=0
    except ValueError:
        print('Invalid Entry')
        a=1

回答by Malik Brahimi

Convert to an integer:

转换为整数:

bass = int(input("Enter bass level on a scale of 1 to 5>>"))

回答by A.J. Uppal

When you take in input()through the built-in function, it takes input as a string.

当您input()通过内置函数接收时,它将输入作为字符串。

>>> x = input('Input: ')
Input: 1
>>> x
"1"

Instead, cast int()to your input():

相反,投射int()到您的input()

>>> x = int(input('Input: '))
Input: 1
>>> x
1

Otherwise, in your code, you are checking if "4" == 4:, which is never true.

否则,在您的代码中,您正在检查if "4" == 4:,这永远不会正确。

Thus, here is your edited code:

因此,这是您编辑的代码:

def crisp():
    bass = int(input("Enter bass level on a scale of 1 to 5>>"))
    print ("Bass level is at") + bass
    if bass >=4:
       print ("Bass is crisp")    
    elif bass < 4:
       print ("Bass is not so crisp")