allow only integers except one specific string - python

Is there a way to allow only integers except one specific string? I wrote a number guessing game in python and if the player decides to quit the game, the game should break through the user input "quit", while allowing only numbers during the guessing process.
Thank you in advance!

Check if input is digit and not 'quit' then continue game
print("Insert your number")
user_input = input()
if user_input.isdigit():
#continue your game
elif user_input == 'quit':
#quit game
else:
print("Invalid option. Type in a number or 'quit' for exit")

how about just checking for either numeric or 'quit'?
if input.isnumeric():
#proceed as with number input
elif input == 'quit':
#quit
else:
#invalid input

Related

How to make a while loop continue to loop if certain parameters aren't met?

still a beginner at programming, so forgive the mistakes:
I am trying to make my user-defined function loop until the user types in "no."
However, when I was adding extra functions to foolproof the loop, i.e. check to make sure what they typed was actually "yes" or "no" and not random garbage/numbers, it seems to run into problems. Here is the loop statement:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop != "no" or "yes":
print("INVALID INPUT")
elif stop == "no":
break
else:
continue
First "if" is checking whether the input was not "no" or "yes", next "elif" is checking if the input was "no" and if so stop the program, and "else" (yes) continue. Instead, it asks if I would like to continue, tells me "INVALID INPUT" no matter what, and continues. What am I doing wrong?
stop != "no" or "yes" is not the correct syntax. What you want is either not (stop=="no" or stop=="yes") or stop not in ["no","yes"].
Consider the following modified version of your code:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop not in ["no","yes"]:
print("INVALID INPUT")
elif stop == "no":
break
Note that the above, while it technically runs, will run percentConvert() in response to an invalid input. Here's a script that behaves in what I suspect is the desired way.
while True:
percentConvert()
while True:
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop)
if stop not in ["no","yes"]:
print("INVALID INPUT")
else:
break
if stop == "no":
break
In the loop as it's currently written, the condition is being interpreted as (stop != "no") or ("yes"). "yes" is a non-empty string, which Python considers to be a "truthy" value, which means that the or and if treat "yes" as if it were True, which means that the if-block always executes.
This is a good use case for using custom error handling.
First define the base class for errors, and a custom exception.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class InvalidInputError(Error):
"""Rasied when user input is not yes/no"""
pass
Then in your while loop, you can use the exception.
percentConvert()
while True:
try:
stop = input("Would you like to continue? yes or no: ".lower())
if stop == 'yes':
percentConvert()
continue
elif stop == 'no':
break
else:
raise InvalidInputError
except InvalidInputError:
print("Must enter either yes/no")

Why "While" doesn't show anything after input command? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
Just i did somethin wrong with while loop i supposed
After print menu section u can input something but than program ends.
print("Welcome in American Roulette")
rules=("blabla rules of roulette")
import random
while True:
print("Enter 'rules' to show rules")
print("Enter 'play' to play the game")
print("Enter 'author' to show info about creator")
print("Enter 'quit' to end the program")
user_input=input()
if user_input=="quit" or "Quit":
break
elif user_input=="rules" or "rule" or "Rules" or "Rule":
print(rules)
elif user_input=="play":
bet=int(input("Place your bet\n"))
amount=float(input("How much you want to bet?"))
spin=random.randint(0,36)
if bet>36:
print("You need to bet number beetwen 0 and 36!")
elif bet<0:
print("You need to bet number beetwen 0 and 36")
elif spin==bet:
print("You won",amount*35)
print("Now you have",start-amount+amount*35)
else:
print("You lose")
elif user_input=="author":
print("Jacob X")
else:
print("Unknown command")
Added some text here becouse my code is mostly code ffs
Your first if should be:
if user_input.lower() == "quit":
break
or
if user_input == "quit" or user_input == "Quit":
break
You are missing the second user_input on the conditional. As "Quit" is not an empty string it evaluates to True and your while loop will break.
This is also the case for this elif:
elif user_input=="rules" or "rule" or "Rules" or "Rule":

I want my function to accept small and capital letters in python

