我正在使用小Python项目的大书来提高我的Python技能,并且在第一个项目上,这是一个简单的逻辑游戏,在第一次尝试中,代码一路走,但是如果你错了,你就不会正常运行。
这是游戏的代码和描述,有机会的while循环应该在整个游戏中运行,直到你的机会用完,第二个while循环应该在用户输入长度小于或大于3的数字
时运行import re
import random
#In Bagels, a deductive logic game, you
#must guess a secret three-digit number
#based on clues. The game offers one of
#the following hints in response to your guess:
#“Pico” when your guess has a correct digit in the
#wrong place, “Fermi” when your guess has a correct
#digit in the correct place, and “Bagels” if your guess
#has no correct digits. You have 10 tries to guess the
#secret number.
choice_of_nums=['123','345','674','887','356','487','916']
random_three_num=random.choices(choice_of_nums)
count_bagel=0
count_fermi=0
Chances=10
while Chances!=0:
guess = input(f'Guess the three digit number! You have {Chances} to guess! ')
while len(guess)!=3:
guess=input('You must choose a three digit number! Try again! ')
for i in range(0,len(random_three_num)):
if guess==random_three_num:
print('YOU WIN! Well done')
break
elif guess[i] not in random_three_num:
count_bagel+=1
if count_bagel==len(random_three_num):
print('Bagels')
Chances=Chances-1
elif guess[i]==random_three_num[i]:
count_fermi+=1
Chances=Chances-1
print('Fermi')
elif guess in random_three_num:
print('Pico')
import random
choice_of_nums = ['123', '345', '674', '887', '356', '487', '916']
random_three_num = random.choice(choice_of_nums)
count_bagel = 0
count_fermi = 0
chances = 10
while chances > 0:
guess = input(f'Guess the three digit number! You have {chances} to guess! ')
while len(guess) != 3:
guess = input('You must choose a three digit number! Try again! ')
while not guess.isdigit():
guess = input('You must choose integer values! ')
number_is_present = any(number in guess for number in random_three_num)
if guess == random_three_num:
print('YOU WIN! Well done')
chances = 1 # combined w/ the last line, chances will become = 0
elif not number_is_present:
print('Bagel')
else:
index_is_right = False
for i in range(len(guess)):
if guess[i] == random_three_num[i]:
index_is_right = True
if index_is_right:
print('Fermi')
else:
print('Pico')
chances -= 1
(06/28/22)添加
chances = 1
,如果猜对了,那么退出while
循环random.choices
返回一个列表你不需要
re
模块按照PEP8
建议使用蛇形案例
print('YOU WIN! Well done')
之后的break
退出for循环而不是while循环. 把Chances = 0
放到break
前面:
if guess==random_three_num:
print('YOU WIN! Well done')
Chances = 0
break
-
永远不要用
x != 0
这样的条件检查while循环。始终使用<=
或>=
。原因是,如果数字0被跳过,最终到达-1
,那么循环仍然会退出。 -
你不能在
for
循环之前检查if guess==random_three_num:
吗?然后break
语句实际上会中断while循环。现在它只是中断了for循环。这是可能导致无限循环的一个原因。 -
你的倒数第二行
elif guess in random_three_num:
应该是elif guess[1] in random_three_num:
。 -
中描述的问题。Chances=Chances-1
也可能在for循环之外,因为每次猜测的机会数量应该只减少一次。目前,在for循环期间,机会的数量最多减少3倍(每次你击中'Fermi')。这可能导致"1.">