+ 1

Don't understand while and for loops in python. Stuck

13th Jan 2020, 10:14 PM
Rootcreator
Rootcreator - avatar
5 odpowiedzi
+ 4
I did this recently for some-one with a similar query. See if it helps. Extracted from Python tutorial, first lesson in 'for loops' https://code.sololearn.com/cCrFrnVXYIxa/?ref=app
13th Jan 2020, 10:51 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
For loops are basically loops that run a specific amount of times. Here's an example: for num in range(0, 5): #this runs 6 times, because 0 is considered a time as well; num can be replaced with anything, it's just a placeholder for the number of times the for loop is running print("Iteration " + str(num)) #as we said before, num contains the number the for loop currently is on, meaning this prints that When we run this: 1st iteration: "Iteration 0" 2nd iteration: "Iteration 1" 3rd iteration: "Iteration 2" 4th iteration: "Iteration 3" 5th iteration: "Iteration 4" 6th iteration: "Iteration 5" For loops can also be provided with a step, which creates a arithmetic sequence(2, 4, 6, 8...) Another use of for loops is to loop through a list, like this: fruits = ["Apple", "Banana", "Orange"] for fruit in fruits: #this will run each time for the number of items inside fruits, which is 3; fruit is a placeholder for the value of the item in the list print("Fruit " + fruit) Try this and see what happens.
13th Jan 2020, 10:53 PM
Jianmin Chen
Jianmin Chen - avatar
+ 2
Continuing from my previous answer, we can now see the output: Iteration 1: "Fruit Apple" Iteration 2: "Fruit Banana" Iteration 3: "Fruit Orange" It basically iterates over every item in the list and prints it. Now onto while loops. These loops basically run while a condition is true. For example, take the following while loop: num = 0 while num < 7: #this runs again and again until num is greater than 10 print("Iteration " + str(num)) num += 1 When we run this, the result should be: Iteration 1: "Iteration 0" Iteration 2: "Iteration 1" Iteration 3: "Iteration 2" Iteration 4: "Iteration 3" Iteration 5: "Iteration 4" Iteration 6: "Iteration 5" This basically does the same thing as the first for loop. But it's a different way of doing it. Also, like Rik Wittkopp and HonFu have mentioned, check out the Python tutorial here for for and while loops.
13th Jan 2020, 11:06 PM
Jianmin Chen
Jianmin Chen - avatar
+ 1
13th Jan 2020, 10:56 PM
HonFu
HonFu - avatar