If I print a capital letter instead writing everything in small letters, the function doesn´t give me the correct output.
I would like to have the output "good bye", when I write: Quit quit QuIt
This is the Output right now if I take Quit or quit as an Input
Quit
This is not a valid option. Please try again.
quit
good bye
quit = True
​
help = ("""
start- to start the car
stop - to stop the car
quit - to exit
​
""")
​
print(help)
while quit:
operation = input(">")
if operation == "start":
print("Car started")
elif operation == "stop":
print("Car stopped")
elif operation == "quit":
print("good bye")
break
else:
print("This is not a valid option. Please try again.")
Use .lower() function on the input string to transform your text into lowercase.
So use operation = input(">").lower()
Here you can find a small docs
Convert your input to lower case.
operation = input(">").lower()

Asking for a specific input without using break

I'm creating a dice poker game and am trying to ask if the user would like to play before continuing with the game and then asking if the player would like to play again after each game.
I am unsure how to allow for incorrect inputs other than Y and N in order to tell the user to enter a correct answer and then loop the input until either is input. I am not allowed to use a break.
play = True
s = input("Would you like to play dice poker [y|n]? ")
if s == "y":
play = True
elif s == "n":
play = False
else:
print("Please enter y or n")
while play:
From here onward is the code for my game
This below section is repeated at the end of each game
again=str(input('Play again [y|n]? '))
if again == "n":
play = False
if again == "y":
play = True
else:
print('Please enter y or n')
wrap your input in a function that evaluates the user input, if it's not valid, call it recursively as necessary. Example:
def keep_playing():
valid = 'ny'
again=str(input('Play again [y|n]? '))
a = again.lower().strip() # allow for upper-case input or even whole words like 'Yes' or 'no'
a = a[0] if a else ''
if a and a in valid:
# take advantage of the truthiness of the index:
# 0 is Falsy, 1 is Truthy
return valid.index(a)
# Otherwise, inform the player of their mistake
print(f'{again} is not a valid response. Please enter either [y|n].')
# Prompt again, recursively
return keep_playing()
while keep_playing():
print('\tstill playing...')

not restarting for program and input integer not working

I'm trying to develop a program wherein at the finish of the game the user will input "Yes" to make the game restart, while if the user inputed "Not" the game will end. For my tries, I can't seem to figure out how to make the program work. I'm quite unsure if a double while True is possible. Also, it seems like when I enter an integer the game suddenly doesn't work but when I input an invalidoutpit the message "Error, the inputed value is invalid, try again" seems to work fine. In need of help, Thank You!!
import random
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
while True:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
else:
guess1=int(guess[0])
guess2=int(guess[1])
guess3=int(guess[2])
guess4=int(guess[3])
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
answer=input("Would you like to play again? (Yes or No) ")
if answer==Yes:
print ('Yay')
continue
else:
print ('Goodbye!')
break
Wrap your game in a function eg:
import sys
def game():
#game code goes here#
Then at the end, call the function to restart the game.
if answer=='Yes': # You forgot to add single/double inverted comma's around Yes
print ('Yay')
game() # calls function game(), hence restarts the game
else:
print ('Goodbye!')
sys.exit(0) # end game
try this
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
gueses=[]
while len(gueses)<=3:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
gueses.append(guess)
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
guess1=gueses[0]
guess2=gueses[1]
guess3=gueses[2]
guess4=gueses[3]
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
if P1=="x" and P2=="x" and P3=="x" and P4=="x":
print("you won")
else:
print("YOUE LOSE")
print("TRUE ANSWERS", A1,A2,A3,A4)
print("YOUR ANSWER", gueses)
game()
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print ('Yay')
game()
else:
print ('Goodbye!')
The previous answers are good starts, but lacking some other important issues. I would, as the others stated, start by wrapping your game code in a function and having it called recursively. There are other issues in the guess=int(input("\nTry and Guess the Numbers :). ")). This takes one integer as the input, not an array of integers. The simplest solution is to turn this into 4 separate prompts, one for each guess. I would also narrow the scope of your error test. I've included working code, but I would read through it and make sure you understand the logic and call flow.
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
if P1=="O" or P2=="O" or P3=="O" or P4=="O":
print("Here is your Clue :) :")
print(P1,P2,P3,P4)
try:
guess1=int(input("\nGuess 1 :). "))
guess2=int(input("\nGuess 2 :). "))
guess3=int(input("\nGuess 3 :). "))
guess4=int(input("\nGuess 4 :). "))
except ValueError:
print("Invalid Input")
continue
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
break
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print('Yay')
game()
else:
print('Goodbye!')
game()

Categories