1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] The program does not re-run instead the else statement is executed

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    Recently, I created this simple game in VS Code. However, if I try to run the code when the game is asking for input, the undefined statement (which I wrote for cases when the input is invalid, check code with #UNDEFINED ERROR ) is executed only . The program does not re-run instead the else(check code with #UNDEFINED ERROR) statement is executed for invalid input in IDE.

    MY THEORY IS WHEN I PRESS RUN IN VS CODE IT ENTER CERTAIN SYMBOL TO TELL COMPILER TO RE-RUN THE PROGRAM BUT WHEN PROGRAM IS ASKIG FOR INPUT IN TERMINAL IT GETS INTERPRETED AS INVALID INPUT I AM NOT SURE AS IT HAS NOT HAPPENED BEFORE.

    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 3:\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) <= 100: # If the guess is too high
    print("Hint: The number is lesser")
    try_remain -= 1

    elif int(inp) == 0: # Special case for input 0
    try_remain -= 6

    elif int(inp) == -1: # Special case for input -1
    print(f"\nThe number was {num_to_guess}")
    print("Exiting program...")
    break

    elif 0 < int(inp) < num_to_guess: # If the guess is too low
    print("Hint: The number is greater")
    try_remain -= 1

    else: # If the input is out of the valid range
    print("Input should be an integer between 1-100")

    else: #UNDEFINED ERROR 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")


    else: # If the user fails to guess the number within the allowed attempts
    print(f"The number was {num_to_guess}")
    comp_won += 1
    print(f"You lost this round!!!\nScore: {user_won}:{comp_won}\n")



    # End of game: printing the final scores and determining the winner
    else:
    print(f"Your score: {user_won}\nComputer score: {comp_won}\n")
    if user_won > 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 OR UNDEFINED STATEMENT:

    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")


    expectation:

    #FIRST TIME PROGRAM IS RUN:

    WELCOME TO GUESS THE NUMBER!

    enter:
    '0' for answer
    '-1' for exit

    BEST OF 10:

    guess the number(6): 50
    Hint: no. is greater
    guess the number(5):

    #NOW RUN BUTTON IS PRESSED AGAIN:

    WELCOME TO GUESS THE NUMBER!

    enter:
    '0' for answer
    '-1' for exit

    BEST OF 10:

    guess the number(6):

    #PROGRAM RE-RUN AGAIN SUCCESSFULLY


    REAL OUTPUT:

    #FIRST TIME PROGRAM IS RUN:

    WELCOME TO GUESS THE NUMBER!

    enter:
    '0' for answer
    '-1' for exit

    BEST OF 10:

    guess the number(6): 50
    Hint: no. is greater
    guess the number(5):

    #NOW RUN BUTTON IS PRESSED AGAIN:

    guess the number(5): python -u "c:\Users\vatsa\OneDrive\Desktop\vatsal_vscode\tkinter\staa.py"
    input should be integer between 1-100
    guess the number(5):

    #PROGRAM DOES NOR RE COMPILE INSTEAD WE GET OUTPUT LIKE WE HAVE PASSED SOME VALUE TO INPUT FUNCTION

    Continue reading...

Compartilhe esta Página