如何将代码重复多次?用python

2024-05-14 09:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何使代码重新接受,以便用户只能猜测随机数的答案三次,我如何使其在某一点停止?谢谢 这是一个随机数字猜测游戏,我是python的初学者,在网络上找不到任何帮助我的东西(或者我只是个傻瓜)

import random
print('what difficulty do you want? Type Easy or Hard accordingly')
difficulty = input('')

if difficulty == 'Hard':
    print('your going to have a tough time')
    hardrandomnum = random.randint(1,100)
    def main():
        print('try to guess the number')
        playerguess = float (input(""))
        if playerguess > hardrandomnum: 
            print ("guess a lower number")
        if playerguess < hardrandomnum:
            print("guess a higher number")
        if playerguess == hardrandomnum:
            print("correct") 
        

        restart = 4
        if restart >4:
            main()

        if restart == 4:
            exit()

main()

Tags: to代码用户numberinputifmainrandom
3条回答

您可以使用for循环:

for i in range(3):
    #your code 

range()中的数字表示访问内部代码的次数 也有while循环,但是对于您的用例,for循环应该可以做到这一点

循环和中断

例如,如果要运行代码三次,请将其包装在For循环中:

for i in range(3):
   [here goes your code]

或者你可以做一个while循环并中断:

while(True):
    [here goes your code]
    if condition is met:
        break

使用below answer提到的循环结构

带有while循环的示例
def repeat_user_input(num_tries=3):
    tries = 0
    result = []

    while tries < num_tries:
        tries += 1
        result.append(float(input()))

    return result


print(repeat_user_input())

列表理解示例和range

def repeat_user_input(num_tries=3):
    return [float(input()) for _ in range(num_tries)]

相关问题 更多 >

    热门问题