First time here? Check out the FAQ!

Ask Your Question
1

other way of creating a list of perfect squares

asked 3 years ago

jhonvi2 gravatar image

Hi there! I am currently explaining a certain exercise to my buddy and part of it consists in creating a list of perfect squares up to root of 64 (included) therefore the list has to look like this [0, 1, 4, 9, 16, 25, 36, 49, 64] My first idea was this

squares=[i*i for i in range(sqrt(64)+1)]

which works but I am now trying to do it in a way so that is not compressed such us

 for i in range(sqrt(64)+1)
        squares=[i*i]
    print(squares)

But I keep getting this error

 for i in range(sqrt(Integer(64))+Integer(1))
                                                ^
SyntaxError: invalid syntax

Any ideas of what I am doing wrong?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 3 years ago

tmonteil gravatar image

updated 3 years ago

In a for loop, the line must end with a colon :

By the way, here are some hints for the exercise:

  • if L is a list, you can add an element to L with L.append(element)
  • the empty list is denoted by []
  • if you want to avoid the use of the square root, you can replace the for loop with a while loop
Preview: (hide)
link

Comments

Hi! thank you so much for your help my code is better now! I just do not really understand your last statement 'if you want to avoid the use of the square root, you can replace the for loop with a while loop' Isn't it the same the for loop and the wwhile loop?

jhonvi2 gravatar imagejhonvi2 ( 3 years ago )

In a for loop, you have to know in advance where to stop, in a while loop, you test on-the-fly.

tmonteil gravatar imagetmonteil ( 3 years ago )

@tmonteil ok so I could do something like

   n =95    
   cuadrados=[ ]
    i=0
    root= int(sqrt(n)+1)
     while i < root:  
       cuadrados.append(i*i)

but it does not seem to work I keep getting an error in cuadrados.append(i*i)

jhonvi2 gravatar imagejhonvi2 ( 3 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 3 years ago

Seen: 608 times

Last updated: Oct 07 '21