0

How do u write a python function with parameter n , which prints square numbers between 0 and n inclusive

28th May 2017, 4:15 PM
Tumisang
4 Answers
+ 1
Thanks now I can see where I missed it
1st Jun 2017, 11:38 PM
Tumisang
0
break it down. Start with importing Math. import math Now, define your function with the argument n import math def squares(n): since you want to check numbers between 0 and n, I would use a for loop. import math def squares(n): for i in range(0, n+1): notice I went n+1.. range starts at 0, thus is ends 1 step before. so range(10) would run 0-9 .. adding 1 to n makes the range complete thru the actual n you desire. Now add a check in each run of the loop that checks if the current number is a square number. To check, I used the math function that returns the square root of the number. I then check if it is an integer. import math def square(n): for i in range(0,n+1): if (math.sqrt(i)).is_integer(): if it is a perfect square, We print the number import math def square(n): for i in range(0,n+1): if (math.sqrt(i)).is_integer(): print(i) Now you call it with the argument of any number greater than 0. squares(1000)
28th May 2017, 4:47 PM
LordHill
LordHill - avatar
0
When you take your problem and break it down to simple steps, it is only 5 lines of code. Take things 1 step at a time. With some practice you can get it to be more efficient (square numbers can't end in 2,3,7 or 8 for example meaning you can skip checks on those numbers) Eventually you will learn about List Comprehension and be able to take those 5 lines of code down to 3 lines import math def square(n): print([i for i in range(0,n+1) if math.sqrt(i).is_integer()])
28th May 2017, 5:02 PM
LordHill
LordHill - avatar
0
Thanks now I can see where I missed it
1st Jun 2017, 11:38 PM
Tumisang