IF statement error new variable input python - python

The problem here is that I just cant get python to check if Currency1 is in string, and if its not then print that there is an error,but if Currency1 IS in string then move on and ask the user to input Currency2, and then check it again.

You can use try-except:
def get_currency(msg):
curr = input(msg)
try:
float(curr)
print('You must enter text. Numerical values are not accepted at this stage')
return get_currency(msg) #ask for input again
except:
return curr #valid input, return the currency name
curr1=get_currency('Please enter the currency you would like to convert:')
curr2=get_currency('Please enter the currency you would like to convert into:')
ExRate = float(input('Please enter the exchange rate in the order of, 1 '+curr1+' = '+curr2))
Amount = float(input('Please enter the amount you would like to convert:'))
print (Amount*ExRate)
output:
$ python3 foo.py
Please enter the currency you would like to convert:123
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert:rupee
Please enter the currency you would like to convert into:100
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert into:dollar
Please enter the exchange rate in the order of, 1 rupee = dollar 50
Please enter the amount you would like to convert: 10
500.0

You were actually trying for:
if type(Currency1) in (float, int):
...
but isinstance is better here:
if isinstance(Currency1,(float,int)):
...
or even better, you can use the numbers.Number abstract-base class:
import numbers
if isinstance(Currency1,numbers.Number):
Although ... Currency1 = str(raw_input(...)) will guarantee that Currency1 is a string (not an integer or float). Actually, raw_input makes that guarantee and the extra str here is just redundant :-).
If you want a function to check if a string can be converted to a number, then I think the easiest way would be to just try it and see:
def is_float_or_int(s):
try:
float(s)
return True
except ValueError:
return False

Related

Issue with int(input) error comes up if someone puts in a float. How to fix

Im currently working on a project for my coding class. The prompt is to make an atm interface.
All of my code is currently working but when it comes to the function of deposit() it asks for a whole number to be entered where I use int(input) say someone inputs a float like 45346.4 it comes up with an error. Is there a fix to this?
here is my code currently for the deposit function. The balance is already given outside of this function.
def deposit():
balanced = balance
print(f'Your current balance is ${balanced}\n------------------------------')
print('How much money would you like to deposit?\n---------------------------\n You can only deposit in whole numbers')
deposit_amount = int(input('Enter here:'))
if deposit_amount.is_integer():
balance_a_d = balanced + deposit_amount
print(f'You Current Balance is ${balance_a_d}\n-------------------------------\nHave a great day!')
quit()
else:
print('----------------------------\nThat is not a whole number please try again\n----------------------------')
deposit()
You could use a while loop and a try block to keep asking for input until ValueError is no longer raised.
Something like this:
number = None
while number == None:
try:
number = int(input('Enter here:'))
except ValueError as e:
print('Please enter a whole number.')
I have a general purpose input function which is simple to use and saves a lot of repeated code.
def getInput(prompt, t=str):
while True:
v = input(f'{prompt}: ')
try:
return t(v)
except ValueError:
print('Invalid input')
If I just want text input then:
getInput('Enter some text')
Of course, for plain text, this isn't really necessary.
If I want a float then:
getInput('Enter a float', float)
Or int:
getInput('Enter an integer', int)
This saves you from having to "wrap" all your inputs in try/except as it's all handled for you

Validate floating values from user input

This function will take a string as input. The string has the following properties:
Includes characters 0-9
May include period to denote cents. (If not
included assume 0 cents.)
May include $ sign.
May include commas as
digit separators.
Your function will convert the string into a floating point number. You may not use any built in commands like int or float. You must solve this problem by analyzing the characters in the string of text.
If the input is invalid, return -1 as the function's result.
If I input the following:
100.00
200
98.78
$1,009.78
Goat
exit
This is what the output looks like:
Determine Price with Tax.
Enter 'exit' at any time to quit.
Enter Amount ($X,XXX.XX):
Amount: 100.0
Tax: 6.0
Price w/ Tax: 106.0
Enter Amount ($X,XXX.XX):
Amount: 200
Tax: 12.0
Price w/ Tax: 212.0
Enter Amount ($X,XXX.XX):
Amount: 98.78
Tax: 5.93
Price w/ Tax: 104.71
Enter Amount ($X,XXX.XX):
Amount: 1009.78
Tax: 60.59
Price w/ Tax: 1070.37
Enter Amount ($X,XXX.XX):
Amount: -1
Tax: -0.06
Price w/ Tax: -1.06
Enter Amount ($X,XXX.XX):
My code is:
def price_to_int(text):
res = 0
valid = "$,.1234567890"
for l in text:
if l in valid:
res = float(text)
else:
return -1
return res
#---------You may not make any changes below this line-----------
print("Determine Price with Tax.")
print("Enter 'exit' at any time to quit.")
word = input("Enter Amount ($X,XXX.XX):\n")
while word.lower() != "exit":
d = price_to_int(word)
tax = 0.06
print("Amount:",round(d,2))
print("Tax:",round(d*tax,2))
print("Price w/ Tax:",round(d+d*tax,2))
word = input("Enter Amount ($X,XXX.XX):\n")
The only thing wrong is the function definition. My code works up until I input '$1009.78'. I am specifically asked to only rewrite the function definition and not change anything else.
Your current solution does not seem right to me. You are iterating over your string character-by-character, coercing each argument. You'd want to convert the entire string at once (otherwise, how are you going to get your float?).
Would you like a solution that does exception handling using try ... except?
def price_to_int(text):
clean_text = text.lstrip('$').replace(',', '')
try:
return int(clean_text)
except:
try:
return float(clean_text)
except ValueError:
return -1
This solution cleans your string and attempts to cast to float. If the conversion is not possible, an error is raised and handled, and -1 returned.
Details
str.lstrip removes the leading $ character
str.replace removes commas (when the second argument is the empty string)
try ... except ValueError: ... will attempt to run code inside the try block while waiting to catch a ValueError exception. If the exception is raised, the code inside the except block is executed (otherwise no).

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")

