i cant seem to break out of this while loop [duplicate] - python

This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed last year.
i took a comp class in my college and its in the real early stages. i was asked to make this little program which plays madlibs and now i cant seem to complete it.
import random
verb=input("Enter a verb: ")
celebrity= input("Enter name of a celebrity: ")
age=input("Enter an age: ")
while not age==int():
age=(input("C'mon man! Enter a number please: "))
madlibs=f"Coding is fun as if im {verb}. I feel like im {celebrity} and im just {age} years old"
print(madlibs)
again im really new at this so if you have any feedback how i can write the same code in lesser lines and feedback like that, its highly requested

input() function always return a string. It won't be dynamically casted,
you can use isdecimal() str method.
If you want to use age as a number don't forget to cast it.
You can replace this part:
while not age==int():
age=(input("C'mon man! Enter a number please: "))
by:
while not age.isdecimal():
age=input("C'mon man! Enter a number please: ")
age = int(age) # cast str > int
Furthermore, if you want to check your variable type, age==int() condition is not valid, use isintance function instead.

I would do something like this
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("ERROR, you must enter a number")
Bear in mind that this will only work if you introduce an integer number, which I think is what you tried to do in your code. If you want to allow decimal numbers #Felix has given an answer using .isdecimal()

You need to define seperate variables for age_target and age_guess.
Then
While not age_target == age_guess

Here is a working example:
import random
verb = input("Enter a verb: ")
celebrity = input("Enter name of a celebrity: ")
age = input("Enter an age: ")
while True:
try:
int(age)
break
except ValueError:
age=(input("C'mon man! Enter a number please: "))
madlibs=f"Coding is fun as if im {verb}. I feel like im {celebrity} and im just {age} years old"
print(madlibs)
What it does differently:
int(age) is trying to convert the string age to an integer. If this is not possible, it will throw a ValueError.
We catch that ValueError and prompt the user to try again.
If we don't have the while True (keep looping forever) statement, the flow would be the following:
Checking the age against integer. Fail.
Prompt the user again.
Go on to the madlibs statement.
With the while True loop we will stuck the user to the very same prompt till the int(age) doesn't succeed (or at least fail with another type of exception), than we break, which will exit the loop end procede to the next statement.

Related

Trying to understand If statements when trying to incorporate user Input

I'm an absolute beginner - like I'm Today-years-old with this.
So I'm mucking about with a silly little piece of code to try and help me understand If statements:
print ('How many sausages have you eaten today?')
userInput = ('>5' or '<5')
if userInput input == int ('> 5'):
print ('Whoa! Slow down Fatty!')
elif userInput input == ('< 5'):
print ('Ok, but better call it a day now')
I'm trying to alter the printed message based on how many sausages the user inputs - e.g. above 5 or below 5.
I know that I'm doing something (probably many things) wrong.
Can anyone help to tidy this up?
Here is a fixed version:
There is some notes to help you understand
# To get an input you need to use input()
userInput = input('How many sausages have you eaten today?')
# Turn the input from text to a number with int()
userInput = int(userInput)
if userInput > 5:
print ('Whoa! Slow down Fatty!')
elif userInput < 5:
print ('Ok, but better call it a day now')
Your code has a few problems. First, you cannot use int() to get user input. Instead, you must use input(). Second, you cannot convert inequalities into integers. Like this:
print('How many sausages have you eaten today?')
userInput = int(input())
if userInput > 5:
print('Whoa! Slow down Fatty!')
else:
print('Ok, but better call it a day now')
Notice how I get user input with input(), which will return a string. Then, I convert it to an integer with int(). If the user inputs something that is not an integer, then the program will crash because the input to int() must be able to be converted into an integer.
In the if-else statement, I check if userInput, which is an integer, is greater than 5. I also used an else statement, not an elif, because if userInput is exactly 5 then neither statement would have been true.

how to deny someone to enter something using python input function

Ok the title is a bit weird. But, basically what i want to ask is:
read = input("Enter some numbers: ")
# The user should only enter numbers and nothing else
But the thing is the user can enter something else other than a numerical value.
How do i stop someone from entering an alphabet in realtime from the terminal?
Lets say the user inputs 123 then enters an "e". How do i make this e not even appear on the
terminal even if the user presses the e key?
you can repeat asking int values if user enters a string.
while True:
try:
# 👇️ use int() instead of float
# if you only accept integers
num = float(input('Your favorite number: '))
print(num)
break
except ValueError:
print('Please enter a number.')

Remove string from x = float(input(" ")) in Python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 11 months ago.
I am working on a Paycheck calculator as a little side project for my portfolio and I have it so that users can input their own information (i.e. pay rate, hours worked, shift differentials, etc.) and parts of my code have inputs for variables:
payrate = float(input("What is your current payrate? $"))
When the code is run it asks the user to enter a value for their pay, but if they enter $20 instead of 20, I get:
ValueError: could not convert string to float: '$20'
How can I optimize my code so that it either ignores the $ when a user inputs something other than a float or it gives a rejection message to the user that I can write out myself in plain English so they know what to do?
Thank you!
Github link in case anyone wants to check it out for themselves (warning: still a massive WIP... so be gentle)
You an define a method called isfloat:
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
payrate = input("What is your current payrate? $")
if isfloat(payrate):
payrate = float(payrate)
# Do some math
else:
print("Please enter a number.")
exit()
print(payrate)
Something like this should do what your question asks:
while True:
s = input("What is your current payrate? $")
try:
payrate = float(s)
break
except ValueError:
print("Couldn't parse you input as a number. Please try again")
print(f"Thanks, payrate is {payrate}")
The loop keeps going until a float is successfully parsed. Each time a parse fails (in other words, each time our attempt to convert the string s to a float raises an exception), it prints an informational message in the except block.

Python data type validation integer

Hello I am creating a registration program and need to ask the user to input their age . However I want to make sure its not a letter by just consisting of numbers. How do I limit the user to only getting a number and if they input other character a error message shows up
while True:
age = int(input("Age: "))
if not (age) != int:
print ("Not a valid age")
continue
else:
break
You can use try and except statements here.
try:
age=int(age) #Do not typecast the age variable before this line
except ValueError:
print("Enter number")
If you do not want the program to proceed until the user enters a number, you can use a flag variable and put the code block mentioned above in a while loop.

How to loop a try and except ValueError code until the user enters the coorect value? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I have this code:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
phone = int(input("Enter your telephone no. : "))
I want the user to enter their telephone number. But if they type anything else apart from integers an error message comes up saying that you can only type integers. What I want to do is to loop this section of the code so that every time the user enters a non-integer value the error message comes up. So far all this code does is, it prints the error message only for the first time. After the first time if the user enters a non-integer value the program breaks.
Please provide a not too complicated solution...I'm just a beginner.
I'm thinking you're meant to use a while loop but I don't know how?
I believe the best way is to wrap it in a function:
def getNumber():
while True:
try:
phone = int(input("Enter your telephone no. : "))
return phone
except ValueError:
pass
You can do it with a while loop like this
while True:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
else: # this is executed if there are no exceptions in the try-except block
break # break out of the while loop

Categories

Resources