Программа не запускается повторно, вместо этого выполняется оператор else.Python

Программы на Python
Anonymous
Программа не запускается повторно, вместо этого выполняется оператор else.

Сообщение Anonymous »

Недавно я создал эту простую игру в VS Code. Однако, если я попытаюсь запустить код, когда игра запрашивает ввод, будет выполнен только оператор undef (который я написал для случаев, когда ввод недействителен, проверьте код с #UNDEFINED ERROR). Программа не запускается повторно, вместо этого оператор else (проверьте код с #UNDEFINED ERROR) выполняется для недопустимого ввода в IDE.
МОЯ ТЕОРИЯ, КОГДА Я НАЖИМАЮ RUN IN VS CODE IT ENTER. ОПРЕДЕЛЕННЫЙ СИМВОЛ, ПОКАЗЫВАЮЩИЙ КОМПИЛЯТОР ПЕРЕЗАПУСТИТЬ ПРОГРАММУ, НО КОГДА ПРОГРАММА ЗАПРОСИТ ВВОД В ТЕРМИНАЛ, ОНА ИНТЕРПРЕТИРУЕТСЯ КАК НЕДЕЙСТВИТЕЛЬНЫЙ ВВОД, Я НЕ УВЕРЕН, ТАК ЧТО ЭТОГО НЕ ПРОИЗОШЛО РАНЬШЕ.
import random # Importing the random module to generate random numbers

# Initializing variables
inp = 1
comp_won = user_won = 0

# Printing the welcome message and instructions
print("WELCOME TO GUESS THE NUMBER!\n\nEnter: \n'0' for answer\n'-1' for exit\n\nBEST OF 10:\n")

# Main game loop: continues until the user inputs -1 or either player wins 3 rounds
while int(inp) != -1 and user_won != 3 and comp_won != 3:
try_remain = 7 # Number of attempts for each round
num_to_guess = random.randint(1, 100) # Generating a random number between 1 and 100

# Loop for each round: continues until attempts run out or the user guesses correctly
while try_remain > 1:
inp = input(f"Guess the number ({try_remain-1} attempts left): ") # Prompting user for input

if inp.isdigit(): # Checking if the input is a digit
if int(inp) == num_to_guess: # If the guess is correct
user_won += 1
print(f"You won this round!!!\nScore: {user_won}:{comp_won}\n")
break

elif num_to_guess < int(inp) comp_won and int(inp) != -1:
print("You won the game!!!")
prize = "".join(random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4)) # Generating a random prize code
with open(r"prize.txt", 'a') as f: # Saving the prize code to the file
f.write(f"{prize}\n")
print(f"Use code-{prize} in the next round for an instant victory")
else:
print("Computer won!!!")

#ELSE ИЛИ НЕОПРЕДЕЛЕННОЕ ЗАЯВЛЕНИЕ:
else: # If the input is not a digit
with open(r'prize.txt', 'a+') as f: # Opening the prize file
f.seek(0)
l = [li.strip() for li in f.readlines()] # Reading the prize codes

if inp.upper() in l: # Checking if the input matches a prize code
print(f"\nThe number was {num_to_guess}")
user_won += 1
print(f"You won this round!!!\nScore: {user_won}:{comp_won}\n")
l.remove(inp) # Removing the used prize code
with open(r"prize.txt", 'w') as f: # Writing the updated prize codes back to the file
for it in l:
f.write(f"{try_remain}\n")
inp = 1
break

print("Input should be an integer between 1-100")


Подробнее здесь: https://stackoverflow.com/questions/790 ... s-executed

Вернуться в «Python»