简体   繁体   中英

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

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)

in your code you have two variable a and b assigned with some value and then u are adding a and b, but it has to be stored somewhere; a+b doesn't mean the sum of a and b goes into a !

a=10;
b=20;
c=a+b;

print c

or

a=10;
b=20;
c=a+b;
print "test %d" %c

or

    a=10;
    b=20;
    c=a+b;
    print "test %d" %(a+b)

Or u can just edit your code to

a = 1
b = 2
a += b
print "test %s" %a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM