1

在python中,如果我为x(x = 1)分配一个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 ( )
4

2 回答 2

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'一个非空字符串,它总是会计算为真,所以条件总是真。你想写的是这样的:

if choice == 'A' or choice == 'a':
于 2012-12-30T20:08:53.000 回答
0

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

如果您对特定代码有问题,发布它怎么样?

于 2012-12-30T19:51:37.743 回答