递增和递减不起作用

2024-03-28 07:47:55 发布

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

嗨,我正在做一个Python猜测游戏程序,我不能减少一个值。这是我的程序:

import random as rand

print('\t\t\tGuess Game\n')
print('Enter a Number Between 1 and 20')

while True:

    a = rand.randint(1, 20)

    for i in range(1, 5):
        guess = 0

        guess = int(input('Enter a Number : '))

        if guess == a:
            print('You Are Right\n')
            break

        if guess == 0 or guess < 0:
            print('Please Enter a Positive Integer\n')
            i -= 1
            continue

        if guess > 20:
            print('Please Enter a Reasonable Number\n')
            i -= 1
            continue

        if guess > a:
            if guess <= (a + 5):
                print('Your Number is Little High\n')

            else:
                print('Your Number is Too High\n')

        if guess < a:
            if guess >= (a - 5):
                print('Your Number is Little Low\n')

            else:
                print('Your Number is Too Low\n')

    if guess != a:
        print('My Number Was %s. Please try The Program Again If You Like\n' % a)

    play = str(input('Do You Want to play Again? '))
    play.lower()
    if play.startswith('y'):
        continue

    elif play.startswith('n'):
        break

    else:
        while play is not ((play.startswith('y') and play.endswith('s')) or play == 'y') or ((play.startswith('n') and play.endswith('o')) or play == 'n'):
            play = input('Please Enter a Yes or No')

i-=1不起作用。你知道吗

谢谢。你知道吗

编辑 当使用负整数时,需要进行7次猜测

随机导入为rand

i=5#猜测次数 a=兰特。兰丁(1,20)

当i>;0时: guess=int(input())

if guess == a:
    print("You won!")
    break

if guess == 0:
    i = i + 1
    continue

i = i - 1

Tags: oryounumberinputplayyourifis
1条回答
网友
1楼 · 发布于 2024-03-28 07:47:55

使用for循环,在每次迭代中设置i。因此,如果从i变量中减去一,它将被简单地设置回应该的值(从5减到1)。要使循环一直运行到玩家猜不出为止,请执行以下操作:

i = 5 # Number of guesses
while i > 0:
    # Do your game loop here. Subtract from i to lose a guess.

    if guess == a:
        print("You won!")
        break

如果玩家猜对了,“你赢了!”将被打印,循环将结束。如果玩家猜不到,循环也会结束,但不会打印消息。你知道吗

如果你想检查玩家是否赢了,只要做i > 0。这将是真实的,如果球员赢了,因为仍将有一些猜测剩余。你知道吗

相关问题 更多 >