Skip to content
Advertisement

Print sum of numbers in Python Script

I’ve been searching for a while and haven’t been able to figure this out.

I’m running Kali Linux and I’m trying to run a very simple script and I’m not getting the output I would expect. I used to programing python on windows and the switch to Kali and I can’t get this basic script to give me my desired output.

a = 1
b = 2
a + b

This should give me the output of 3, however I don’t get any output.

When I run:

a = 1
b = 2
a + b

print "test %s" %a

I get the output:

test 1

Any help is greatly appreciated

Advertisement

Answer

By saying that you are running the script, I assume that you are not running your code in an interactive shell, which would give you the output you expected. However, while running a script, you have to tell the computer exactly what to do. You missed out the print statement in the first script. So, the computer calculated the sum and happily exited.

Now in the second script, you mistakenely forgot to add before printing out. And, also ‘%s’ is a string formatter for the type string that means it expects a string. Here, we should be using ‘%d’ for a digit(number)

So try either:

a = 1
b = 2
c = a + b

print "test %d" %c

OR DIRECTLY

a = 1
b = 2
print "test %d" %(a+b)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement