+ 2
Where is the error
A = input("1st") B = input("plz use + or - sign for add or sub") C = int input("2nd") if B == "+": print (A + C) if B == "-": print (A - C) print ("code ended") I want to make simple calculator but there comes problem dont know where
8 Respuestas
+ 10
A = eval(input("1st"))
B = input("plz use + or - sign for add or sub")
C = eval(input("2nd"))
if B == "+":
print (A + C)
if B == "-":
print (A - C)
print ("code ended")
# I'm not very good in Python, but... "int input" and your indentations should be the problem, this works well. ^_^
# @visph @Amaras... Thank you for your completess, i already knew the use of eval ( ) in Javascript, i did not think was the same for Python! ^^
+ 10
Use casting function float or int instead:
A = float(input("1st"))
... because input() return value type is string.
But however, you need to handle exception, as an error will be raised if Python cannot convert the string to a float ( or int ). So, use a custom function to cast numbers:
def number(n):
try:
if '.' in n:
return float(n)
else:
return int(n)
except:
return None
A = number(input("1st")
+ 9
@Maz: indentation isn't a problem, as one space indent is enough, even readability will be improved by recommended 4 spaces ( not mandatory ;) )
+ 7
Returned value from input() is always of type string...
In the other hand, the argument (parameter) of input is expected to be a string to display (question/indication for expected user entry). If you put something inside quotes, you pass a string literal, and if not, you pass a variable (needs to be declared and assigned with a string type value).
+ 4
I have one point to emphasise: NEVER EVER EVER trust user input.
@Maz: your code is fundamentally broken: never use eval on your input before sanitising it. It's just too dangerous... like what if I type something that deletes the whole disk? That's why you rarely use the eval function and the exec statement
+ 2
What do you suggest amaras?
+ 2
A = input("1st") ======> Entered value will be taken as Int
B = input("plz use + or - sign for add or sub") ==> Here User is forced to enter the + or - inside a quotes - something that user should be made aware of --> this can be made user friendly.
C = int input("2nd") ======> Entered value will be taken as int and the code should be like C = int(input("2nd")) ==> u were missing braces
if B == "+":
print (A + C)
if B == "-":
print (A - C)
print ("code ended")
+ 1
@janakiraman if we want the entered value to be taken as string. What command will we use?
A = input('1st')
Or
A = input(1st)
?