为什么我的函数会不断循环,我该如何解决?

时间:2018-12-03 19:02:23

标签: python function

import time 
import random
import sys
def code(): 
    user_num=()
    user_num=int(input("What number do you want from 0-30"))
    if user_num>30:
        print("number needs to be smaller")
        print("restart code and try again")
    else:
        pass
    if user_num<0:
        print("your number needs to be greater")
        print("restart code and try again")
    else:
        pass
    code()

code()
random_num=random.randint(0,1)
if random_num==user_num:
    print("your number is correct")
else:
    print("your number is incorrect")
    time.sleep(1)
    try_again=input("do you want to try again (yes/no")
    if try_again=="yes":
        code()
    else:
        print("ok. Bye")

我对功能非常陌生,如果这是菜鸟的错误,抱歉。任何有关功能的帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:6)

在“代码”功能的最后,您要再次调用

答案 1 :(得分:0)

尝试一下:

import time 
import random
import sys
def code(): 
    user_num=()
    user_num=int(input("What number do you want from 0-30"))
    if user_num>30:
        print("number needs to be smaller")
        print("restart code and try again")
    else:
        pass
    if user_num<0:
        print("your number needs to be greater")
        print("restart code and try again")
    else:
        pass
    return user_num


random_num=random.randint(0,1)
user_num = code()
if random_num==user_num:
    print("your number is correct")
else:
    print("your number is incorrect")
    time.sleep(1)
    try_again=input("do you want to try again (yes/no")
    if try_again in "yes":
        user_num = code()
    else:
        print("ok. Bye")