This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
I am working on a program and have come up with an error I don't usually face. My error is quite simple, yet I cannot wrap my head around a way to get past this problem. Thanks for helping.
Code:
budget = 50
depositAmount = input("Please enter an amount you would like to add")
if depositAmount > budget:
print("Sorry, you do not have the required funds to join. You have been exited.")
else:
#DO THE REST OF THE PROGRAM#
So in short terms, I will be adding values to the budget variable in the future, thats why I can't use the if statement and say less than 50, because the budget variable may be different. How do I make sure that if the user inputs a number greater than the variable value (or lower) they will be given an error message?
Convert depositAmount to number with int built-in before comparing with budget, to do it replace your if condition from
if depositAmount > budget:
to
if int(depositAmount) > budget:
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
What's the canonical way to check for type in Python?
(15 answers)
How can I read inputs as numbers?
(10 answers)
Closed last year.
I am a beginner when it comes to coding. I am trying to run a program on python that takes in kilometers(user input) and returns it in miles(output). I know how to do the task but I wanted to challenge myself by using if statements to check if the user has entered a number:
Kilometers = input("Please insert number of Kilometers: ")
if type(Kilometers) == int or float:
print("This is equivalent to", float(Kilometers)/1.609344, "Mile(s)")
else:
print("This is not a number")
I understand that whatever the user inputs will be saved as a string. However, whenever I run the code, the program always tries to convert the input into miles.
I have specified in the if statement that the type has to equal a float or an int, so shouldn't the output always be "This is not a number" until I change the first line to:
Kilometers = float(input("Please insert number of Kilometers: "))
or
Kilometers = int(input("Please insert number of Kilometers: "))
When programming if statements in Python, each condition must be fully rewritten. For example, you would write if type(Kilometers) == int or type(Kilometers) == float rather than if type(Kilometers) == int or float. Another important thing in your code is that if someone inputs 5.5, you would expect a float value, but Python interprets that to be a string. In order to circumvent this, you can use a try/except clause like this:
Kilometers = input("Please insert number of Kilometers: ")
try:
Kilometers = float(Kilometers)
print("This is equivalent to", Kilometers/1.609344, "Mile(s)")
except ValueError:
print("This is not a number")
What this is doing is trying to set Kilometers as a float type, and if the user inputs a string that cannot be interpreted as a float, it will cause a ValueError, and then the code inside except will run. You can find more on try/except clauses here: Python Try Except - W3Schools
One more thing I noticed is that you should name your variables according to the standard naming conventions, so Kilometers should be kilometers. You can find more on the naming conventions here: PEP 8
This question already has answers here:
Convert Python strings into floats explicitly using the comma or the point as separators
(3 answers)
Convert decimal mark when reading numbers as input
(8 answers)
Closed 2 years ago.
Super beginner here.
I'm following along the Automate the Boring Stuff With Python book and I decided to make a little script to help me out with some basic percentage checking. I didn't want to open Excel everytime I wanted to do this.
So the script gets two inputs, an old price and a new price and then calculates the percentage change in price. I think I got that right.
The problem occurs once I try to enter a float (that's the right term, yeah?) and I use the comma here in Europe.
I found a topic here where a similar question was answered, but there seems to be an issue on whether or not to call setlocale and (as far as I understand it) it does not deal with how to convert an input?
My code is below:
def izracun_odstotkov(): #function to calculate the difference in % between original price and new price
while True:
try:
prvotna_cena = float(input('Prosim vnesi prvotno ceno:')) #original price
except ValueError:
print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
continue
if prvotna_cena == 0:
print('Prvotna cena ne more biti 0.')
else:
break
while True:
try:
nova_cena = float(input('Prosim vnesi novo ceno:')) #new price
except ValueError:
print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
continue
else:
break
print(round((float (nova_cena)- float (prvotna_cena))/ float (prvotna_cena)*100, 2), '%')
while True:
izracun_odstotkov() #This makes the script run over and over so the user can just keep checking the % changes.
You can use the replace method:
prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I don't think I am using the write syntax to write my code, I am new and would like some help. This code is due tonight so anything would be helpful.
I have tried looking on youtube and other websites, but I couldn't find anything.
print("Hello, I can divide by two! Try me out.")
myNumber = input("What is your number?")
print("myNumber/2")
myAnswer = int(input(myNumber/2))
print("myAnswer")
I expect that the fourth line of code has incorrect syntax for the intended function.
input is always a string. It has to be converted to int for any int operations. Change this.
myNumber = input("What is your number?")
to
myNumber = int(input("What is your number?"))
You are taking input and storing it in myNumber which is string type. you can type-cast the myNumber to integer or float data type before dividing it by two.
print("Hello, I can divide by two! Try me out.")
myNumber = input("What is your number?")
print("myNumber/2")
myAnswer = int(myNumber)/2
print("myAnswer is ",myAnswer)
I believe this will do your work.
This question already has answers here:
Python (2.x) multiplication is not happening properly
(3 answers)
Closed 5 years ago.
I am working on a project that involves random numbers and them being greater or less than another number.
from random import randint
number = (randint(0, 100))
guess = raw_input("Guess: ")
print number
if (guess > number):
print str(guess) + " is greater than "+ str(number)
This code was created to help me debug my problem, but nothing worked. No matter what I put in as the variable "guess," it would always say that it was larger than the random number.
For example:
Guess: 0
27
0 is greater than 27.
Is this a problem with my code or with the random numbers? Thanks in advance!
raw_input returns a String type. You need to convert it into an int
guess = int(raw_input("Guess: "))
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
This has been flagged as a duplicate, i was unaware of the issue at the time but I shall take this post down in the next 48 hours, apologies.
I'm currently working on a python (v3.5.0:374f501f4567) program that generates a ranom equation using multiplication, addition or subtraction using. The code works perfectly up until the final hurdle. When trying to return if the answer is correct or incorrect I am thoroughly stumped. When I use the following code:
import random
from operator import add,sub,mul
x=random.randint(0,10)
y=random.randint(0,10)
eqn=(add, sub, mul)
eqnchoice=random.choice(eqn)
eqnstring={add:'+',sub:'-',mul:'*'}
useranswer=0
def eqngenerator():
random.seed
answer=eqnchoice(x,y)
answer=round(answer,2)
print("what's the answer to",x,eqnstring[eqnchoice],y,"=?\n")
useranswer=input("Enter the answer here:")
if useranswer==answer:
print('Correct!')
else:
print('Incorrect!')
print(eqngenerator())
I am faced with the following problem as seen in the screenshots below.
I'm befuddled as to why this is, if anyone can help please do.
Thank you for your time.
input() will be giving you a string in your useranswer variable. It will need to converted to a number before use, eg a float or an int
useranswer = int(input("Enter the answer here:"))
or
useranswer = float(input("Enter the answer here:"))
Use int if you know the answer to your calculation will always be an integer
input returns a string, so you need:
useranswer=float(input("Enter the answer here:"))
it will raise an error if user enter any other value then a number, so you can make:
def eqngenerator():
random.seed
answer=eqnchoice(x,y)
answer=round(answer,2)
print("what's the answer to",x,eqnstring[eqnchoice],y,"=?\n")
useranswer=input("Enter the answer here:")
try:
if useranswer==answer:
print('Correct!')
else:
print('Incorrect!')
except ValueError:
print('Incorrect!')