+ 1
Please can someone help and explain to me how while and for loops work's in python
10 ответов
+ 1
Abdulrahman Jaafar Aminu Hi! What parts in the Python course about loops did you not get?
+ 1
Thank you sir
+ 1
I understand sir
Thank you
0
For example if I am ask to do a program that will print perfect square numbers from 1 to 500 using for loops,so how I'm going to do this
0
Abdulrahman Jaafar Aminu Okey, I see. But even if you can’t find exactly that solution in the Python course, I mean that all the knowlages are there, if you look. But if you try, get stucked and link your code, I will help you.
0
from math import sqrt
for value in range(1,500+1):
c = sqrt(value)
if c == value:
print(value)
0
# Hi! You can look at this one:
from math import sqrt
n = 500
n_max = int(sqrt(n))
my_list = []
for value in range(1, n_max + 1):
my_square = value * value
my_list.append(my_square)
for i in my_list:
print(i)
0
Sir pls explain line 5
0
Hi, again! Maybe with line five you intend:
n_max = int(sqrt(n)) + 1
If you want all perfekt squares up to n, you need to use all numbers between 1 and the square root of this number. For positiv numbers, int(x) gives the floor of the number:
int(5.0) -> 5
int(5.1234) -> 5
int(5.9999) -> 5
Example:
all squares up to 6
sqrt(6) = 2.4495
int(2.4495) = 2
=> 1*1 = 1, 2*2 = 4 (but 3*3 > 6)
all squares up to 9:
sqrt(9) = 3.0
int(3.0) = 3
=> 1*1 = 1, 2*2 = 4, 3*3 = 9 ok!
The last + 1 was just for the intervall in range. It was a bit confusing. Maybe this is better:
…
n_max = int(sqrt(n))
…
for value in range(1, n_max + 1):
…
And of course, you don’t have to put the squares in a list before you print them out. Actually, you can code everything in just one line:
print(*(i**2 for i in range(1, int(int(input()) ** .5) + 1)), sep='\n')
0
[while]
* these loops will cycle forever until a [break] condition is met
example [while] code:
x = 0
while x < 10:
print(“Hamburger”)
# if you use this code in a Python IDE, it will NEVER stop printing hamburger, because we didnt give it a away to break the code.
[for]
* these loops will only cycle through the preset [list] or [range] that you give it. Then it will end.
example [for] code:
for x in “hamburger”:
print(x)
# this code will print all the letters in hamburger and then finish.
#notes
* So how is this useful for you?
* if you want to keep the checks between a defined range or within a certain value, use [for]
* if you want a more broad check, use [while], just dont forget to also include a [break] expression of some sort or the code will never end.