Remove string from x = float(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 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.

Related

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

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.

Python: detecting a input error and how to give a solution to it [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am a beginner in python and made a couple of programs, one of the same things I see, is that when ever I make a code like this
do = int(input("Enter number >"))
I accidentally type a letter, I want to be able to give like a wrong input message and try again, but python would always detect the difference in variable container.
You can catch ValueError:
success = False
while not success:
try:
do = int(input("Enter number >"))
success = True
except ValueError:
print("Wrong input, please try again")
I would suggest having a validation function. You can then use this function in other Python programs in the future.
def validate_int(inp):
try:
int(inp)
return True
except Exception:
print('Invalid input')
return False
This function will return true or false depending on whether a number has been entered.
You can then call the function like this:
inp = input('Enter number >')
while validate_int(inp) == False:
inp = input('Enter number >')

How would I go about while looping this code? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
So I'm creating a part of my program that raises a error when the user doesn't input a integer. Below is my code...
try:
pw_length_ask = int(raw_input("How long would you like your password to be? "))
final_pw_length = pw_length + int(pw_length_ask.strip())
print("Pass length set to " + str(final_pw_length))
except ValueError:
print("You must enter a number.")
int(raw_input("How long would you like your password to be? "))
It works great until the user is asked to enter a number again...
ValueError
It just throws a ValueError then crashes. So how do I make it so that instead of giving the Value Error it repeats the question until the user gives correct input?
You could put it in a while loop, like this:
while True:
try:
pw_length_ask = int(raw_input("How long would you like your password to be? "))
final_pw_length = pw_length + int(pw_length_ask)
print("Pass length set to " + str(final_pw_length))
break
except ValueError:
print("You must enter a number.")
The error likely came from the input you placed in the except block.

How would I implement the try/except/else structure to my code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
for my Informatics class assignment it is asking me to use a try/except/else structure to my code. I know im not supposed to post beginner friendly questions on this website but I am in need of help.
Check that the user enters a valid month number and a valid day number. Use a try/except/else structure to ensure numeric data is entered. I already have the if/else structure.
I do not know if the question is asking me to use one of them or all three.
Here is my code and it works perfectly fine:
#This program will ask the user to enter a month (in numeric form), a day in a months, and a two-digit year.
#Then, determine if this is a special date(the month times the day equals the year).
#Special Date
print("The date February 10, 2020 is special because when it is written in the following format the month times the day equals the year : 2/10/20.")
#Inputs
userInputMonth = int(input("Please enter a valid month:"))
userInputDay = int(input("Please enter a valid day:"))
userInputYear = int(input("Please enter a valid two-digit-year:"))
print()
if userInputMonth * userInputDay == userInputYear:
print("The date you provided " + str(userInputMonth) + "/" + str( userInputDay) + "/" + \
str(userInputYear) + " is the special date.")
else:
print("The date you provided " + str(userInputMonth) + "/" + str(userInputDay) + "/" + \
str(userInputYear) + " is not the special date.")
I just need to figure out how to implement the try/except/else structure to make sure that its a valid month, valid day, valid year.
Try-except-else in Python works roughly in this way:
try:
dosomething() # see if something works
except:
handleproblem() # it didn't work, handle the problem
else:
domorestuff() # it did work, proceed normally
In your case, parsing user input would be something that could fail, like if the user input was abc instead of a number.
try:
usermonth = int(input("Please enter a valid month:"))
except ValueError as e:
print("Please provide a numeric input next time")
else:
print("Thank you, month is ok")
That is not a full solution to your problem, but should get you started.
Use a try/except/else structure to ensure numeric data is entered.
My interpretation of this requirement of your assignment is that you are supposed to do just what I lined out above, use try-except-else to make sure the user did in fact enter numeric data.
To give a litte hint on how the structure of your final program could look like:
collect user input into variables (do not parse yet, just store it)
try to parse stored user input with int()
if (2) fails with exception, print a scolding message
else print nice message, do that special date thing, etc
Are you looking for something like this?
try:
userInputMonth = int(input("Please enter a valid month:"))
except ValueError as error:
print(str(error))
else:
print("Input month is ok!")
If userInputMonth is wrong, the above program will print an error message.
Edit: You can modify your code as follows.
while True:
try:
userInputMonth = int(input("Please enter a valid month:"))
except ValueError:
print("Please provide a numeric input for the month. Try again...")
else:
break
while True:
try:
userInputDay = int(input("Please enter a valid day:"))
except ValueError:
print("Please provide a numeric input for the day:")
else:
break
while True:
try:
userInputYear = int(input("Please enter a valid two-digit-year:"))
except ValueError:
print("Please provide a numeric input for the year.")
else:
break

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