简体   繁体   English

在Python脚本中打印数字总和

[英]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. 我正在运行Kali Linux,我正在尝试运行一个非常简单的脚本,但我没有得到我期望的输出。 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. 我曾经在Windows上编程python并切换到Kali,我无法得到这个基本脚本来给我我想要的输出。

a = 1
b = 2
a + b

This should give me the output of 3, however I don't get any output. 这应该给我3的输出,但是我没有得到任何输出。

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. 通过说您正在运行脚本,我假设您没有在交互式shell中运行代码,这将为您提供预期的输出。 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. 你错过了第一个脚本中的print语句。 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. 并且,'%s'也是类型字符串的字符串格式化程序,这意味着它需要一个字符串。 Here, we should be using '%d' for a digit(number) 在这里,我们应该使用'%d'来表示数字(数字)

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分配了一些值然后你正在添加a和b,但它必须存储在某个地方; a+b doesn't mean the sum of a and b goes into a ! a+b并不意味着ab的总和进入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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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