简体   繁体   中英

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. 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. Pycharm is highlighting the else: statement as being unreachable.

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:

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

In this case, it always prints "Your number IS divisible by 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. You can just call main() and it must work. Remember, print is used for showing output. 2nd thing I want to mention is about return True if userNumber % 7 == 0 else False . userNumber%7 == 0 returns boolean. You can just return it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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