Python 我的if语句条件未正确触发,尽管条件已满足
我正在学习如何使用Python编程,通过参与一些小项目来让自己熟悉Python。我遇到了一个小问题,尽管在程序执行期间满足了条件,但if语句没有被正确触发。这是我自己做的骰子模拟项目 我想不出任何其他的方法在这个时候,因为我仍然是一个新手,但学习,因为我要去Python 我的if语句条件未正确触发,尽管条件已满足,python,Python,我正在学习如何使用Python编程,通过参与一些小项目来让自己熟悉Python。我遇到了一个小问题,尽管在程序执行期间满足了条件,但if语句没有被正确触发。这是我自己做的骰子模拟项目 我想不出任何其他的方法在这个时候,因为我仍然是一个新手,但学习,因为我要去 import random import time print("Welcome to the dice simulator, lets find out how lucky you are!") "\n" min = 1 max =
import random
import time
print("Welcome to the dice simulator, lets find out how lucky you are!")
"\n"
min = 1
max = 6
roll = input("Do you want to play? ")
while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":
print("Now rolling both dice....")
time.sleep(1)
print("calculating....")
time.sleep(3)
print(random.randint(min, max))
print(random.randint(min, max))
if min == max: #This if condition does not work even if the dice match. Needs work.
print("Amazing! You scored a double!")
else: #This else condition works regardless of the outcome.
print("Oof! Might wanna keep trying!")
roll_again = input("Roll again? y/n: ")
if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
print("Goodbye!")
break
# else:
# print("Invalid answer")
# break
如果满足If条件,将打印一条消息,祝贺用户获得双倍分数,例如1,1或6,6。如果骰子没有显示匹配的数字,else条件将打印一条消息,告诉用户下次好运。这是因为您预设了永不更改的min和max。因此,如果min==max不能为真 您只需将结果保存在新变量中即可:
dice_1 = random.randrange(1, 7)
dice_2 = random.randrange(1, 7)
然后比较骰子1和骰子2的条件试试:-
import os
import datetime
directory = r'C:\Users\vasudeos\OneDrive\Desktop\Test Folder'
extensions = (['.jpg', '.jpeg', '.png']);
import random
import time
print("Welcome to the dice simulator, lets find out how lucky you are!")
"\n"
min = 1
max = 6
roll = input("Do you want to play? ")
while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":
print("Now rolling both dice....")
time.sleep(1)
print("calculating....")
time.sleep(3)
min1 = random.randint(min, max)
max1 = random.randint(min, max)
print("{}\n{}".format(min1, max1))
if min1 == max1: #This if condition does not work even if the dice match. Needs work.
print("Amazing! You scored a double!")
else: #This else condition works regardless of the outcome.
print("Oof! Might wanna keep trying!")
roll_again = input("Roll again? y/n: ")
if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
print("Goodbye!")
break
正如其他人所指出的,变量
min
和max
在整个程序执行过程中都具有常量值(1,6),并且由于它们的值不相同,如果min==max始终为false,甚至不会改变。min
始终为1,max
始终为6,因此,即使随机数相同,min
和max
都是内置函数,if语句也永远不会为真。它们不是变量名的好选择。非常感谢!我现在有更好的方法来解决这个问题!