Python Forum
Same codes show different output ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Same codes show different output ?
#1
Trying to write a program to perform various functions on numbers.
num1, operator, num2 = input ('enter calculation').split()
num1 = int(num1)
num2 = int(num2)

if operator == "+":
  print("{} + {} = {}" .format(num1, num2, num1+num2))

elif operator == "-":
  print("{} - {} = {}".format(num1, num2, num1 - num2))

elif operator == "*":
  print("{} * {} = {}".format(num1, num2, num1 * num2))

elif operator == "/" :
  print("{} / {} = {}".format(num1, num2, num1 / num2))

else:
  print("Use either + - * or /")
this code works




However when I do the same thing like this it prints what is after ELSE. please help !



num1= input ('enter calculation')
num2 = input('second number')
operator= input('enter operation')
num1 = int(num1)
num2 = int(num2)

if operator == "+":
  print("{} + {} = {}" .format(num1, num2, num1+num2))

elif operator == "-":
  print("{} - {} = {}".format(num1, num2, num1 - num2))

elif operator == "*":
  print("{} * {} = {}".format(num1, num2, num1 * num2))

elif operator == "/" :
  print("{} / {} = {}".format(num1, num2, num1 / num2))

else:
  print("Use either + - * or /")
Reply
#2
Mainly just to clarity, if you change the first prompt from
num1 = input('enter calculation')
to this
num1 = input('first number ')
Anyway, runs just fine for me. Also, you could save some typing by changing num1 & num2 to :
num1 = int(input('first number '))
and removing lines 4 and 5.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#3
I can can see a dead elephant in the room, where is nobody talking about.
Code duplication. You're repeating over and over the print function and if statements.

from operator import add, sub, mul, truediv, floordiv
num1, operator, num2 = input ('Enter calculation: ').split()
num1 = int(num1)
num2 = int(num2)
op_dict = {'+': add, '-': sub, '/': floordiv, '*': mul}
op = op_dict.get(operator) # returns by default None if the key does not exist
# we can use this 
if not op:
    print('Sorry, the operation is not supported :-(')
else:
    result = op(num1, num2)
    print("{} {} {} = {}".format(num1, operator, num2, result))
What do you think?
Try to find out what happens when you calculate 1 / 2.
How much lines do you have to add for a new operator in your code?
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
2nd one works for me too. Either you got a haunted IDLE process, or a typo in your input. Oddly, the same thing happened to me when I tried doing my first calculator a few weeks ago. If you do a dive, you can find my first thread about it.

Like DeaD_EyE and sparks_alot said, you can combine a few lines to save some typing:
num1, num2, operator = input ('first number'), input('second number'), input('enter operation')
num1, num2 = int(num1), int(num2)
Reply
#5
One addition...

You can use decimal.Decimal to get precise decimal calculation.
It's useful for calculators and you want to have this for financial stuff.

https://docs.python.org/3.6/library/decimal.html

Try following:
0.1 + 0.1 + 0.1 + 0.1 - 0.3
Output:
0.10000000000000003
It's not Pythons fault, every language has the problem, which comes from IEEE 754. Blame them.
Short explanation: The representation of floating point is the binary number system, which can't represent all decimal numbers/fractions.
You would run later into this problem. If you make for example after a floating point calculation an equality check, you'll have problems.

(0.1 + 0.1 + 0.1 + 0.1 - 0.3) == 0.1
Output:
False
Same with decimal.Decimal:
import decimal


D = decimal.Decimal # as a shourtcut
D('0.1') + D('0.1') + D('0.1') + D('0.1') - D('0.3')
Output:
Decimal('0.1')
You can take this and instead of using int to convert the input to an integer, you can use Decimal.
You'll also have control about precision and rounding. This does not mean, that you should use Decimal for every calculation.
It's much slower as a floating point calculation.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
(Jul-10-2017, 08:17 AM)tozqo Wrote: 2nd one works for me too. Either you got a haunted IDLE process, or a typo in your input. Oddly, the same thing happened to me when I tried doing my first calculator a few weeks ago. If you do a dive, you can find my first thread about it.

Like DeaD_EyE and sparks_alot said, you can combine a few lines to save some typing:
num1, num2, operator = input ('first number'), input('second number'), input('enter operation')
num1, num2 = int(num1), int(num2)

but the second one does not work in Aptana or PyCharm. It says syntax error in aptana and prints what is after ELSE in pycharm. Thanks for replying was really worried.

(Jul-09-2017, 02:29 PM)DeaD_EyE Wrote: I can can see a dead elephant in the room, where is nobody talking about.
Code duplication. You're repeating over and over the print function and if statements.

from operator import add, sub, mul, truediv, floordiv
num1, operator, num2 = input ('Enter calculation: ').split()
num1 = int(num1)
num2 = int(num2)
op_dict = {'+': add, '-': sub, '/': floordiv, '*': mul}
op = op_dict.get(operator) # returns by default None if the key does not exist
# we can use this 
if not op:
    print('Sorry, the operation is not supported :-(')
else:
    result = op(num1, num2)
    print("{} {} {} = {}".format(num1, operator, num2, result))
What do you think?
Try to find out what happens when you calculate 1 / 2.
How much lines do you have to add for a new operator in your code?



Thanks for your help. But Im not at such an advanced level so i still got multilinetisis. Its my 2nd python program.
Reply
#7
The snake bite you. You're using Python 2.x.
In Python 2 input evaluates the input.
+ is an operator. What happens if you just enter the + in the repl?

In Python 2, you should use raw_input and not input.
input is unsafe and allows code evaluation, which is not under your control.
A user can just type os.remove('/somefile') and it will be executed. You should avoid using
legacy Python and start using Python 3. Python 3 is cleaner and also raw_input is now input.
If you don't use Python 3.x, you'll miss all good features. Avoid using legacy Python, if you don't have dependencies.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#8
Using 2.x could explain the syntax errors. I'm egocentric and just assume everyone is using the same version of Python that I have. All my tests were run using Python 3.x in IDLE, and sparkz_alot's signature indicates PyCharm won't give you syntax errors using Python 3.x with our code recommendations.
Reply
#9
(Jul-10-2017, 02:09 PM)DeaD_EyE Wrote: The snake bite you. You're using Python 2.x.
In Python 2 input evaluates the input.
+ is an operator. What happens if you just enter the + in the repl?

In Python 2, you should use raw_input and not input.
input is unsafe and allows code evaluation, which is not under your control.
A user can just type os.remove('/somefile') and it will be executed. You should avoid using
legacy Python and start using Python 3. Python 3 is cleaner and also raw_input is now input.
If you don't use Python 3.x, you'll miss all good features. Avoid using legacy Python, if you don't have dependencies.

im using 3. and getting an output in Python fiddle but not in PyCharm
Reply
#10
Did someone deleted his post? Maybe I answered to the wrong topic :-/
I can remind that there was the problem with a Syntax Error when you input +.


In PyCharm you can select the interpreter version.
Python fiddle should be automatically Python 3.x.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PIL Image im.show() no show! Pedroski55 2 959 Sep-12-2022, 10:19 PM
Last Post: Pedroski55
  PIL Image im.show() no show! Pedroski55 6 4,888 Feb-08-2022, 06:32 AM
Last Post: Pedroski55
  Jupiter Notebook does not show output line Renym 3 2,647 Apr-26-2020, 11:21 AM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020