YEETter 23414323424
YEETter 23414323424

Reputation: 57

problems with making the square of a number via for loop

I'm learning python, now I'm learning for and while, the exercise that I'm doing asks me to make the square of a number using a for loop. So I'm trying to make it but I don't know how to solve a problem, that I know why it is there, but I don't know how to solve it.

Anyway here's the code

def main():
    #start
    givn_n = eval(input("Tell me the number:\n"))
    for i in givn_n:
        #start
        double_givn_n = givn_n ** 2
        print(double_givn_n)
        #end
     return
     #end

main()

The error is:

Traceback (most recent call last):
  File "C:\Users\Simone\Desktop\progetto python\Tutorial-python\w ext libraries\somma_quadrati.py", line 12, in <module>
    main()
  File "C:\Users\Simone\Desktop\progetto python\Tutorial-python\w ext libraries\somma_quadrati.py", line 6, in main
    for i in givn_n:
TypeError: 'int' object is not iterable

Upvotes: 1

Views: 93

Answers (3)

Richard Jessop
Richard Jessop

Reputation: 972

I place the following in a .py script. Note the need for absolute value:

#!python

givn_n = abs(int(input("Tell me the number:\n")))
double_givn_n = 0

for i in range(0,abs(givn_n)):
    double_givn_n += givn_n

print(double_givn_n)

Upvotes: 0

ErdoganOnal
ErdoganOnal

Reputation: 880

Your question has already been answered but I want to mention about how to improve your code.

eval is a dangerous function. I recommend you to not use it. In your case, int can be called.

What about something else. Simple. Try ast.literal_eval. Secure way of doing the evaluation.

def main():
    # start
    givn_n = int(input("Tell me the number:\n"))
    for i in range(givn_n):
        # start
        double_givn_n = givn_n ** 2
        print(double_givn_n)
        #end
     return # Your code already ends, I think no need to return :)
     #end

main()

Upvotes: 2

Abhishek Prusty
Abhishek Prusty

Reputation: 864

Your code needs a small correction

for i in range(givn_n):

Upvotes: 1

Related Questions