While loop to identify integer in Python

I'm trying to write a program to calculate densities, and I have tried to create a while loop the prevents the user from entering nothing or a non-number for the volume.
But when I run the program the it just loops "You have to type a value" forever. I've tried the same code in a for loop and it does work after inputing 2 numbers.
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while Volume == ("") or type(Volume) != int:
print("You have to type a value")
Volume = input()
return float(Volume)
This solution is written assuming you are using Python 3. The problem in your code is that you are assuming that if you type in a number, the input method will return a type int. This is incorrect. You will always get a string back from your input.
Furthermore, if you try to cast int around your input to force an int, your code will raise if you enter a string, with:
ValueError: invalid literal for int() with base 10:
So, what I suggest you do to make your implementation easier is to make use of try/exceptinstead to attempt to convert your value to a float. If it does not work, you prompt the user to keep entering a value until they do. Then you simply break your loop and return your number, type casted to a float.
Furthermore, because of the use of the try/except, you no longer need to put in a conditional check in your while loop. You simply can set your loop to while True and then break once you have satisfied your condition in your code.
Observe the code below re-written with what I mentioned above:
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while True:
try:
Volume = float(Volume)
break
except:
print("You have to type a value")
Volume = input()
return Volume
def GetVolume():
Volume = input("How many cublic cm of water does the item displace")
while not Volume.replace('.', '').replace(',', '').isdigit():
Volume = input("You have to type a value")
return float(Volume)
x = GetVolume()
print(x)
You have to modify your while because is validating that is str or different than int. An input will always be an str by default unless you modified the type with int() or float() in your case.
You can use 'try' instead to check for this:
while True:
x = input("How many cubic cm of water does the item displace")
try:
x = float(x)
break
except ValueError:
pass
print('out of loop')

How do I provide error checking to ensure user input only allows letters and provides a looping error message if numbers are typed?

I am trying to provide a looping error message to the user for the customerName input so that the user receives an error message if they type anything other than letters aA - zZ,(I don't want to allow the user to input numbers specifically). I would like it to operate similar to the one I used for the customerAge input( which i provided as an example). but I cant seem to figure out the correct code to accomplish this. can anyone provide some insight?
customerName = input('Enter your name: ')
customerAge = int(input('Enter your age: '))
while customerAge <= 15 or customerAge >= 106:
print('Invalid entry')
customerAge = int(input('Enter your age: '))
after reviewing all the answers I received (thanks goes out to all of you for the help). I coded it like this and it appears to be operating correctly.
customer_name = input('Please enter your name: ')
while not customer_name.isalpha():
print('invalid Entry')
customer_name = input('Please enter your name: ')
Let's start with what your program needs to do:
Loop until the input is valid
That will be it for all kinds of validation that are in the form of:
1) User inserts something
2) Something is wrong
3) Program informs user and asks for input again
So, in python:
valid = False
while not valid:
valid = True
customer_name = input('Enter your name: ')
customer_age = int(input('Enter your age: '))
if customer_age <= 15 or customer_age >= 106:
print 'Enter a valid age'
valid = False
if not customer_name.isalpha():
print 'Enter a valid name'
valid = False
What we did here:
1) Set valid to True, so the happy case will let us out of the loop
2) Obtain both values
3) If any of them is invalid, set valid to False and inform the situation
You can even use 2 loops to validate separately.
A note on the isalpha() method: You can find the documentation here and some good info about it in this question
Also, as a bottom line advice: never use camel case in python variables.
That notation is reserved for Class names. For variables, use lower case and _
Regex should do what you want
import re
while 1:
name = raw_input("Enter your name: ")
if re.search(r'(?i)[^a-z]', name):
print("Invalid name")
else:
break
Check the type of each character with the type() function.
u_input = raw_input()
valid = ""
for char in u_input:
if str(type(char)) == "<type 'int'>":
valid = "False"
break
else:
pass
if valid == 'False':
print 'This string has a number! Gosh darn it!"
Place this in a function/while loop, and you have your looping error message. You can add other loops to ensure any other parameters.
This is the easiest, and likely the most efficient way.
More information on type() here: https://docs.python.org/2/library/functions.html#type

Categories