Reputation: 1
How would one produce some code that counts up using a for loop as opposed to a while loop? My code is as follows;
def square():
count = 1
number = input("How far?")
number = int(number)
if number < 1:
print ("broken")
elif number >= 1:
while count <= number:
square = count*count
print ("{0}*{0}={1}".format(count, square))
count = count+1
square()
Upvotes: 0
Views: 81
Reputation: 405
U can do it with list comprehensions like:
def square():
number = int(input("How far?"))
# range will be from 1 to number +1, and will proceed square for all
return [val ** 2 for val in range (1, number+1)]
squares = square()
if not squares:
print('broken')
# u can iterate over result even if list is empty(if u pass broken number)
for val in squares:
print ("{0}*{0}={1}".format(count, square))
Upvotes: 0
Reputation: 19634
You can do it like that:
def square():
number = input("How far?")
number = int(number)
if number < 1:
print ("broken")
elif number >= 1:
for count in range(1,number+1):
square = count*count
print ("{0}*{0}={1}".format(count, square))
square()
Using the line
for count in range(1,number+1):
counts
iterates over the values 1,2,...,number
.
Upvotes: 1