布尔 return 值?

Boolean return value?

def main():

    num = int(input('Please enter an odd number: '))

    if False:
        print('That was not a odd number, please try again.')

    else:
        print('Congrats, you know your numbers!')

def number():

    if (num / 2) == 0:
        return True,num

    else:
        return False,num


main()

我正在尝试做到这一点,如果输入的数字是奇数,它会向用户表示祝贺。如果不是,那么它应该告诉他们再试一次。我正在尝试 return 布尔值到 main 然后当我尝试使用 main 函数中的代码来提示用户时,它不起作用。

你的函数很奇怪,我说的不是不能被 2 整除的数字。试试这个:

num = int(input('Please enter an odd number: '))

if num % 2 == 0:
    print('Better luck next time??') # no really, you should go back to school (;

else:
    print('Genius!!!')

您的代码确实像 Malik Brahimi 提到的那样看起来很奇怪。这可能是因为您正在尝试将 python 代码编写为 Java,这需要一个 main 方法。 python.

中没有这个要求

如果你想检查包裹在你可以在别处调用的已定义函数中的数字 "odd-ness",你应该尝试这样写。

def odd_check(number):

    if number % 2 == 0: 
#This is the check the check formula, which calculates the remainder of dividing number by 2
        print('That was not an odd number. Please try again.')

    else:
        print('Congrats, you know your numbers!')


num = int(input('Please enter an odd number: ')) #where variable is stored.

odd_check(num) #This is where you are calling the previously defined function. You are feeding it the variable that you stored.

如果您想要一段代码,它会不断要求您的用户输入数字,直到他们输入正确为止,请尝试如下操作:

while True: #This ensures that the code runs until the user picks an odd number

    number = int(input('Please enter an odd number: ')) #where variable is stored.

    if number % 2 == 0: #the check formula, which calculates the remainder of dividing num by 2
        print('That was not an odd number. Please try again.')

    else:
        print('Congrats, you know your numbers!')
        break #This stops the "while" loop when the "else" condition is met.

试试这个:

num_entry = int(input('Please enter an odd number: '))


def number():
    return num_entry % 2 == 0

def main():

    if number() == True:
        print('Sorry, please try again.')

    else:
        print('Nice! You know your numbers!')

number()

main()

这应该有效!