So I have a homework on coding a bank ATM machine and I have done most of the code but I do not seem to make work like the professor stated "If the user enters an invalid numeric value, inform the user as such. If the user enters a valid number between 0 and 100, display the amount of funds left in the account"
example:
kitten : "Invalid Entry".
20.5 : "Your account has $79.50 remaining"
My code so far:
amt = int(input("Withdraw amount: "))
if amt <= 0:
print("Invalid Amount")
else:
print{"Invalid Entry")
if amt > 100:
print("Not enough funds in account")
if (amt >=0 and amt <=100):
print("Your account has ${0:1.2f} remaining." .format(100-amt))
My issue is that when I enter 20.5 it give me an error
"ValueError: invalid literal for int() with base 10: '20.5'"
The second issue is when I enter a string "ValueError: invalid literal for int() with base 10: 'kitten'"
The reason why entering 20.5 gives you an error is because in the amt variable, it is looking for an integer to be inputted. In python, any number with a decimal is considered a float.
The code for the amt variable is currently
amt = int(input("Withdraw amount: "))
For the amt variable to have a number with a decimal as acceptable input, the amt variable should be this:
amt = float(input("Withdraw amount: "))
You are converting everything to an int, so putting in strings and doubles will give you errors. You need to check the content of your input before blindly converting it to an int.
You need to think about what your code is actually doing instead of just blindly changing things until they work without understanding why.
Related
I just completed my pre-course assessment.
The project was:
A cupcake costs 6.50. If you purchase more than 6 cupcakes, each of them will cost 5.50 instead, and if you purchase more than 12, each of them will cost 5.00 instead.
Write a program that asks the user how many cupcakes they want to purchase, and display the total amount they have to pay.
My inputs have been:
amt=input("How many cupcakes would you like to but? ")
if amt>=6:
disc = amt*0.12
elif amt>=12:
disc=amt*0.24
print(disc)
I can't seem to get the code running. Can anyone please dump it down for me?
THE COMPLETE SOLUTION TO YOUR PROBLEM IS:
amt=int(input("How many cupcakes would you like to but? "))
if amt <= 6:
pancake_price_650 = 6.50
price_inferior_6 = amt * pancake_price_650
print(price_inferior_6)
elif amt > 6:
pancake_price_550 = 5.50
price_superior_6 = amt * pancake_price_550
print(price_superior_6)
elif amt > 12:
pancake_price_500 = 5.00
price_superior_12 = amt * pancake_price_500
print(price_superior_12)
You were wrong in constructing the logic of conditions.
Also, you haven't converted the input to a string. Input is always read as a string, in your code you haven't read it as an integer. Convert string input to int using int(), because int() transforms a string into an integer. You need to add int before input, but put it in parentheses.
Python takes input in string format, you need to cast the input into int but in your code, you're comparing a string with int in the conditionals.
amt=int(input("How many cupcakes would you like to but? "))
if amt>=6:
disc = amt*0.12
elif amt>=12:
disc=amt*0.24
print(disc)
In my form I ask for an Investment Amount and it should be at least $50,000. When I test if it works (see below), no matter what a person puts in it still says Investment Amount Must Be At Least $50,000:
investor = get_string("Investment: ")
investment = int()
if (investment < 50000):
print("Investment Amount Must Be At Least 50000!")
else:
print("OK")
~/project/ $ python test.py
Investment: 60000
Investment Amount Must Be At Least 50000!
I think it has something to do with the line:
investment = int()
Here's the fixed code:
investment = int(input("Investment: "))
if (investment < 50000):
print("Investment Amount Must Be At Least 50000!")
else:
print("OK")
Edit: The top line was also off, when I tried your original code, get_string was giving me a Name Error.
The int() function returns an integer object constructed from a number or string , or return 0 if no arguments are given. Since investment is zero, the condition is executed always. Try to get get the input and then compare.
investment = int(input("Enter Investment Amount"))
if (investment < 50000):
print("Investment Amount Must Be At Least 50000!")
else:
print("OK")
investment = int() is creating a new int object with default value of 0.
A friend of mine is studying Python and gets this error
name = int(input('Type str: '))
if name >= 0:
print('Typed name is wrong')
elif name <= 0:
print('Typed name is wrong')
else:
name1 = str(input('Type your name: '))
print('Your name is: ' + name1)
Of course, I don't understand Python, but when he enters a number, everything works fine, but when he feeds on entering a string value, he gets an error, how can this problem be solved?
So when you use the input() function you read input in string form. When you use int(input()) your string input is typecasted to integer form. If you input anything that can't be typecasted to an integer you'll get an error.
For example: If your input is "3" then it'll be typecasted to 3 and if you input "your name" it can't be typecasted, hence it'll throw an error.
That's why you didn't get any error when you were typing a number because the typecasting was successful.
It'll be helpful if you could elaborate what output you want.
I am getting a value error when I try to enter 10.8 as hours. Why can't I enter a float value and convert it into int here?
def computepay(hours,rate):
try:
hours=int(hours)
rate=float(rate)
if hours > 40:
payment = 40 * rate # Standard Payment until 40 Hours
payment = payment + rate *(hours-40) * 1.5 # + the rest which has more rate
print("Pay:",payment)
else:
payment=hours*rate
print("Pay:", payment) # Otherwise Normal Payment
except:
print("Value error")
hours=input("Enter hours:")
rate=input("Enter Rate:")
computepay(hours,rate)
It's simply because int() cannot convert strings that do not represent integers. As input returns as string, I suggest you pass it to float() first.
So : hours = int(float(hours)).
I couldn't make much sense of the code but it appears that you are passing string values to the method directly. input() returns a string. In your case putting in 10.8 would produce a
ValueError, invalid literal with base 10.
What you should be doing is casting your input into a float and then passing it to your function.
Do something like this.
hours = float(input("Enter hours:"))
rate = float(input("Enter Rate:"))
computepay(hours,rate)
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