我是Python新手。我有一个程序,让你猜一个随机的4位密码。例如,如果密码是5530
,如果我猜里面有一个5
(例如5111
),它说我猜对了两个数字。如果密码是5535
,它说我正确地猜到了3个数字
但实际上,它解释了我答案中的单个5
对于其他5
是正确的。我只想说,如果有两个或三个5
,我猜对了一个数字;如果我为5530
键入了两个5
,我猜对了两个;如果我为5535
键入了三个5
,我猜对了三个
import random
no1 = random.randint(0, 9)
no2 = random.randint(0, 9)
no3 = random.randint(0, 9)
no4 = random.randint(0, 9)
password = str(no1) + str(no2) + str(no3) + str(no4)
count = 0
if no1 % 2 == 0:
count += 1
if no2 % 2 == 0:
count += 1
if no3 % 2 == 0:
count += 1
if no4 % 2 == 0:
count += 1
print(password)
print(f"Hint: The password consists of {count} even number(s)")
guess = input("Guess the 4 numbers: ")
present = 0
if str(no1) in guess:
present += 1
if str(no2) in guess:
present += 1
if str(no3) in guess:
present += 1
if str(no4) in guess:
present += 1
if present == 4:
if guess == password:
print("Congrats! You have guessed the password correctly.")
else:
print("All the numbers are present but not in the correct sequence.")
print(f"You did not make it! The password is {password}.")
else:
print(f"{present} number(s) of your guess are present in the password.")
print(f"You did not make it! The password is {password}.")
p.S.我希望我下面的代码可能会被range
之类的东西缩短,但我没有信心这样做,所以有人能帮我吗
更改此项:
致:
另一种方式:
您必须将密码中的每个数字与guess中的每个数字进行比较。为此,您必须使用索引访问guess。像这样:
相关问题 更多 >
编程相关推荐