9 Respuestas
+ 4
There are two kinds of loop in Python. For loop and while loop.
For loop short example
for i in range(3):
print(i)
result
0
1
2
At the first line, "i" is the variable will be print, and the value is range(3).
What is range(3)? It produce three numbers start from 0, and each element is increased by 1. So it produce 0, 1, 2. Each element will assigned to variable "i".
Finally variable "i" get print on the screen.
While loop short example
i = 3
while i > 0:
print(i)
i = i - 1 # or the shorthand, i -= 1
result:
3
2
1
At the first line we set value 3 into variable "i".
Second line says while i is greater than zero, do the following code.
At this stage i=3, it will print on the screen. After printing we decrease i by 1, and the program jump back to while i > 0:
Now i=2, it prints 2 and i becomes 1.
Next loop i=1, it prints 1 and i becomes 0.
Now i > 0, replacing i the the value it becomes 0 > 0, it is a False, the program quit the while loop.
You can review the material many time as you wish.
+ 4
What is hardest thing in loops?
Python only supports for and while loop so what is hard here.
+ 4
Asgar Ali it sounds like your BASIC training was incomplete. Even the earliest dialects of BASIC have FOR/NEXT loops.
Some dialects have DO WHILE/LOOP and DO/LOOP WHILE.
Some have additional options of DO UNTIL/LOOP and DO/LOOP UNTIL.
+ 3
Yes you are right I enrolled in Diploma in computer science and management when I was 19 years old.After 1 Month into the course I left it since everything taught there used to go over my head.the only thing I could understand was GoTo statement used for control flow which the instructor used to explain with the help of flowchart.
+ 1
How loop works
please explain with code
+ 1
Thank you so much for this beautiful explanation
+ 1
Shivam ,
Python has a loop format that is actually easier than other languages but that people coming from other languages don't immediately understand.
For example, if you wanted to print every letter of a word, one by one, other languages would make you get the length of the word, set up a counter, give it an initial value, increment (or decrement) the counter, use the counter as an index into the word to grab each character, and test when the counter reaches the word length (or zero).
Python only makes you name the counter. It automatically takes care of the rest. I named my counter "letter" below.
word = "cat"
for letter in word:
print(letter)
Output:
c
a
t
+ 1
Thanks u a lot
+ 1
Yes very hard to understand loops.I never used loops when I started Coding in BASIC.Just Goto was used then instead of Loops.