我应该在if语句中使用add()和sub()作为参数?

时间:2017-02-15 11:40:35

标签: python parameter-passing

我想使用用户输入进行计算,我已经定义了add(* args)和sub(* args)但是如果我在if语句中的add()中编写* args则显示错误:args未定义 如果写m,那么它显示m的值不是总数....

// Set the path to the file
$file = '/Absolute/Path/To/File';

// Instantiate our JImage object
$image = new JImage($file);

// Get the file's properties
$properties = JImage::getImageFileProperties($file);

// Declare the size of our new image
$width = 100;
$height = 100;

// Resize the file as a new object
$resizedImage = $image->resize($width, $height, true);

// Determine the MIME of the original file to get the proper type for output
$mime = $properties->mime;

if ($mime == 'image/jpeg')
{
    $type = IMAGETYPE_JPEG;
}
elseif ($mime = 'image/png')
{
    $type = IMAGETYPE_PNG;
}
elseif ($mime = 'image/gif')
{
    $type = IMAGETYPE_GIF;
}

// Store the resized image to a new file
$resizedImage->toFile('/Absolute/Path/To/New/File', $type);

1 个答案:

答案 0 :(得分:1)

在调用addsub函数时,您没有传递任何内容,也不保存所有用户输入。您需要将用户输入保存到列表中,然后将列表传递给函数。请注意,您还需要从函数签名中删除*,因为您要传入列表,而不是任意数量的参数。

def add(args):
    total = 0
    for a in args:
        total += a
    print(total)

def sub(args):
    total = 0
    for a in args:
        total -= a
    print(total)

.
.

if n == 1:
    li = []
    for i in range(counter):
        li.append(int(input("enter no.")))
    add(li)
elif n == 2:
    li = []
    for i in range(counter):
        m = li.append(int(input("enter no.")))
    sub(li)

请记住,您可以使用生成器缩短代码(不一定更具可读性):

if n == 1:
    add(int(input()) for i in range(counter))
elif n == 2:
    sub(int(input()) for i in range(counter))