while loop - Square number sequence in Python - Stack Overflow
List of squares in python - Stack Overflow
for loop - Writing a Python program that finds the square of a number without using multiplication or exponents? - Stack Overflow
trying to make a code that prints all square numbers up to 5000 but it just goes past 5000 and doesnt stop, how to make it stop before 5000?
What is the simplest method to square a number in Python?
The simplest way to square a number is using the exponent operator: 5 ** 2. It's built-in, requires no imports, and clearly expresses the intent of raising to a power.
When is NumPy used to square a number?
You should use NumPy to perform square operations in large datasets.
How do I handle errors when squaring numbers in Python?
You can avoid errors by validating your code to handle exceptions where necessary.
There are some problems. First, your input (what raw_input() returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
Second, you are setting a = 1 each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line
a = 1
Finally, it's not necesary to check if a > n, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
There is a small error in your code:
while a < n:
a=1 # `a` is always 1 :)
print a*a
a += 1
if a > n:
break
Just some tips:
Try not to use eval(), it will evaluate any input given and so it can do something you don't want to do. Instead, use int().
Remember that, say 4*4, is just 4 + 4 + 4 + 4. You're on the right track with a for-loop, but now make the loop iterate n times adding n to itself.
new = 0
for _ in range(n):
new += n
Note that this won't work with negative numbers. If you're going to be dealing with those, perhaps get the absolute value of n at the beginning:
def square(n):
n = abs(n)
....
Since you have been told you have to get the answer by producing the first n odd numbers, then you need to think about how to do that - certainly your loop isn't doing that :
several issues :
- you do odd =1, and then use odd in your for loop, the two can't co-exist, so the initial value of odd = 1 is overwritten.
- Your loop doesn't produce the first n odd numbers that I can see.
My suggest would be to rework your loop : the first 'n' odd numbers are in the form :
1, 3, 5, ... n*2-1 (Counting from 1 not from zero)
so a loop like this :
final = 0
for c in range(1, n+1): #start counting from 1 to do 1 to n+1
odd = c*2 -1 #Use the series above to generate each odd number.
final += odd
should work
a much more 'pythonic' way to do this is :
final = sum(c*2-1 for c in range(1,n))
This uses a generator to create all of the odd numbers (the equivalent of the loop), and sum the values as they get created.