Python3 While Loop jumping to else statement - python

Im in my first couple of weeks of programming. I am trying to make a function that asks for a users input, checks whether or not that input is alphabetic, if it is alphabetic then i want to break the while loop.
If I run the script and enter the correct types in the input it breaks and works fine. If I intentionally put a number in the input field it doesn't break out of the loop when I reenter the correct type.
any ideas on what im doing wrong?
def wallType():
wall_type = input("What type of wall was the route on? ")
while wall_type:
#if there is text in the input,instead of an alphanumeric, then tell them they must put in a number.
if str.isalpha(wall_type):
return wall_type
else:
print("You entered a number, you must enter a word. Try again. ")
wallType()

Put your code in a while True loop. When input received is alphabetic, use break to break out of while loop. Else loop again to ask for input.
def wallType():
while True:
wall_type = input("What type of wall was the route on? ")
# string is alphabetic, break out of loop
if str.isalpha(wall_type):
break
else:
print("Please reenter an alphabetic word. Try again. ")

Related

I dont know how to do error handling with incorrect inputs

im trying to make it so in a part of my code where a user enters their name that they cant enter a number, without the program crashing. I am also trying to do the same with some other parts of my code aswell
I havent tried anything as of now
enter code here
myName = str(input('Hello! What is your name?')) #Asks the user to input their name
myName = str(myName.capitalize()) #Capitalises the first letter of their name if not already
level = int(input('Please select a level between 1 and 3. 1 being the easiest and 3 being the hardest'))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
again = int(input("Would you like to play again? Input 1 for yes or 2 for no?" ))
# Is asking the user if they want to play again.
if again == 1:
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
You should post the code of guessNumber().
kinda difficult to understand question anyway I'd do this.
To accept a string and if the value entered is int it'd give the message but you can't differentiate as int cant be str but str can be a number.
try:
myName=str(input("Enter name\n"))
except ValueError as okok:
print("Please Enter proper value")
else:
printvalue=f"{myName}"
print(printvalue)

How to make a user input both a string and integer

I'm trying to create a game that is kind of along the lines of the game mastermind.
I have a section where the user has to either guess the number or type "exit" to stop the game. How do i make it so that the code allows both an integer and string input?
The code is:
PlayerNum = int(input("Type your number in here:"))
if PlayerNum == "exit":
print "The number was:",RandNum1,RandNum2,RandNum3,RandNum4
print "Thanks for playing!
exit()
If anyone could help that would be great.
Thanks. :D
you can use isdigit() function to check whether input is int or string.
Let user has input "32" then "32".isdigit() will return True but if user has input "exit" then "exit".isdigit() will return False.
player_input = input("enter the number")
if player_input.isdigit():
# Do stuff for integer
else:
# Do stuff for string
PlayerNum = input("Type your number in here:")
Well You can remove the int so that it takes both integet and string as input
Integer and String classifications are specific to Python (they are functions). When the user types in their response, that would be interpreted by the system as stdin (standard input).
Once the stdin is entered by the user and allocated under the PlayerNum variable, you are free to convert it to an int/str/bytes as you please.

Python not responding in loop

Here is my code:
from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
now, that works fine, if I happen to get the unlucky number.
else :
print("You entered a room.")
doorNum = randint(1, 3)
This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.
I am new to programming in Python, I spent most of my time as a web developer.
UPDATE:
Thanks #rawing, I can not yet upvote (newbie), so will put it here.
If you are using python3, then input returns a string and comparing a string to an int is always false, thus your exit() function can never run.
Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like print(type(doorInp)) after your input line.
To fix it, just enclose the input statement inside int() like:doorInp = int(input("...."))
In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.
I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:
from random import randint
while True:
doorNum = randint(1, 3)
doorInp = int(input("Please Enter A Door Number Between 1 and 3: "))
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
break
print("You entered a room.")
See also: Asking the user for input until they give a valid response

Looping the function

