繁体   English   中英

Python 猜 2 数字游戏

[英]Python guessing 2 numbers game

问题是

编写一个程序,将 1 到 100 之间的两个随机生成的自然数(正整数)的和 (a+b) 和乘积 (a*b) 打印给用户。要赢得游戏,用户必须猜测这两个数字,猜测的顺序应该无关紧要。 给用户三个猜测,如果在三个猜测之后他们错了,则向他们显示数字。 用户必须在一轮中正确猜出两个猜测,并且不会被告知前一轮中的一个数字是否正确。 用户有 3 次尝试猜测这两个数字,如果用户猜对了数字,则游戏应该结束。

import random
a = random.randint(1,100)
b = random.randint(1,100)

print("Sum of two random number is",a + b)
print("Product of two random number is", a * b)
print("Try to guess the 2 numbers that make this sum and product, you have 3 tries, good luck!")

count = 0
win = 0

while count != 3:
    guess_a = int(input('Guess first number '))
    guess_b = int(input('Guess second number '))
    
    if count == 3:
        break
        
    if ((guess_a == a) or (guess_b == b)) and ((guess_b == a) or (guess_a == b)):
        win = 1
        break
        
    else:
        count = count + 1
        print('Incorrect!!!')

if win == 1:
    print('Congrats you won the game.')
    
else:
    print('You lost the game.')
    print('Number a was:',a)
    print('Number b was',b)

我试过这个它有点工作,但我不知道如何使它猜测数字的顺序无关紧要。

一种方法是根本不使用布尔值。

由于在条件语句中0会自动转换为False ,因此如果某个条件为真,我们可以创建一个等于0的表达式。

我想出的表达是:

is_guess_a_right = (a - guess_a) * (a - guess_b)
is_guess_b_right = (b - guess_a) * (b - guess_b)
are_both_right = is_guess_a_right + is_guess_b_right

如果最终表达式等于 0,则两个表达式都是正确的,换句话说,guess_a 和 guess_b 等于 a 和 b(因为如果它们相同, a - guess_a将等于 0)。

最终代码:

import random

a = random.randint(1, 100)
b = random.randint(1, 100)

print("Sum of a and b is %s" % (a + b))
print("Product of a and b is %s" % (a * b))
print("You have three tries to guess the numbers")

count = 0

while count < 3:
    guess_a = int(input("Guess the first number: "))
    guess_b = int(input("Guess the second number: "))

    lose = (guess_a - a) * (guess_a - b) + (guess_b - a) * (guess_b - b)

    if lose:
        print("Try again")
        count += 1
    else:
        print("Congrats, you won the game")
        print("The two numbers were %s and %s" % (a, b))
        break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM