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()
我试图这样做,如果输入的数字是奇数,它会祝贺用户。如果没有,那么它应该告诉他们再试一次。我试图将布尔值返回到main,然后当我尝试使用main函数中的代码来提示用户时,它不起作用。
答案 0 :(得分:6)
你的功能非常奇怪,我不是在谈论那些不能被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!!!')
答案 1 :(得分:2)
试试这个:
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()
这应该有效!
答案 2 :(得分:0)
你的代码确实看起来像Malik Brahimi提到的那样奇怪。这可能是因为您正在尝试编写像Java这样的python代码,这需要一个main方法。 python中没有这样的要求。
如果您想检查包含在您可以在其他地方调用的已定义函数中的数字的“奇数”,您应该尝试这样写。
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.