Validating User Input in Python [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
"""
GuessNumber.py - This program allows a user to guess a number
between 1 and 10.
Input: User guesses numbers until they get it right.
Output: Tells users if they are right or wrong.
"""
import random
number = random.randint(1, 10)
# Prime the loop.
keepGoing = input("Do you want to guess a number? Enter Y or N ")
# Validate input.
# Enter loop if they want to play.
while keepGoing == "Y":
# Get user's guess.
stringNumber = input("I'm thinking of a number. .\n Try to guess by entering a number between 1 and 10 ")
userNumber = int(stringNumber)
# Validate input.
# Test to see if the user guessed correctly.
if userNumber == number:
keepGoing = "N"
print("You are a genius. That's correct!")
else:
keepGoing = input("That's not correct. Do you want to guess again? Enter Y or N ")
# Validate input.
If the user guesses correctly, the program congratulates the user, and then the loop that controls guessing numbers exits; otherwise the program asks the user if he or she wants to guess again. If the user enters "Y", he or she can guess again. If the user enters "N", the loop exits. You can see that the "Y" or "N" is the sentinel value that controls the loop. I need to ass a code that validates "y" and "n"

keepGoing.upper() == "Y" would check lower and upper case inputs.
You shouldn't need to validate N/n

import random
number=random.randint(1,10)
keepGoing=raw_input("DO you want to guess a number:\n ")
keepGoing=keepGoing[0].upper()
while keepGoing=='Y':
stringNumber=int(raw_input("I'm thinking of a number. .\n Try to guess by entering a number between 1 and 10:\n "))
if (stringNumber==number):
print("You are a genius. That's correct!")
break
else:
keepGoing=raw_input("DO you want to guess a number")
keepGoing=keepGoing[0].upper()

Related

How To Keep Trying New Inputs in Try and Except Format [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 months ago.
I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right.
Right now, my code only allows the user to input one ValueError. I don't want this, I want to keep inputting until I guess the number. Attached is my code. Any help is greatly appreciated!
ex:
I want to input errors ("a", 4.20, "hello") and still have them count as guesses until I guess the number
"a" > 4.20 > "hello" > 26 => Guessed it in 3 tries
def guess(n):
secret_number = 26
if n < secret_number:
return print("Too low!")
elif n > secret_number:
return print("Too high!")
def try_exp():
try:
n = int(input("What is your guess? "))
return n
except ValueError:
n = int(input("Bad input! Try again: "))
return n
def counter():
print("Guess the secret number! Hint: it's an integer between 1 and 100... ")
n = try_exp()
i = 0
while n != 26:
guess(n)
i += 1
n = try_exp()
print(f"You guessed it! It took you {i} guesses.")
counter()
Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:
def try_exp():
first_input = True
while True:
try:
if first_input:
n = int(input("What is your guess? "))
return n
else:
n = int(input("Bad input! Try again: "))
return n
except ValueError:
first_input = False
In this, we go through an infinite loop, and we have a flag that designates whether it is the first guess or if they have already guessed before. If it is the first guess, we ask them for input, and if it is the second guess, we tell them that they gave incorrect input and ask for more input. After receiving correct input, the function returns n. If the input is incorrect which is when it is not an integer, we set first_input as false. Then, the while loop loops again. It will keep on waiting for input until they submit an integer.

while if statements, am not sure how to use a while statement when a name is not equal to quit

I am learning how to do while if statements and am unsure how to do step 2 in this program, "use a while statement to test when the name is not equal to quit". I tried to assign a variable to "name" but am not sure if that is the right way to go about it.
# Write the statements requested in Steps 1-6 below
# See the examples in the provided code
# Use structured programming and indent your code.
# Programmer Name: *****add your name here****
import random
# uses randrange instead of randint for better results in Python 3.7
# randrange stops just before the upper range, use (1, 11) for 1-10
num = random.randrange(1, 11)
# Step 1: Ask the player to enter a name or quit to exit
print("Hi, please enter your name or type 'quit' to exit.")
# Step 2: use a while statement to test when the name is not equal to quit
a=name
while a
# Step 3: input enter a number from 1 to 10 for the variable your_guess
# display the number guessed
print("Your number is", your_guess)
while num != your_guess:
# Step 4: Write an if statement for your_guess is less than num
print("Your guess is too low.")
your_guess = int(input("Guess another number from 1 to 10: "))
elif your_guess > num:
print("Your guess is too high")
your_guess = int(input("Guess another number from 1 to 10: "))
else:
break
print("The correct number was", num)
# Step 5 display text with your guess and You won, name
print("***************************************************************")
# Step 6 ask the player to enter a name or quit to exit
num = random.randrange(1, 11)
print("Thank you for playing!")
The program is bascially asking you to check whether the user has typed in quit instead of a number.
I don't see you take in the input entered by the user in the program, maybe you should try and do
print("Hi, please enter your name or type 'quit' to exit.")
your_guess = input()
Then you have to check whether your_guess is equal to 'quit' because that should terminate the loop (stop it from running and exit the program).
while your_guess != 'quit':
P.S. Make sure to say your_guess = int(your_guess) to convert it to a string inside the loop, or else it will be evaluated as a string.

Basic guessing game not functioning the way I want it to [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
I'm trying to get this game to run ad infinitum until the user enters "q" or "quit". For some reason, this isn't quite working out with what I have. I initially tried to do this with two functions but failed miserably, so I consolidated for right now into one function to try to get it going. Still failing, but not as bad.
#Ex9: Guessing game. Generate a number between 1-9 and provide info whether its too high or low
import random
#print("Type q or quit to quit")
#guess = int(input("Please enter a number between 1 to 9: "))
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1 == "quit".lower() or "q".lower():
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")
guessing_function()
Basically the issue is that the script just stops after one loop, rather than continue on without the user's input.... Not sure what I'm doing wrong.
Looks like you want to check if the user wanted to quit.
checking "quit".lower() is not correct. "quit" is already lower.
Also the or part of the if statement is incorrect. It will always be True.
Instead you want to check if lowercase of quit1 is either "quit" or "q".
You can do that by giving if quit1.lower() in ("quit","q"). By using in ("quit","q"), the if statement checks against the items in the tuple. This is a much better way to check when you have multiple values to check.
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1.lower() in ("quit","q"): #fixed this line
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")
print doesn't prompt for user input(and returns None always), you should replace it with input instead.
The if is also wrong, it should be if quit1 == "quit" or quit1 == "q":. How to test multiple variables against a value? explains it better than I could.

Function and loop debugging [duplicate]

This question already has answers here:
Loop until a specific user input is received in Python [duplicate]
(3 answers)
Closed 4 years ago.
This is code I wrote, it runs perfectly and so does the function this code is from except for one part, when it comes to the part where I ask the user if they want to try again, if they select no then it stops which is what is suppose to happen. On the other hand, if they say yes ‘y’ they will get another exact same prompt 'Would you like to try again? (y/n) '. You can say y 100 times and nothing will happen, my goal is for the code to go back and call the function from the start. I have tried a break if the user says ‘y’ to try and get out of the loop etc but it did not work and I now have no idea…
Additionally, as you can see, I have correct digits which compares to see if the user guessed number is in the generated list, that part I have no problem with. Now with the correct locations, I am not sure how to do that, the goal is to check is both the number and location is the name in both lists.
import random
play = True
turnsleft = 1
#this is a function that is in charge of generating a random password
def generatePassword():
generatePassword = [] #create an empty list
for i in range(1,6):
generatePassword.append(random.randint(1,9))
return generatePassword
'''this is a function that prompts the userfor their guess
the input will be comprimised of 5 different variables to store
the different numbers which will then all be added to the list of user number'''
def getUserGuess():
getUserGuess = [] #create an empty list
v1,v2,v3,v4,v5 = input("Please take a guess of the password by entering 5 numbers(comma between each): ").split(",")
v1,v2,v3,v4,v5 = int(v1), int(v2), int(v3), int(v4), int(v5)
for i in(v1,v2,v3,v4,v5):
getUserGuess.append(i)
return getUserGuess
#this function will compare the cpu generated password to the user inputed numbers list
def reportResult(generatePassword,getUserGuess):
correctdigits = 0
correctlocations = 0
global turnsleft #use the play variable initiated outside the funtion
global play #use the play variable initiated outside the funtion
while play is True:
if getUserGuess == generatePassword:
print("Congradulations! You have guessed the right password.")
elif turnsleft == 0:
print("You will never guess my password! It was " +str(generatePassword()))
playagain = input("Would you like to play again? (y/n) ")
if playagain == 'n':
play = False
else:
turnsleft-= 1
for e in getUserGuess():
if e in generatePassword():
correctdigits+= 1
for e in getUserGuess():
if e in generatePassword():
correctlocations+= 1
print(str(turnsleft) +" guesses left.")
print(str(correctdigits) +" of 5 correct digits.")
print(str(correctlocations) +" of 5 correct locations.")
return reportResult
while play is True:
reportResult(generatePassword,getUserGuess)
I believe you simply need to set 'turnsleft' to some value greater than 0 in when 'turnsleft' is 0.
For example:
elif turnsleft == 0:
print("You will never guess my password! It was " +str(generatePassword()))
turnsleft = 2 #<-- Reset turns here!
playagain = input("Would you like to play again? (y/n) ")
if playagain == 'n':
play = False
This will allow you to 'start a new game' with the turns set to some value. But it also introduces new problems. Perhaps you should write a resetGame() that will edit all the variables it needs to to truly start from scratch.

How do I have python run (if statements) based on the users input.?

I am not doing anything particularly complicated I am simply messing with import random and having the user type roll to roll a six sided die. I have gotten this far.
import random
roll = random.randint(1,6)
input("Type roll to roll the dice!\n")
# This is where I have my issue pass this line I'm trying things out, unsuccessfully.
if (userInput) == (roll)
print("\n" + str(roll))
else:
input("\nPress enter to exit.")
I don't want the program to print the str(roll) if the use presses enter, I'd rather it exit the program if no input is given. So how do I write the code to do particular thing based of user input when using the if statement. If user input is 'roll" then print("str(roll))?
You need to capture the user input in a variable. Currently, the return value of input(…) is being thrown away. Instead, store it in userInput:
userInput = input("Type roll to roll the dice!\n")
The if requires a colon at the end in order to start the block:
if someCondition:
# ^
If you want to compare the user input against the string 'roll', then you need to specify that as a string, and not as a (non-existent) variable:
if userInput == 'roll':
You also don’t need parentheses around the values
In order to check for just an enter press, check against the empty string:
elif userInput == '':
print('User pressed enter without entering stuff')
You should roll inside the condition, not before, so you don’t generate a random number although it’s not requested.
So in total, it could look like this:
import random
userInput = input('Type roll to roll the dice!\n')
if userInput == 'roll':
roll = random.randint(1,6)
print('You rolled: ', roll)
elif userInput == '':
print('Exit')

Categories

Resources