Learning Python - 4th Day (Night)

 Watched this tutorial: Click here


I have learnt 2 things.

while loop and for loop in python.

I have studied java , c++ before, so I thought these loops are might be the same as it was in java and C++, so I was going to skip this tutorial until I realized, NO! In python they are different and more usable.

While loop:

Let's have an example of a water tank and one water pump.
I have a blank 1000 liters water tank. Now I have to fill it up with water.

To fill the tank with water I need to turn on the water pump. In order to fill up the tank without wasting water, the pump needs to run until the tank gets filled up.

Let's say it line by line:

While the tank's water level is less than 1000 liters:
       The pump will run

Let's implement that in python:

while water_level < 1000:
    water_pump = on

Like this let's have a real example here:

I need to print "Hello, Shad" 5 times:

print_count = 0

while print_count < 5
    print("Hello, Shad")
    print_count = print_count + 1

Output: 

Hello,Shad
Hello,Shad
Hello,Shad
Hello,Shad
Hello,Shad

In a sentence, while means a loop that will work continuously whenever a condition is true.

For loop:

Let's say, I have a list.

myList = ['Samsung', 'Iphone', 'Xiaomi', 'Asus']

Now I want to print full array:

print(myList)

Output: ['Samsung', 'Iphone', 'Xiaomi', 'Asus']

But I need all the items printed one by one.

for i in myList
    print(i)

Output: 

Samsung
Iphone
Xiaomi
Asus

Just like this, for loop is used many times in a project. 

More about while and for loops: 

While loops
Definition
A while loop will continue to repeat a block of code while some condition is true. It checks the condition at the start of each loop and if it is False then it doesn’t run the block of code.

Hint

A while loop will always need the condition to result in True or False.

Easy example
fileName = ''
while fileName == '':
    fileName = input('Please enter a filename: ')
print('Thank you.')
Show/Hide Output
Syntax
while condition:
    print('do this')    #the conditions indented will repeat while the condition is true
    print('and this')

print('After, do this') #this will happen once the condition is false
Examples
Example 1 - While to check a string
userPassword = ''

while userPassword != 'secret':
    userPassword = input('Type in your password: ')

print('Access granted!')
Show/Hide Output
Example 2 - While with a flag - to continue playing a game
playGame = True

while playGame:
    print('We are playing the game')

    playAgain = input('Would you like to playAgain? ')

    if playAgain == 'n' or playAgain == 'no':
    playGame = False

print('Thank you for playing')
Show/Hide Output
Example 3 - An infinite loop
while True:
    print('hello')
Show/Hide Output
Example 4 - While to check a list
usernames = ['Tony', 'asmith', 'Angela']

userChoice = ''

while userChoice not in usernames:
    userChoice = input('Type in your username: ')

print('Hi ' + userChoice)
Show/Hide Output
Key points
Hint

Beginners will often write while gameOver == True:. This should be rewritten while gameOver: and is easier for programmers to read.

Note

while True: creates an infinite loop. It is possible to break out from this if a condition is met using the break keyword. In general, break is not a good technique to use as it can make code hard to debug - use flags instead.

Note

A while loop is one way of performing iteration (looping). The other way is to use a for loop. While loops are also known as condition-controlled loops/iteration.

See also

#Reference: https://www.easypythondocs.com/while.html


For loops
Definition
In Python, a for loop can be used in two ways. It can either repeat a block of code a pre-defined number of times, or it can cycle each item in a list.

Warning

A range starts at 0 and doesn’t include the upper number. For example, range(5) would include the numbers 0, 1, 2, 3, 4.

Easy example
for i in range(5):
    print(i)
Show/Hide Output
Syntax - using range
for i in range(number):
    print('statement 1')      #put statements here
    print('statement 2')      #this statement is part of the loop

print('statement3')           #this statement isn't part of the loop
Examples
Example 1 - Output ‘hello’ four times
for i in range(4):
    print('Hello')
Show/Hide Output
Example 2 - Output from 1 to 10
for i in range(1, 11):
    print(i)
Show/Hide Output
Example 3 - Output from 0 to 5
for i in range(6):
    print(i)
Show/Hide Output
Example 4 - Output every other number from 1 to 10
for i in range(1, 11, 2):
    print(i)
Show/Hide Output
Example 5 - Output from 10 to 0
for i in range(10, -1, -1):
    print(i)
Show/Hide Output
Example 6 - Loop with concatenation (joining strings together)
for i in range(10):
    print('The current number is: ' + str(i))
Show/Hide Output
Example 7 - Loop through a string
secretWord = 'This is a secret'

for letter in secretWord:
    print(letter)
Show/Hide Output
Example 8 - Loop through a list (array)
popularNames = ['Emma', 'Liam', 'Olivia', 'Mason', 'Ava', 'Lucas']

for name in popularNames:
    print(name + ' is a popular name.')
Show/Hide Output
Example 9 - Nested loop - times tables
maxTimesTable = 3
numberOfRows = 10

for i in range(1, maxTimesTable + 1):
    for j in range(1, numberOfRows + 1):
        answer = i * j
        print(str(i) + '*' + str(j) + ' = ' + str(answer))

    print('----------')
Show/Hide Output
Key points
Note

Loops can be nested. This means that a for loop is placed inside another for loop.

Hint

The variable name i is often used for a counter name. For nested loops, i, j, k are often used.

Warning

All statements in the loop must be tabbed over to the exact same amount if the are to be part of the loop.

Note

A for loop is one way of performing iteration (looping). The other way is to use a while loop. For loops are also known as count-controlled loops/iteration.

Note

Python allows you to repeat a string without using a loop. For example, print('Hello\n' * 5) will print the string Hello five times on the screen.

#Reference: https://www.easypythondocs.com/forloops.html

Comments

Popular posts from this blog

Apple iPad Air (2022) Specifications and Review in 2023

17-year-old suspect in fatal stabbing at Taylor Swift-themed dance event ID’d

Exercise vs Diet