简体   繁体   中英

Python: Call a variable from a function to an if statement

I am trying to practice my modular programming with this assignment. I found out how to call the variables into my main function, but for my if statement in evenOdd(), I am not sure how to call the value. I get the error 'randNum' is not defined.

from random import randint
def genNumber():
    randNum = randint(0,20000)
    print("My number is " + str(randNum))
    return (randNum)

def inputNum():
    userNum = input("Please enter a number: ")
    print("Your number is " + str(userNum))
    return (userNum)

def evenOdd():
    if randNum%2==0:
        print("My number is even")
    else:
        print("My number is odd")
    if userNum%2==0:
        print("Your number is even")
    else:
        print("Your number is odd")

def main():
    randNum = genNumber()
    userNum = inputNum()
    evenOdd()
    input("Press ENTER to exit")


main()

您可以在全局范围内定义randNum,也可以将其作为变量传递给evenOdd()函数,例如evenOdd(randNum)。

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