I have this function below, which I have done something wrong in somewhere.
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:
try:
int(i)
return int(quantity)
valid = True
except ValueError:
print("We didn't recognise that number. Please try again.")
#If I get here, I want to loop back to the start of this function
return True
return False
To run through, the function is called from the main part of the program like so: quantity = quantityFunction(product)
The return False at the bottom of the code is to do with if product is None, which is needed after a bit of code in another function but has had to go in this function.
If the user input for quantity is a number, all works fine. If it is anything else, the Value Error is printed and you can enter another input. If you put another letter etc in, it repeats again, if you put a number in, it accepts it.
However, it does not return the number you inputted after the letters. It just returns 0.
I suspect this is something to do with how I am repeating the code, i.e. the code should loop back to the start of the function if it hits the Value Error.
Any Ideas?
You said:
the code should loop back to the start of the function if it hits the Value Error.
Then you should not use return statements, otherwise the function will terminate, returning True or False.
Few issue:
1) return statement returns control to the calling function.
2) You are looping over the input, which is wrong.
3) valid=True isn't executed at all.
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity)
#valid = True (since it is never run)
except ValueError:
print("We didn't recognise that number. Please try again.")
#If I get here, I want to loop back to the start of this function
#return True
return False
quantityFunction("val")
Note : Use raw_input() in case of Python 2.7 and input() in case of 3.x
Try this (some formatting included too, but the functionality should be the same):
def determine_quantity(product): # descriptive function name
if not product: # avoiding nesting
return False
while True:
quantity = input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity) # try to convert quantity straight away
except ValueError:
print("We didn't recognise that number. Please try again.")
# nothing here means we simply continue in the while loop
Ideally, you'd take product out. A function should do as little as possible, and this check is better off somewhere else.
def determine_quantity():
while True:
quantity = input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity)
except ValueError:
print("We didn't recognise that number. Please try again.")
First, let's address the code. Simply stated, you want a function that will loop until the user enters a legal quantity.
product doesn't do much for the function; check it in the calling program, not here. Let the function have a single purpose: fetch a valid quantity.
Let's work from there in the standard recipe for "loop until good input". Very simply, it looks like:
Get first input
Until input is valid
... print warning message and get a new value.
In code, it looks like this.
def get_quantity():
quantity_str = input("Please enter the amount of this item you would like to purchase: ")
while not quantity_str.isdigit():
print("We didn't recognise that number. Please try again.")
quantity_str = input("Please enter the amount of this item you would like to purchase: ")
return quantity
As for coding practice ...
Develop incrementally: write a few lines of code to add one feature to what you have. Debug that. Get it working before you add more.
Learn your language features. In the code you've posted, you misuse for, in, return, and a function call.
Look up how to solve simple problems. try/except is a more difficult concept to handle than the simple isdigit.
You should try this..
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
if quantity.isdigit():
return int(quantity)
valid = True
else:
print("We didn't recognise that number. Please try again.")
continue
return False
quantity = quantityFunction("myproduct")

Checking for user error in Python

I am trying to analyse user input and only allow integers to be inputted. I have succesfully managed to only allow denominations of 100s between a certain range, but I cannot work out how to prompt the user to re-enter data if they enter a random string.
Trying to use the "try" command just results in the program getting stuck:
while True:
try:
bet=int(raw_input('Place your bets please:'))
except ValueError:
print 'l2type'
#The following receives a betting amount from the user, and then assesses whether it is a legal bet or not. If not, the user is prompted to enter a legal bet.
while True:
if bet%100==0 and 100<=bet<=20000:
print bet,"Your bet has been accepted, can you make a million?"
break
else:
print bet,"Please enter a legal bet. The table minimum is 100, with a maximum of 20000 in increments of 100."
bet = input('Place your bets please:')
You have the right approach for rejecting non-integer input, but you need to break out of the loop if your user enters valid input. Use the break statement:
while True:
try:
bet=int(raw_input('Place your bets please:'))
break # we only get here if the input was parsed successfully
except ValueError:
print 'l2type'
You will probably also want to move the range checks within the loop. If input that's out of range doesn't naturally lead to an exception, use if statements to make sure "break" is only executed if the input is completely valid.
I rather prefer my recursive version:
def ask_bet(prompt):
bet = raw_input(prompt)
# Validation. If the input is invalid, call itself recursively.
try:
bet = int(bet)
except ValueError:
return ask_bet('Huh? ')
if bet % 100 != 0:
return ask_bet('Huh? ')
if not 100 <= bet <= 20000:
return ask_bet('Huh? ')
# The input is fine so return it.
return bet
ask_bet("Place your bets please: ")
In my opinion, that is much cleaner and easier to read than while loops. You don't have to bother what are attribute values after the first iteration? Adding new validation rules is also really simple.
Generally, I try to avoid while loop in favour of recursive version. Of course, not all the time, since it's slower and the stack is not infinite.

Categories