简体   繁体   中英

Can anyone help me in this python code for finding Cube

x=3
y=x
ans=0

while( y != 0 ):
  ans = ans + x
  y = y - 1
ans = ans*x
print( str(ans) )

There is no output on screen. And no error is showing up. Just shown in image.

在此处输入图片说明

Your code only works for 3 cubed. You're also using multiplication. If you only want only addition as your comment implies, you'll probably want to break down your logic a bit. Here's how I'd do it (stop reading here and try to work it out yourself, first!):

def cube(x):
    """ Calculate x to the 3rd power (cube) """
    x_times_x = multiply(x, x)
    x2_times_x = multiply(x_times_x, x)
    return x2_times_x

def multiply(x, y):
    """ Multiplies two numbers only using addition """
    accum = 0
    for _ in range(y):
        accum += x
    return accum

print(cube(3))
print(cube(4))
print(cube(5))

Outputs:

27
64
125

as expected. Remember the easiest way to see output is to just save code to a file and run python from your command line.

Your syntax is all off.

You're using a capital X on the first line, then suddenly it's lowercase on the 2nd line.

while loops in python are generally written like this:

while y != 0 :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM