如何在Python中添加变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16313986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:15:58  来源:igfitidea点击:

How to add variables in Python?

pythonvariablesif-statementsum

提问by particlepat

Python noob here. I'm trying to add a set of input variables defined in an 'if' statement and whenever I try to find the sum it will just display the values inline. For example, when a, b, c, and d equal 5, perimeter = 555...

这里是 Python 菜鸟。我正在尝试添加一组在“if”语句中定义的输入变量,每当我尝试查找总和时,它只会显示内联值。例如,当 a、b、c 和 d 等于 5 时,周长 = 555...

shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?")
if shape.lower() == "q":
    a = raw_input("What is the length in feet of side 'a'?")
    b = raw_input("What is the length in feet of side 'b'?")
    c = raw_input("What is the length in feet of side 'c'?")
    d = raw_input("What is the length in feet of side 'd'?")
elif shape.lower() == "t":
    a = raw_input("What is the length in feet of side 'a'?")
    b = raw_input("What is the length in feet of side 'b'?")
    c = raw_input("What is the length in feet of side 'c'?")
else:
    print "Please enter 'q' for quadrilateral or 't' for triangle."

if shape.lower() == "q":
    perimeter = a + b + c + d
elif shape.lower() == "t":
    perimeter = a + b + c
else:
    print "Please make sure you enter numbers only."

print perimeter

回答by akaIDIOT

strvalues can be added to each other much like numbers. The +operator you use works fine, but concatenates values for strings. The result of raw_inputis a string (str), so that's why you'd see '555'in stead of 15. To sum numbers, use int()to coerce the values to numbers before adding them up:

str值可以像数字一样彼此相加。+您使用的运算符工作正常,但连接字符串的值。的结果raw_input是一个字符串 ( str),所以这就是为什么你会看到'555'而不是 15。要对数字求和,使用int()将值强制转换为数字,然后再将它们相加:

try:
    a = int(raw_input('gimme a number'))
except ValueError as e
    print 'that was not a number, son'

回答by akaIDIOT

for variables a, b, c, and d, use input(prompt)instead of raw_input(prompt). raw_inputreturns a string, but inputreturns the console input evaluated as a python literal. (As of right now, you're concatenating strings, not adding integers).

对于变量abcd,使用input(prompt)代替raw_input(prompt)raw_input返回一个字符串,但input返回计算为 python 文字的控制台输入。(截至目前,您正在连接字符串,而不是添加整数)。

回答by kiriloff

Make sure that your raw_inputactually Is an int():

确保您raw_input实际上是一个 int():

shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?")
if shape.lower() == "q":
    try:
        a = raw_input("What is the length in feet of side 'a'?")
        b = raw_input("What is the length in feet of side 'b'?")
        c = raw_input("What is the length in feet of side 'c'?")
        d = raw_input("What is the length in feet of side 'd'?")
        perimeter = int(a) + int(b) + int(c) + int(d)
    except ErrorValue as e  
        print "Please make sure you enter numbers only."

elif shape.lower() == "t":
    try:
        a = raw_input("What is the length in feet of side 'a'?")
        b = raw_input("What is the length in feet of side 'b'?")
        c = raw_input("What is the length in feet of side '
        perimeter = int(a) + int(b) + int(c)
    except ErrorValue as e  
        print "Please make sure you enter numbers only."
else:
    print "Please enter 'q' for quadrilateral or 't' for triangle."

回答by Bhavish Agarwal

Your code is not a good design. What if you want to add more shapes, hexagon, octagon and so on. You can actually use a dict to store shape mapping to number of sides. You don't have to write multiple if statements for each shape. You will have to do less type checking and you could use python builtin function sum to return the parameter. Go on now and try the following:

你的代码不是一个好的设计。如果你想添加更多的形状,六边形,八边形等等怎么办。您实际上可以使用 dict 将形状映射存储到边数。您不必为每个形状编写多个 if 语句。你将不得不做更少的类型检查,你可以使用 python 内置函数 sum 来返回参数。现在继续并尝试以下操作:

d = {'q': 4, 't': 3}

shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?\n")

if shape.lower() not in d:
    print "Please enter 'q' for quadrilateral or 't' for triangle."

else:
    sides = []

    for i in range(0,d.get(shape.lower())):
        side = raw_input("What is the length in feet of side " + str(i+1))
        try:
            sides.append(int(side))
        except ValueError:
            print "Integer value only"

    print sum(sides)

回答by Mr_Spock

I did this using a dictionary.

我是用字典做的。

sides = {'a':0,'b': 0,'c': 0,'d': 0}
perimeter = 0

shape = raw_input("Is the plot a (q) quadrilatral or (t) triangle?: ")
if shape.lower() == "q":
    for side, length in sides.iteritems():
        sides[side] = input("What is the length (in feet) of side %s?: " % side)
        perimeter+=int(sides[side])

elif shape.lower() == "t":
    sides.pop("d",None)
    for side, length in sides.iteritems():
        sides[side] = input("What is the length (in feet) of side %s?: " % side)
        perimeter+=int(sides[side])
else:
    print "Please enter 'q' or 't'."

print "Perimeter is: %d" % perimeter 

I figured a dictionary would be easier to use. Might be much cleaner, rather than repeat yourself.

我认为字典会更容易使用。可能会更干净,而不是重复自己。