Недавно я закончил изучение Python на Codecademy, поэтому решил создать игру для скалы, бумаги, ножниц для своей первой настоящей программы, так как она казалась довольно простой.Python игнорирует if statement in while loop
При тестировании программы Python, похоже, игнорирует большой оператор if/elif, который вложен в цикл while. Игра генерирует случайное целое число (0 - рок, 1 - бумага, 2 - ножницы), а затем печатает его (для отладки). Затем он запрашивает плеер для ввода. После этого вместо того, чтобы оценивать выбор с помощью оператора if, он просто запрашивает у игрока другой выбор. Он также печатает новое случайное целое число, поэтому я знаю, что он просто пропускает оператор if и возвращается к началу цикла while.
Ниже приведено код к игре. Если в выражении if есть какая-то синтаксическая ошибка, я ее не вижу. Кто-нибудь знает, что происходит?
from random import randint
def choose():
print '\nWill you play rock, paper, or scissors?'
rawhumanchoice = raw_input('> ')
if rawhumanchoice == 'rock' or rawhumanchoice == 'r':
humanchoice = 0
elif rawhumanchoice == 'paper' or rawhumanchoice == 'p':
humanchoice = 1
elif rawhumanchoice == 'scissors' or rawhumanchoice == 's':
humanchoice = 2
else:
print '\nSorry, I didn\'t catch that.'
choose()
def gameinit():
roundsleft = 0
pcwins = 0
humanwins = 0
print 'How many rounds do you want to play?'
roundsleft = raw_input('> ')
while roundsleft > 0:
pcchoice = randint(0,2)
print pcchoice
humanchoice = -1
choose()
if humanchoice == 0: #This is what Python ignores
if pcchoice == 0:
print '\nRock and rock... it\'s a tie!'
roundsleft -= 1
elif pcchoice == 1:
print '\nPaper beats rock... PC wins.'
roundsleft -= 1
pcwins += 1
elif pcchoice == 2:
print '\nRock beats scissors... human wins!'
roundsleft -= 1
humanwins += 1
elif humanchoice == 1:
if pcchoice == 0:
print '\nPaper beats rock... human wins!'
roundsleft -= 1
humanwins += 1
elif pcchoice == 1:
print '\nPaper and paper... it\'s a tie!'
roundsleft -= 1
elif pcchoice == 2:
print '\nScissors beat paper... PC wins.'
roundsleft -= 1
pcwins += 1
elif humanchoice == 2:
if pcchoice == 0:
print '\nRock beats scissors... PC wins.'
roundsleft -= 1
pcwins += 1
elif pcchoice == 1:
print '\nPaper beats rock... human wins!'
roundsleft -= 1
humanwins += 1
elif pcchoice == 2:
print '\nScissors and scissors... it\'s a tie!'
roundsleft -= 1
else:
if humanwins > pcwins:
result = 'The human wins the match!'
elif humanwins < pcwins:
result = 'The PC wins the match.'
elif humanwins == pcwins:
result = 'The match is a tie!'
print '\nThe score is %s:%s... %s \n' % (humanwins,pcwins,result)
gameinit()
gameinit()
Если бы кто-то мог закрыть как дублирующий [этот] (http://stackoverflow.com/questions/32364127/store-function-result-into-variable), я был бы признателен. – TigerhawkT3
Как функция 'select' модифицирует переменную, которая не входит в ее область? –
Тщательно посмотрите на строку 'humanchoice = -1' ... Код правильно игнорирует это утверждение if –