将所有值放入变量处理为字符串?

时间:2012-12-30 19:49:18

标签: string variables python-3.x int

在python中,如果我将1分配给x(x = 1),那么每次将1视为一个字符串吗?

我不明白为什么数字不被视为数字而必须转换成数字 数学运算的公认整数。继续改变似乎很麻烦 来回变量值。

谢谢

第2部分: 圆形程序区域的一些代码:

def chooseDim ( ):
    **choice = input ('Do you need to find radius or area? ')
    if choice == 'A' or 'a':
        area = 0                [This part of the prog is the culprit, specifically the
        area = int(area)         "choice" variable prior to the If conditional. The If 
        areaSol ( )**           keeps reading the condition as True no matter what value
                                "choice" is. It has to do w/the "or" condition. When I let
                                "choice" be one value, it's fine, but if I code
                                "if choice = 'A' or 'a'"  the prog evals the If as True                  
                                every time. Am I not coding the "or" statement right?]

    elif choice == 'R' or 'r':

        radSol ( )

    else:
        print ('Please enter either A/a or R/r.')
        chooseDim ( )

2 个答案:

答案 0 :(得分:0)

没有。所有值都不会转换为字符串。 Python虽然在变量可能在其生命周期中包含不同类型的值的意义上被“动态类型化”,但通常对操作非常严格(例如,您不能将数字连接到字符串上)。如果将数字分配给变量,则该值将为数字。

如果你对某段特定代码有疑问,可以发布它吗?

答案 1 :(得分:0)

不,你说的不正确。 Python是动态类型的,这意味着虽然的变量有类型,但它的值确实有类型。您可以使用type函数轻松检查以获取值的类型:

>>> x = 1
>>> type(x)
<class 'int'>
>>> x = '1' # storing a different value in x
>>> type(x)
<class 'str'>
>>> type(1) # type() works on the value, so this works too
<class 'int'>
>>> type('1')
<class 'str'>

然而,Python也是强类型的,这意味着不会进行动态类型转换。这就是在执行算术运算时必须将字符串明确地转换为数字的原因:

>>> 1 + '1' # int does not allow addition of a string
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> '1' + 1 # on the other hand, int cannot be converted to str implicitely
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    '1' + 1
TypeError: Can't convert 'int' object to str implicitly

修改

要回复您发布的代码,您的if是这样的:

if choice == 'A' or 'a':

如果choice == 'A'评估为choice,则检查'A'(如果'a'等于True),。由于'a'是非空字符串,因此它将始终求值为true,因此条件始终为true。你想写的是:

if choice == 'A' or choice == 'a':