简体   繁体   English

Python 新手,在 if/else 语句中存在不可读代码的问题

[英]New to Python, issues with unreadable code in if/else statements

I am new to programming with Python and have been having non-stop issues with parts of my code being listed as unreachable.我是使用 Python 编程的新手,并且我的部分代码被列为无法访问的问题一直存在。 Here is my program:这是我的程序:

def inputData():

    userNumber = int(input("Please enter a number to check if it is divisible by 7 "))

    return userNumber

def processData(userNumber):

    return True if userNumber % 7 == 0 else False


def outputData(processData):

    if True:
        print("Your number IS divisible by 7!")
    else:
        print("Your number is NOT divisible by 7!")

def main():

    userNumber = inputData()
    isitdivisible = processData(userNumber)
    outputanswer = outputData(isitdivisible)

print(main())

When I run it works for numbers that ARE divisible by 7 however when I input a number that gives the true output regardless.当我运行它时,它适用于可被 7 整除的数字,但是当我输入一个无论如何都会给出真实输出的数字时。 Pycharm is highlighting the else: statement as being unreachable. Pycharm 强调 else: 语句无法访问。

Any advice on this would be greatly appreciated as I have not been able to get it to work with the use of google at all.对此的任何建议将不胜感激,因为我根本无法让它与谷歌的使用一起工作。

In your outputData function you aren't checking processData , instead you have written:在您的outputData函数中,您没有检查processData ,而是编写了:

if True:
    print("Your number IS divisible by 7!")

In this case, it always prints "Your number IS divisible by 7!".在这种情况下,它总是打印“你的数字可以被 7 整除!”。 You should have written:你应该写:

if outputData:
    print("Your number IS divisible by 7!")
else:
    print("Your number is NOT divisible by 7!")

Your code should work after this, but there are some things I must say.在此之后,您的代码应该可以正常工作,但我必须说一些事情。 You don't need to print main() function.您不需要打印main()函数。 You can just call main() and it must work.你可以只调用main()并且它必须工作。 Remember, print is used for showing output.请记住, print用于显示输出。 2nd thing I want to mention is about return True if userNumber % 7 == 0 else False .我想提到的第二件事是关于return True if userNumber % 7 == 0 else False userNumber%7 == 0 returns boolean. userNumber%7 == 0返回布尔值。 You can just return it like this:你可以像这样返回它:

def processData(userNumber):
    return userNumber % 7 == 0 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM