Pages


Wednesday, 12 June 2019

(Post 9/Year 1 Week 1)Learning python part 9:For Loop

In this post,we will cover loop

hello Let's do a very simple For loop

Code

##for looper in the list containing 1,2,3,4,5 print hello for looper in [1, 2, 3, 4, 5]: print("hello")
Output



Let try again, by changing the looper

Code


##it need not be looper ,it can be anything eg I or thing ##for thing in the list containing 1,2,3,4,5 print hello for thing in [1, 2, 3, 4, 5]: print("hello")
Output


Using a counting loop

Now let’s do something a bit more useful with loops. Let’s print a multiplication table. It
only takes a small change to our program. Here’s the new version.

##for looper in the list 1,2,3,4,5 print looper,"times 8",looper multiply by 8 for looper in [1, 2, 3, 4, 5]: print(looper, "times 8 =", looper * 8)
Output



In the previous example, we only looped 5 times:
But what if we wanted the loop to run 100 times, or 1,000 times? That would be a lot
of typing!

Luckily, there’s a shortcut. The range() function lets you enter just the starting and ending
values, and it creates all the values in between for you. range() creates a list containing a
range of numbers.

The next listing uses the range() function in the multiplication table example.

Code

##for looper in the range of 1 to 5,print looper,"times 8=',looper *8 for looper in range (1, 5): print(looper, "times 8 =", looper * 8)

Output



It’s almost the same as the first result … except that it missed the last loop! Why? Because range (1, 5) gives us the list [1, 2, 3, 4].

Code
##print(range 1 to 5) print range(1, 5)

Output


Let's  now modify the loop to print ten times

Code

##for looper in range 1 to 11,print looper,"times 8",looper *8 for looper in range(1, 11): print looper, "times 8 =", looper * 8
Output



Remenber ,i say that looper can be change with anything e.g such as I,Now let change the looper with i
##for I in range from 1 to 5,print I,"times 8=,i*8
For i in range(1, 5):
 print(i, "times 8 =", i * 8)
Output


Now let's try a range shortcut

Code
##for I in range (5),print i
for i in range(5):
   print(i)
Output


This is the same as the below code

Code


##for i in range 0 to 4,print i
for i in range(0, 5):
    print(i)
Output


No comments:

Post a Comment