Home > Back-end >  How to make if statement check each for loop statement for valid input
How to make if statement check each for loop statement for valid input

Time:09-30

import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))

for (computer_choice) in range(1,6):
    user_choice = input("What number between 1 and "   max_value   " do you choose? ")
    if user_choice == computer_choice:
        print("Thank you for playing. ")

Needs to give the user 5 chances to give the computer_choice before failing. For loop is required.

CodePudding user response:

You can add a counter which will keep the track of the number of attemps that user has made so far.

Also need to convert user input from string to int type.

import random
max_value = int(input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? "))
computer_choice = random.randint(1, int(max_value))
count = 0
for (computer_choice) in range(1,6):
    user_choice = int(input("What number between 1 and "   max_value   " do you choose? "))
    count  = 1
    if user_choice == computer_choice:
        print("Thank you for playing. ")
    if count==5:
         print("you have reached maximum attempt limit")
         exit(0)

CodePudding user response:

Run the for loop with separate variable then computer_choice. Also add eval to input statement as it gives string to conert the user_choice to integer and add a break statement in if user_choice == computer_choice to end the program, rest should work fine.

import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))

for (i) in range(1,6):
    #input takes string convert choice to int using eval
    user_choice = eval(input("What number between 1 and "   max_value   " do you choose? "))
    if user_choice == computer_choice:
        print("Thank you for playing. ")
        break
    if(i==5):
        print("Sorry, maximum number of tries reached.")
        
  • Related