Python:类型错误、非整数的数字和变量问题

2024-09-28 05:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着做一个程序,要求3个数字,然后返回这些数字的乘积(确定一个长方体的体积)

def cuboid ():
    A = input('Height '),
    B = input('Width '),
    C = input('Depth '),

到目前为止,这使得PYthon需要这三个值,但是我不知道如何告诉PYthon它们不是字符串,而是整数。i、 我不知道如何使用int()命令。 如果在那之后我输入:Volume = A*B*C,它会给出一个类型错误,因为他认为1,2和3不是整数。你知道吗

我不知道为什么这样不行,因为

def o3 (x,y,z):
    print x*y*z

确实有效。 提前谢谢


Tags: 字符串命令程序inputdef体积数字整数
3条回答

这就是你想要的吗?你知道吗

def cuboidv ():
    h=input('enter hieght')
    l=input('enter length')
    w=input('enter width')
    ans=l*w*h
    print ans
def input_int(text):
    while True:
        x = raw_input('%s: ' % text) 
        try:
            return int(x)
        except Exception, e:
            print 'Please enter a correct integer'


h = input_int('Height')
l = input_int('Length')
w = input_int('Width')

print 'Result is', h * l * w

您使用的是input(),而您应该使用raw_input()。在输入之后,您只需要说a = int(a),a将是一个整数,您可以对它进行普通的算术运算。你知道吗

示例:

def get_cube_dims():
    x = int( raw_input('Enter x:') )
    y = int( raw_input('Enter y:') )
    z = int( raw_input('Enter z:') )
    print 'The volume is: {}'.format(x*y*z)

相关问题 更多 >

    热门问题