Python Tutorial for Beginners Part 3

Python Tutorial for Beginners Part 3

Branching:-

Branches can define by the conditions in the flow of a program.
We use if, elif , else keywords for Branching.

We can create multiple branches using elif keywords.

if ( condition ):
   ......

else:
   ......
if ( condition ):
   ......
elif ( condition ):
   ......
elif ( condition )
   ......
else:
   ......

Covered Topics

  • Branching
  • Indentation
  • Assignment vs. Equality
  • Iteration
  • Range function
  • Control Statements
a = 5
b = 3
if a > b:
    print(a)
else:
    print(b)
#
#
if else flowchart
a = 5
b = 3
if a > b:
    print(a)
elif a < b:
    print(b)
else:
    print("they are equal")
if elif else flowchart

Indentation:-

Indentation refers to spaces added at the beginning of a statement in our code. And as we already know, each line of code is called a statement.

You can use as many indenting spaces as you like, but there must be at least one. By default, Python uses four spaces for indentation. And for four (4) spaces.

indentation-example-image

You can use a tab key on your keyboard. All statements indented the same belong to the same block of code.

Simply, instructions belonging to a block of code must assume the same vertical alignment. And if a block needs to be nested deeper than the previous one, it’s just indented further to the right. Anytime you specify a different number of spaces for declarations within the same block of code, you’ll get an error message from the Python interpreter.

if False:
    print("Cyber Connaught")
print("Cyber")
Output :- Cyber
if False:
    print("Cyber Connaught")
    print("Cyber")
Output :- 

We can nest “if” statements to create complex branching. Nesting is done by indentation

a = int(input("Enter a number for a: "))
y = int(input("Enter a number for y: "))
if a == y:
    print("a and y are equal")
    if y != 0:
        print("therefore,  a / y is", a/y)
elif a < y:
    print("a is smaller", a)
else:
    print("y is smaller", y)

Assignment vs. Equality:-

= ” is assignment
righthand side value is assigned to lefthand side variable

== ” is a check for equality
returns True if the left-hand side is equal to the right-hand side

x = 5
if x == 5:
    print("string")
Output :- string
x = 5
if x = 5:
    print("string")
Output :- if x = 5:
              ^
SyntaxError: invalid syntax

Iteration:-

Sometimes we want a program to do, the same work many times in a specific way there we use
iteration.

  1. Printing numbers from 1 to 100
  2. Print odd or even numbers from 1 to 100
  3. Get each number from 1 to 100 and check its prime or not
  4. Get factorial of number i.e, 5!(5 factorial) = 5.4.3.2.1

All these examples require repetitive tasks to complete multiple times, these repetitive tasks can be done easily by looping in Python.

While Loop

Do something repetitively until it reaches the termination condition, in this case, we use the while loop.
The while loop is used to do something as long as a condition holds that’s why make sure that the loop terminates otherwise you get an infinite loop.

For Loop

The for loop is used for iterating over a sequence it is either a list, a tuple, a dictionary, a set, or a string.

For Loop

for <variable> in <sequence>:
    <do something>
for i in range(1,6):
    print('Hello World')
#
#
for loop flowchart

While Loop

while <conditon>:
    <do something>
i = 1
while i<=5:
    print('Hello World')
    i+=1
while loop flowchart

Example of for loop

k =  int(input("Enter num "))
l=[]
for i in range(2,k):
    if k % i == 0:
        l.append(int(0))
    else:
        l.append(int(1))
if int(0) in l:
    print(k, "is not prime.")
else:
    print(k, "is prime.")

Example of while loop

k =  int(input("Enter num "))
i = 2
con = True
while i < k and con:
    if k % i == 0:
        con = False
    i = i + 1
if con:
    print(k, "is prime.")
else:
    print(k, "is not prime.")

Range function:-

While using for loops sometimes we need to provide a sequence of numbers, there we use the range()
Range function provides a sequence of integer values.
Range function has 3 arguments start, stop, step. An argument is a parameter input to a function

range(start, stop, step)

start = 0 ( if not assign )
step = 1 ( if not assign )

range(5) = 0,1,2,3,4range(5) means, range(start = 0, stop = 5, step = 1)
Note:- It includes 0 and exclude 5
range(1,9,2) = 1,3,5,7range(1,9,2) means, range(start = 1, stop= 9, step = 2)
Note:- It includes 1 and excludes 9

Remember here “stop” is exclusive

range( 10 , 0 , -1 ) = 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1

Control Statements:-

There may be times when you want to exit the loop completely, skip an iteration, or ignore a condition. These can be handled with loop control statements (break, continue and pass). The loop control statements interrupt the execution flow and terminate/skip the iteration as needed.

Simply reading this post will provide you with a comprehensive insight into the topic.

Break

The break statement is used to end the loop or statement that contains it.

Continue

The continue statement is the inverse of the break statement in that it causes the loop to perform the next iteration rather than ending it.

Pass

As the name implies, the pass statement does nothing.

for i in range(1,10):
    if i == 6:
        break
    else:
        print(i)
# can use while too
Output:- 1 2 3 4 5
for break tutorial
for i in range(1,10):
    if i == 6:
        continue
    else:
        print(i)
# can use while too
Output:- 1 2 3 4 5 7 8 9
for continue tutorial
str = "Cyber@Connaught"
for i in str:
    if i == "@":
        print("pass")
        pass
    print(i)
Output:- C y b e r pass @ C o n n a u g h t

Leave a comment