我是python的新手。以下是Y Daniel Liang Python第4章的练习编程练习。 如果彩票号码是333,我会得到133,233,433,533,633,733,833,933等不同用户输入的完美匹配,我不知道为什么。
#!/usr/bin/env python3
#import random
lottery = 333 #random.randint(100, 999)
guess = int(input("\nEnter a three-digit number: "))
print("\nThe Lottery Number is:", lottery)
lottery_digit1 = lottery // 100
lottery %= 100
lottery_digit2 = lottery // 10
lottery_digit3 = lottery % 10
guess_digit1 = guess // 100
guess %= 100
guess_digit2 = guess // 10
guess_digit3 = guess % 10
if guess == lottery:
print("Perfect Match: First Prize $10,000")
elif (guess_digit1 == lottery_digit1 or
guess_digit1 == lottery_digit2 or
guess_digit1 == lottery_digit3) and \
(guess_digit2 == lottery_digit1 or
guess_digit2 == lottery_digit2 or
guess_digit2 == lottery_digit3) and \
(guess_digit3 == lottery_digit1 or
guess_digit3 == lottery_digit2 or
guess_digit3 == lottery_digit3):
print("Matching All Digits: Second Prize $3,000")
elif (guess_digit1 == lottery_digit1 or
guess_digit1 == lottery_digit2 or
guess_digit1 == lottery_digit3) or \
(guess_digit2 == lottery_digit1 or
guess_digit2 == lottery_digit2 or
guess_digit2 == lottery_digit3) or \
(guess_digit3 == lottery_digit1 or
guess_digit3 == lottery_digit2 or
guess_digit3 == lottery_digit3):
print("Matching a Single Digit: Third Prize $1,000")
else:
print("Nice Try.")
答案 0 :(得分:3)
当最后两位数字相同时,你得到一个匹配的原因是因为这些行在这里:
lottery %= 100
...
guess %= 100
你正在改变彩票和猜测的价值。
+=
,-=
,*=
,/=
和%=
运算符会更改它们所使用的变量的值。因此,在执行此操作后,您的变量将变为:
lottery =333
lottery %= 100
#lottery is now 33
和
guess = 733
guess %= 100
#guess is now 33