简体   繁体   中英

Why does my function keep looping and how can i fix it?

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")

i am very new to functions so sorry if this is a rookie mistake. Any help with functions will be appreciated. Thank You.

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

Try this:

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")

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