+ 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

24th May 2017, 5:28 PM
drmaik
drmaik - avatar
8 Réponses
+ 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! ^^
24th May 2017, 5:56 PM
Maz
Maz - avatar
+ 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")
25th May 2017, 2:51 AM
visph
visph - avatar
+ 9
@Maz: indentation isn't a problem, as one space indent is enough, even readability will be improved by recommended 4 spaces ( not mandatory ;) )
25th May 2017, 2:53 AM
visph
visph - avatar
+ 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).
27th May 2017, 5:42 PM
visph
visph - avatar
+ 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
25th May 2017, 12:44 AM
Amaras A
Amaras A - avatar
+ 2
What do you suggest amaras?
25th May 2017, 1:04 AM
drmaik
drmaik - avatar
+ 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")
27th May 2017, 10:55 AM
Janakiraman Munusamy
Janakiraman Munusamy - avatar
+ 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) ?
27th May 2017, 1:17 PM
drmaik
drmaik - avatar