import random
thenum = random.randint(1000, 9999)
print (thenum)
tally = 1
guessone = int(input("What is your first guess?: "))
strguessone = str(guessone)
strthenum = str(thenum)
if strguessone [0] == strthenum [0]:
tally + 1
if strguessone [1] == strthenum [1]:
tally + 1
if strguessone [2] == strthenum [2]:
tally + 1
if strguessone [3] == strthenum [3]:
tally + 1
print (tally)
if tally == 5:
print ("You Win")
当我运行此代码时,我只得到一个来自打印计数器的响应为什么我在if语句中添加了计数器我知道我应该使用循环但我认为这是我想要做的
答案 0 :(得分:1)
当你这样做时 -
tally + 1
它会计算该表达式的结果,但之后会抛弃结果,因为您没有指示Python解释器对结果执行任何操作。如果您希望将tally
增加1,则必须将结果分配回tally
。示例 -
tally += 1
答案 1 :(得分:1)
您应该使用+ =运算符而不是+运算符。
import random
thenum = random.randint(1000, 9999)
print (thenum)
tally = 1
guessone = int(input("What is your first guess?: "))
strguessone = str(guessone)
strthenum = str(thenum)
if strguessone [0] == strthenum [0]:
tally += 1
if strguessone [1] == strthenum [1]:
tally += 1
if strguessone [2] == strthenum [2]:
tally += 1
if strguessone [3] == strthenum [3]:
tally += 1
print (tally)
if tally == 5:
print ("You Win")
答案 2 :(得分:0)
tally + 1
语句所做的只是计算计数加1的值。它不会保存新值。您需要执行tally = tally + 1
。但是,在这种情况下,您可以直接比较数字而不是将两个值都转换为字符串并比较这些字符串(无论如何都可以进行,而无需逐个手动比较每个字符):
import random
thenum = random.randint(1000, 9999)
print (thenum)
guessone = int(input("What is your first guess?: "))
if thenum == guessone:
print ("You Win")