Conditional and Looping Constructs

Introduction:

In the programs we have seen till now, there has always been a series of statements faithfully executed by Python in exact top-down order. What if you wanted to change the flow of how it works? For example, you want the program to take some decisions and do different things depending on different situations, such as printing ‘Good Morning’ or ‘Good Evening’ depending on the time of the day?

Similarly while writing program(s), we almost always need the ability to check the condition and then change the course of program.

Types of Statements in Python:

Statement is the instructions given to the computer to perform any kind of action.

Three type of Statement:

a) Empty Statement: As the name suggested, this statement does not contain anything. In python an empty statement is pass statement.

b) Simple Statement (Single Statement): Simple statements are comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. For example,

                       A=10

                       B=int(input(“Enter Number”))

c) Compound Statement: Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way.

For example:

i) def sum ( ):

           a=10           #Function sum ( ) contains multiple statements or compound statement.

            b=20

s=a+b

print (“The Sum is :”,s)

sum( )                                                  #calling of sum function

ii) a=int(input(“Enter Number: ”)

if a>0:

            print(“Number is positive”)

else

            print(“Number is negative”)

Statement Flow of Control:

The flow of activity through the program code is called the flow of control. Usually the flow of control is sequential, that is, the statements are executed in the order in which they appear in the code. In computer programming, there are three main types of control flows that occur. These are:

  • Sequential: The statements execute from top to bottom sequentially.

sequential

  • Conditional or selection: Out of two instructions, only one will be executed successfully depending on the condition. Because the condition produces a result as either True or False.

comp

  • Repetition or loop: In which the instruction(s) are repeated over a whole list whenever the condition is True.

loop

Program Logic Development:

Algorithm, flowchart and pseudo code are three types of tools to explain the process of a program.

Algorithm: An algorithm is a precise specification of a sequence of instructions to be carried out in order to solve a given problem.

  • An Algorithm is a technique to solve a given problem systematically.
  • An Algorithm is a step-by-step approach to solve a given problem in finite number of steps.
  • It takes a set of input values and processes it and gives the output.
  • Each instruction tells what task is to be performed.

Properties (characteristics) of an Algorithm:

  • It should be simple.
  • It may accept zero or more inputs.
  • It should be precise with no ambiguity.
  • It should have finite number of steps.
  • It should produce at least one output.

Flowchart: A flowchart is the graphical or pictorial representation of an algorithm with the help of different symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we can easily understand a program. The main purpose of a flowchart is to analyze different processes. Several standard graphics are applied in a flowchart:

  • A flowchart depicts pictorially the sequence in which instructions are carried out in an algorithm.
  • A flowchart is a schematic representation of an algorithm or a stepwise process, showing the steps of boxes of various kinds and their order by connecting these with arrows.
  • Flowcharts are used not only as aids in developing algorithms but also to document algorithms.
  • Flowcharts are used in designing or documenting a process or program.

Flowcharts Symbols:

Symbol Name Function
1 Start and Stop

OR  Terminal

Indicates the starting or ending of the program, process, or interrupt program
2 Process Indicates any type of internal operation inside the Processor or Memory
3 input/output Used for any Input / Output (I/O) operation. Indicates that the computer is to obtain data or output results
4 Decision

 

Used to ask a question that can be answered in a binary format (Yes/No, True/False)
5 Connector

 

Allows the flowchart to be drawn without intersecting lines or without a reverse flow.
6 Predefined Process Used to invoke a subroutine or an interrupt program.
7 Flow Lines Shows direction of flow. It indicates the flow of data from one geometrical signal to another.

For Example: Write Algorithm to check whether entered number is even or odd and also draw the flowchart for the same.

Algorithm:                                                                                        Flowchart:

Step 1 : Start                                                                         flow1

Step 2 : Input Number

Step 3 : rem=number mod 2

Step 4 : if rem=0 then

              Display “Even Number”

           else

               Display “Odd Number”

           endif

Step 5 : Stop

Pseudocode: Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is a “text-based” detail (algorithmic) design tool.

Examples 1:

If student’s grade is greater than or equal to 60

Print “passed”

else

Print “failed”

Example 2:

  1. Initialize total to zero
  2. Initialize counter to zero
  3. Input the first grade
  4. while the user has not as yet entered the sentinel
  5. add this grade into the running total
  6. add one to the grade counter
  7. input the next grade (possibly the sentinel)
  8. if the counter is not equal to zero
  9. set the average to the total divided by the counter
  10. print the average
  11. else
  12. print ‘no grades were entered’

Example 3: Write a pseudo code and Python program code to calculate the sales tax of an item.

Solution Pseudo Code:

  1. Input Price of item
  2. Input Sales tax rate
  3. Calculate Sales tax = price of item X Sales tax rate/100
  4. Final price = Price of item plus Sales tax
  5. Display Final price
  6. Stop

Python Code:

# 1. Input Price of item

Price = float(input(“Enter item’s price: “))

# 2. Input Sales tax rate

Tax_rate = float(input(“Enter the sales tax rate, in decimal: “))

# 3. Sales tax = Price of item times Sales tax rate

Tax = Price * Tax_rate/100

#4. Final price = Price of item plus Sales tax

Final_price = Price + Tax # 5. Display Final price

print (“The final price is: %7.2F” % Final_price)

 Conditional Control:

Conditional control statements are also called branching or selection statements that execute one group of instructions depending on the outcome of a decision. In this category, Python programming language provides following types of decision making statements as

Statement Description
if statements An if statement consists of a Boolean expression followed by one or more statements.
If…….else statement An-if statement can be followed by an optional else statement, which executes\when the Boolean expression is false.
Nested if statement You can use one if or else if statement inside another if or else if statement(s).

if Selection Structure:-

Selection structures choose among alternative courses of action. For example, suppose that the passing grade on an examination is 60. Then the pseudo code statement

If student’s grade is greater than or equal to 60

Print “Passed”

Determines whether the condition “student’s grade is greater than or equal to 60” is true or false. If the condition is true, then “Passed” is printed.

The general Python syntax for a simple if statement is

if condition:                                                                                  

                     indented Statement Block                            Flow diagram of if condition

 

if1

If the condition is true, then do the indented statements. If the condition is not true, then skip the indented statements.

Example 1:

if balance < 0:

transfer = -balance

backupAccount = backupAccount – transfer # take enough from the backup acct.

balance = balance + transfer

In the examples above the choice is between doing something (if the condition is True) or nothing (if the condition is False). Often there is a choice of two possibilities, only one of which will be done, depending on the truth of a condition.

Example 2: Write a program to take a value from the user and print the square of it, unless it is more than 120. The message I cannot square numbers that appear if the user types too large a number.

Solution:

num = int(input(“What number do you want to see the square of? “))

 if num < 120:

                        square = num * num; print (“The square of %d is %d “ % (num, square))

 if num >= 120:

                          print (“*** Square is not allowed for numbers over 120 ***” )

print (“Run this program again and try a smaller value. “)

print (“Thank you for requesting squares.”)

if – else Statements:-

If the conditional statement under if is evaluated to be true then the statement under if block will be executed otherwise the statements under else block would be executed.

The general Python syntax is                                                             flow diagram                                                    ifelse

if condition :

         indentedStatementBlockForTrueCondition

else:

         indentedStatementBlockForFalseCondition

These statement blocks can have any number of statements, and can include about any kind of statement.

For Example:

x = 0

y = 3

x += y

if  x > y :

                print(”x is greater”)

else :

          print(”we are in else part because x and y both became equal”)

Output:

>>>  we are in else part because x and y both became equal

The above code produces an output as ―”we are in else part because x and y both became equal” because the conditional statement under if evaluates as false as x is not greater than y, it is same as that of y.

Example: Write a program to find greatest among 3 numbers

ALGORITHM:                                                                            FLOWCHART:

Step1:start                                                                                                                 flow2.png

Step2:input a,b,c

Step3:if(a>b) &&(a>c)

Step4: display a is grater

Step 5:else

Step6:if(b>c)

Step7: display b is grater

Step 8:else

Step: display c is grater

Step10:stop

 

Program:

a=b=c=0

a=float(input(“Enter value of a: “))

b=float(input(“Enter value of b: “))

c=float(input(“Enter value of c: “))

if a>b and a>c:

        print(“%.1f is greatest of  %.1f  %.1f  %.1f”%(a,a,b,c))

else:

        if b>c:

            print(“%.1f is greatest of  %.1f  %.1f  %.1f”%(b,a,b,c))

        else:

            print(“%.1f is greatest of  %.1f  %.1f  %.1f”%(c,a,b,c))

5) Result:

Enter the values of a: 10

Enter the values of b: 30

Enter the values of c: 20

30.0 is greatest of 10.0  30.0 20.0

Example: The program takes a number and checks whether it is positive or negative.

Problem Solution

  1. Take the value of the integer and store in a variable.
  2. Use an if statement to determine whether the number is positive or negative.
  3. Exit.

Program/Source Code

n=int(input(“Enter number: “))

if n>0 :

    print(“Number is positive”)

else:

    print(“Number is negative”)

Program Explanation

  1. User must first enter the value and store it in a variable.
  2. Use an if statement to make a decision.
  3. If the value of the number is greater than 0, “Number is positive” is printed.
  4. If the value of the number if lesser than 0, ”Number is negative” is negative.

Run time Test Cases

Case 1:

Enter number: 45

Number is positive

Case 2:

Enter number: -30

Number is negative

 Multiple Tests and if – elif Statements (Ladder if – else):-

The most elaborate syntax for an if statement, if- elif-…-else is indicated in general below:

if condition1 :                                                                            

indentedStatementBlockForTrueCondition1

elif condition2 :

indentedStatementBlockForFirstTrueCondition2

elif condition3 :

indentedStatementBlockForFirstTrueCondition3

elif condition4 :

indentedStatementBlockForFirstTrueCondition4

else:

indentedStatementBlockForEachConditionFalse 

flow3

In the above syntax there are ladder of multiple conditions presented by each if, all of these conditions are mutually exclusive that is only one of them would get satisfied and all the conditions below it would not be evaluated and is discarded.

Say suppose if condition-3 gets satisfy i.e. it yields a true value for the condition, the statement under the block of third if gets executed and all other n number of if conditions below it would be discarded.

If none of the n if conditions gets satisfied then the last else part always gets executed. It is not compulsory to add an else at the last of the ladder.

Example 1: Write a program to enter a number and check if the number is zero, positive or negative using if-else-if ladder.

SOLUTION:

N = int(input(“Enter any number: “))

if (N<=-1):

           print(“N is a negative number having value “, N)

elif (N ==0):

            print(“N is a zero number having value “)

elif (N > O):

            print(“N is a positive number having value N”)

Example 2: Program that reads two numbers and an arithmetic operator and displays the computed result.

Algorithm:

Step 1: Start

Step 2: Read x and y values

Step 3: Read option + or – or * or / or %

Step 4: If option is ‘+’ res = x + y

Step 5: If option is ‘-’ res = x – y

Step 6: If option is ‘*’ res = x * y

Step 7: If option is ‘/’ res = x / y

Step 8: If option is ‘%’ res = x % y

Step 9: If option does not match with + or – or * or / or %

           Print select option +, -, *, /, /, % only

Step 10: Print x, option, y, res values

Step 11: Stop

Solution:

Num1 = float ( input( “Enter first number :” ) )

Num2 = float ( input( “Enter second number :” ) )

op = input( “Enter operator [ + – * / % ] :” )

result = 0

if op ==’+’ :

          result = num1 + num2

elif op ==’-‘:

           result = num1 – num2

elif op == ‘*’ :

           result = num1* num2

elif op ==’/’ :

           result = num1 / num2

elif op ==’ %’ :

           result = num1% num2

else :

           print (“Invalid operator! !”)

print (num1, op, num2 , ‘=’, result)

Example 3: This program allows the user to enter any year and then it will check whether the user entered year is Leap year or not using the python elif.

year = int(input(“Please Enter the Year Number you wish: “))
if (year%400 == 0):
          print(“%d is a Leap Year” %year)
elif (year%100 == 0):
          print(“%d is Not the Leap Year” %year)
elif (year%4 == 0):
          print(“%d is a Leap Year” %year)
else:
          print(“%d is Not the Leap Year” %year)

 

NESTED IF STATEMENTS:-

There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct.

In a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.

The syntax of the nested if…elif…else construct may be:nestedif else

If the test expression 1 present in the above structure is true then compiler will go to nested if statement

  • If the test expression 2 is True then Test expression 2 True statements will be executed
  • Else (it means test expression 2 is false) Test expression 2 false statements will be executed

If the test expression 1 is false then Test expression 3 will be test, if expression 3 will be false then else will be executed.

Example 1:  for Python Nested If Statement

age = int(input(” Please Enter Your Age Here:  “))
if age < 18:
    print(” You are Minor “)
    print(” You are not Eligible to Work “)
else:
    if age >= 18 and age <= 60:
        print(” You are Eligible to Work “)
        print(” Please fill in your details and apply”)
    else:
        print(” You are too old to work as per the Government rules”)
        print(” Please Collect your pension!”)

 

Example 2: Program that reads three numbers (integers) and prints them in ascending order.

Solution:

x = int(input( “Enter first number :” ))
y = int (input ( “Enter second number :” ))
z = int(input( “Enter third number :” ))
min = mid = max = None
if x < y and x < z :
if y < z :
min, mid, max = x, y, z
else :
min, mid, max = x, z, y
elif y < x and y < z :
if x < z :
min, mid, max = y, x, z
else :
min, mid, max = y, z, x
else :
if x < y :
min, mid, max = z, x, y
else:
min, mid, max = z, y, x
print (“Numbers in ascending order :”, min, mid, max)

Compound Boolean Expressions:-

The new Python syntax is for the operator and:

condition1 and condition2

It is true if both of the conditions are true. It is false if at least one of the conditions is false.

To be eligible to graduate from Jamia Millia Islamia, you must have 128 units of credit and a GPA of at least 2.0. This translates directly into Python as a compound condition:

Example:

Write an application to calculate your class grade and grade-point for a subject mark  as per the following table:

Marks Range Grade Grade Pint
91-100 A1 10.0
81-90 A2 9.0
71-80 B1 8.0
61-70 B2 7.0
51-60 C1 6.0
41-50 C2 5.0
33-40 D 4.0
21-32 E1 0.0
00-20 E2 0.0

Solution: 

# Calculating grade for a subject

Mark = input(“Enter a subject mark: “)
Grade, GrPoint = “Non”, 0.0
if Mark >= 91 and Mark <= 100:
Grade = “Al”
GrPoint = 10.0
elif Mark >= 81 and Mark < 91:
Grade = “A2”
GrPoint = 9.0
elif Mark >= 71 and Mark < 81:
Grade = “B1″
GrPoint = 8.0
elif Mark >= 61 and Mark < 71:
Grade =”B2”
GrPoint = 7.0
elif Mark >= 51 and Mark < 61:
Grade = “C1”
GrPoint = 6.0
elif Mark 41 and Mark < 51:
Grade = “C2”
GrPoint = 5.0
elif Mark >= 33 and Mark < 41:
Grade = “D”
GrPoint = 4.0
elif Mark >= 21 and Mark < 33:
Grade =”E1″
GrPoint = 0.0
elif Mark >= O and Mark < 21:
Grade = “E2”
GrPoint = 0.0
print (“The grade is: “, Grade)
print (“Grade point is: “, GrPoint)

Looping / Iteration Constructs:-

The iteration constructs means repetition of a set of statements depending upon a condition test. Till the time a condition is true (or False depending upon the loop), a set of statements are repeated again and again. As soon the condition becomes False (or True), the repetition stops. The iteration constructs is also called looping constructs.

Two types of looping construct in Python

  1. while loopwhile loop flowchart
  2. for loop

while loop:-

The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause.

 

Its syntax is:

while (condition) :                # condition is Boolean expression returning True or False

                STATEMENT’s BLOCK 1

else:                                                   # optional part of while

STATEMENT’s BLOCK 2

Here,

  • We can see that while looks like if statement. The while statement star with keyword while followed by Boolean condition followed by colon (:).
  • A while loop consists of the keyword while.
  • It contains a Expression/Condition called Boolean expression which produce either a true of false result depending on the counter control.
  • The Expression/Condition controlled by a counter control variable which produces a true result for a number of times.
  • When the Expression/Condition becomes False, program control passes to the line immediately following the loop.
  • The Program statements are called the body of the loop, which can be a single statement or a block of statements and indented inside while and else loop.
  • The else statement is optional and executed the Program statements when the condition becomes False.
  • If you do not mention the else statement and when the condition is tested and the result is False, the loop body will be skipped and the first statement after the while loop will be executed.
  • To exit from the loop you can use break statement at any place in between the loop. Details about break statement will be discussed latter in the chapter.

NOTE:The statement(s) in BLOCK 1 keeps on executing till condition in while remains True; once the condition becomes False and if the else clause is written in while, and then else will get executed. While loop may not execute even once, if the condition evaluates to false, initially, as the condition is tested before entering the loop.

Some examples of while loop are:

Example 1:

num = 5

while num != O:

print (num)

num = num — 1

this loop prints a num starting from 5 and going down to 1, until the num becomes 0 which is the terminating condition of the loop.

Example 2:

n = int(input(“Enter value of n: “))

while (i < n):                       # This loop counts i up to n.

print (i)

i = i + 1

Here, the while loop is controlled by a loop counter variable i. The loop will only terminated when i equal to n or greater than n.

Example 3:

num = 5

while (num):

print (num)

num – = 1

Here, the while (num) is same as saying while (num != 0). So, this example is same as:

num = 5

while (num !=0):

print (num)

num – = 1

Example 4:

i = 4                            #line no. 1

while (i < 9):              #line no. 2

    print(i)                    #line no. 3

    i = i+2                       #line no. 4

The output is

4

6

8

The sequence order is important. The variable i is increased before it is printed, so the first number printed is 6. Another common error is to assume that 10 will not be printed, since 10 is past 9, but the test that may stop the loop is not made in the middle of the loop. Once the body of the loop is started, it continues to the end, even when i becomes 10.

line i comment
1 4
2 4 < 9 is true, do loop
3 6 4+2=6
4 print 6
2 6 < 9 is true, do loop
3 8 6+2= 8
4 print 8
2 8 < 9 is true, do loop
3 10 8+2=10
4 12 print 10
2 10 < 9 is false, skip loop

 SOLVED EXAMPLES:

Example 1: Write a program with a flowchart and Python program to print the numbers from 1 to 10 using while loop.
SOLUTION :
# Program to print numbers from 1 to 10      while ex1
count = 1
while (count < 11):
print (‘The count is: l, count)
count = count + 1
print (“Thank you!”)

which will produce the following output:

The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
The count is: 10
Thank you!
Here, the block consisting of the print and increment statements, is executed repeatedly until the count is less than 11. With each iteration, the current value of the index count is displayed and then increased by 1.

Example 2:  Write a flowchart and program to find the sum of first 10 natural numbers. That is :
1+2+3+4+5+6+7+8+9+10=55
Also, explain the program code execution style.
SOLUTION : while ex2.jpg
Python Code:
# Program to find sum of first 10 natural numbers.
ctr = 1
SumN = 0
while (ctr <= 10):
SumN = SumN + ctr
ctr + = 1
print (“Sum of first 10 natural numbers is:”, SumN)

Here,
• The ctr variable in the above code is 1.
• The low value is 1 and the high value is 10.
• The body of the loop consists of a single statement to add ctr value with SumN.
• The effect of this code is to compute and then output the SumN of the numbers from 1 to 10.

Example 3: Draw a flowchart and write a Python program to find the factorial of an input number.
i.e., factorial of 5 x 4 x 3 x 2 x 1 = 120
SOLUTION : while ex3.jpg
# Program to find the factorial of a number
Fact = ctr = 1
N = int(input(“Enter any number to find factorial)
while (ctr <= N):
Fact = Fact * ctr
ctr+=l
print (“The factorial of %d is 0/0.2f”% (N, Fact))

  

Example 4: Write a program to find the Fibonacci Series upto 10 terms.

Note: A Fibonacci series is: O, 1, 1, 2, 3, 5, 8, 13,21,34                                                   

Solution:

# Program to find the Fibonacci Series of numbers till 20.

f1,f2=0,1
n=0
print(f1,f2,end=” “)
while(n<8):
f3=f1+f2
f1=f2
f2=f3
n+=1
print (f2, end=” “)

Example 5: Write a program that accepts two numbers and prints their highest common factor.
SOLUTION :
# Program to find HCF of two numbers
x = int(input(“Enter first number: “))
y = int(input(“Enter second number: “))
if x > y:
x1= x; y1 = Y
else:
y1= x; x1 = Y
rem = 1
hcf = 0
while (rem!=O):
hcf = y1
rem = x1 % y1
quotient = x1 / y1
y1 = rem
print (“HCF of %d and %d is: %(x, y, hcf))

The output is:
Enter first number: 10
Enter second number: 5
HCF of 10 and 5 is: 5

The else Statement used with while Loop: 

Python supports to have an else statement associated with while loop. If the else statement is used with a while loop, the else statement is executed when the condition becomes False.
The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5 otherwise else statement gets executed.

# Program to demonstrate else statement with while loop

ctr = 5
while (ctr < 10):
print (“%d is less than 10” % ctr)
ctr = ctr + 1
else:
print (“%d is not less than 10” % ctr)

When the above code is executed, it produces the following results:
5 is less than 10
6 is less than 10
7 is less than 10
8 is less than 10
9 is less than 10
10 is not less than 10

The range( ) Function:

Before start with for loop, let us discuss the range (  ) function .

You can generate a sequence of numbers using range ( ) function. This function does not store all the values in memory, it would be inefficient. It just remembers the start, stop, step size and generates the next number on the go. It is most often used in for loops. The arguments must be plain integers. The general format of range ( ) function is:

Syntax is :

range ( [start,] stop[, step])

Here,

  • start and step are optional.
  • start is the staring number of range. If the start argument is omitted, it defaults to 0.
  • stop is the last number of range where the range will end. That is the exact end position is: stop -1.
  • step is the increment.

Examples :
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]

>>> range(0, 10, 3)
[0, 3, 6, 9]

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

range(x) is the simplest way to loop n times in Python is: range(x) returns a list whose items are consecutive integers from 0 (included) up to x (excluded).
for i in range(n):
statement(s)
Example:
x=10
for i in range(x):                           #1 value pass to range()
print (i),

output:
0 1 2 3 4 5 6 7 8 9

range(x,y):can take two numbers and tells Python to count from the one to the other. By default, it does this in increments of 1. range(x, y) returns a list whose items are consecutive integers from x(included) up to y (excluded). The result is the empty list if x is greater than or equal to y.
for i in range(x, y):
statement(s)
Example:
x=11
y=21
for i in range(x,y):                 #2 value pass to range()
print i,

Output:
11 12 13 14 15 16 17 18 19 20
We can also give 3 values to the range(), x the start point, y the end point and step is the number by which series will increase or decrease.

range(x, y, step): It returns a list of integers from x (included) up to y (excluded), such that the difference between each two continuous items in the list is step. range() returns the empty list when x is greater than or equal to y and step is greater than 0, or when x is less than or equal to y and step is less than 0. When step equals 0, range raises an exception.
for i in range(x, y, step):
statement(s)
Example:
x=11
y=21
step=3
for i in range(x,y,step):                     #3 value pass to range( )
print i,

Output:
11 14 17 20

for loop:- 

The for..in statement is another looping statement which iterates over a any sequence of objects i.e. go through each item in a sequence such as a list or a string. New Doc 2018-08-25 22.08.38.jpg

Its Syntax is:
for <variable> in <sequence>:
           STATEMENT BLOCK 1
else:
           STATEMENT BLOCK 2                           # optional block

  • The body of the loop can be any sequence of Python statements.
  • If a sequence contains an expression list, it is evaluated first, Then, the first item in the sequence is assigned to the iterating variable iterating_var.
  • The variable iterating_var after the keyword for is called the loop index. Figure 6.2 Flowchart of a for loop.
  • Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statements(s) block is executed until the entire sequence is exhausted.
  • The else statement is executed when the loop has exhausted iterating the list.
  • Let us take some examples.

Some Results using range function in for loop:

Statement Output Loop Description
for i in range(5, 10):

print (i, end=” “)

5 6 7 8 9 5 is the start, 9 is the stop and step is default 1.
for i in range(0, 10, 3):

print (i, end=” “)

0 3 6 9 0 is the start, 9 is the stop and step is default 3.
for i in range(-10, -100 -30):

print (i, end=” “)

-10 -40 -70 -10 is start, -100 is stop and step is  -30
for i in range(21,-1,-2):

print (i, end=” “)

21 19 17 15 13 11 9 7 5 3 2 1 21 is start,1 is stop, and step is -2
for i in range(11,3,-1):

print (i, end=” “)

11 10 9 8 7 6 5 4 11 is start, 3 is stop and -1 is step

Example 1: 

for a in [1,4,7]:
print (a)
output:
1
4
7
In the above example, for loop will be processed as follows:

  • Firstly, the loop – variable a will be assigned first value of list that is 1 and the statements in the body of the loop will be executed with this value of a. Hence value 1 will be printed.
  • Next, a will be assigned next value in the list that is 4 and loop – body executed. Thus 4 is printed.
  • Next, a will be assigned next value in the list that is 4 and loop – body executed. Thus 7 is printed.
  • All the values in the list are executed, hence loop ends.

 Example 2:

for A in [1,2,3]:
print (A*A*A)
output:
1
8
27

Example 3:

for ch in ‘Python’
print (ch)

output:
P
y
t
h
o
n

NOTE: variable ch given values are ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’  one at a time from string ‘Python’.

 

Python: Data Types and Operators with Simple Programs

Before write even the most elementary programs in any language, there are some fundamentals you need to know. This blog introduces some such fundamentals: data types, variables, operators and expression in Python.

DATA TYPES: It is a set of values, and the allowable operations on those values. It can be one of the following:

datatype

1. Number

Number data type stores Numerical Values. This data type is immutable i.e. value of its object cannot be changed (we will talk about this aspect later). These are of three different types:

a) Integer

  • Plain integer
  • Long integers                   
  • Boolean

 b) Float/floating point

c) Complex

 a) Integer:

Integers are whole numbers such as 5, 30, 1981,0 etc. They have no fractional parts. Integers can be positive or negative.

 -> Plain integer:

  • Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99, 0, 17.
  • Range of an integer in Python can be from -2147483648 to 2147483647. However, if the result of operation would fall outside this range, the result is normally returned as a long integer.
  • While writing a large integer value, don’t use commas to separate digits. Also integers should not have leading zeros.

-> Long integer:

  • When we want a value to be treated as very long integer value appends L to the value. Such values are treated as long integers by python.
  • Long integer has unlimited range subject to available memory. In python 2.2 and later, ints are automatically turned into long ints when they overflow.

Example:

>>> a = 10

>>> b = 5192L                                  #example of supplying a very long value to a variable

>>> c= 4298114

>>> type(c)                                     # type ( ) is used to check data type of value

<class ‘int’>

>>> c = c * 5669

>>> type(c)

<class ‘long’>

-> Boolean Type:

  • It is a unique data type, consisting of two constants, True & False.
  • A Boolean True value is Non-Zero, Non-Null and Non-empty.

Example

>>> flag = True

>>> type(flag)

<class ‘bool’>

b) Floating Point:

  • Numbers with fractions or decimal point are called floating point numbers.
  • A floating point number will consist of sign (+, -) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963.
  • These numbers can also be used to represent a number in engineering/ scientific notation.

-2.0X 105 will be represented as -2.0E5

2.0X10-5 will be 2.0E-5

Example

y= 12.36

A value when stored as floating point in Python will have 53 bits of precision.

c) Complex:

  • Complex number in python is made up of two floating point values, one each for real and imaginary part.
  • For accessing different parts of variable (object) x.
  • We will use real and x.image.
  • Imaginary part of the number is represented by ‘j’ instead of ‘i’, so 1+0j denotes zero imaginary part.

Example

>>> x = 1+0j

>>> print (x.real, x.imag)

1.0  0.0

Example

>>> y = 9-5j

>>> print (y.real, y.imag)

9.0  -5.0

Data Type Range
Plain integer -231 to +231 – 1 that is -2147483648 to 2147483647 – 1
Long integers An unlimited range, subject to available (virtual) memory only
Booleans Two values True (1) and False (0)
Floating point numbers An unlimited range, subject to available (virtual) memory on underlying machine architecture.
Complex numbers Same as floating point numbers because the real and imaginary parts represented as floats.

2. None:

  • This is special data type with single value. It is used to signify the absence of value/false in a situation. It is represented by None.

3. Sequence

  • A sequence is an ordered collection of items, indexed by positive integers.
  • It is combination of mutable and non mutable data types.
  • Three types of sequence data type available in Python are Strings, Lists & Tuples.
  • Sequential data types contain multiple pieces of data, each of which is numbered, or indexes.
  • Each piece of data inside a sequence is called an element.
  • Sequential data types are that which can manipulate the whole sequence, chunks of the  sequence, or individual elements inside the sequence.

-> String:

  • String is an ordered sequence of letters/characters. They are enclosed in single quotes (‘ ‘) or double (“ “).
  • The quotes are not part of string. They only tell the computer where the string constant begins and ends.
  • They can have any character or sign, including space in them. These are immutable data types.

Python offers two string type:

i) Normal ASCII string:

It is also called str type string. This string type holds string of zero or more ASCII character.

Example:

‘Boy’, Navin’, “ZIG 1981”

ii) Unicode string:

This string type can hold strings containing Unicode characters. Unicode string values are written as – normal strings prefixed with letter u (not in quotes).

Example:

u ‘BOY’, u”Hello mr.”,  u “امجد ”

The Unicode string are used to store Unicode letters (ASCII character + many more)

Conversion from one type to another

In general, the number types are automatically ‘up cast’ in this order:

Int → Long → Float → Complex. The farther to the right you go, the higher the precedence.

Example:

>>> x = 5

>>> type(x)

<type ‘int’>

>>> x = 187687654564658970978909869576453

>>> type(x)

<class ‘long’>

>>> x = 1.34763

>>> type(x)

<class ‘float’>

>>> x = 5 + 2j

>>> type(x)

<class ‘complex’>

It is possible to change one type of value/ variable to another type. It is known as type conversion or type casting. The conversion can be done explicitly (programmer specifies the conversions) or implicitly (Interpreter automatically converts the data type).

For explicit type casting, we use functions (constructors):

int ()

float ()

str ()

bool ()

Example

>>> a= 12.34

>>> b= int(a)

>>> print (b)

12

Example

>>>a=25

>>>y=float(a)

>>>print (y)

25.0

-> Lists: A list is a mutable (can change) sequence data type, elements in a list can be added or removed due to its mutable  feature. List can contain mixed data types which means list elements don’t have to be of the same type.

A list contains items separated by commas and enclosed within square brackets []. List elements are numbered internally starting from 0. There can have nesting of lists one inside other

>>> l = [1,2,3,4,”xyz”,2.34,[10,11]]

>>> l[0]

1

>>> l[4]

‘xyz’

>>> l[6]

[10, 11]

>>> l[6][0]

10

Add element in an existing list

>>> l.append(‘Vishal’)

>>> l

[1, 2, 3, 4, ‘abc’, 2.34, [10, 11], ‘Vishal’]

Remove element from list

>>> del l[0]

>>> l

[2, 3, 4, ‘abc’, 2.34, [10, 11], ‘Vishal’]

Slicing elements of list

>>>1 [1 : 4 ]

[3,4,’abc’]

-> Tuples: Tuples are a sequence of values of any type, and are indexed by integers. Tuples are enclosed in (). A tuple in Python is much like a list except that it is immutable (unchangeable) once created. Tuple can be index, sliceand concatenate, but one cannot append or alter the values of the tuple after it  has been initialized. Tuples are created using round brackets.

>>> t = (1,2,3,4,’abc’,2.34,(10,11))

>>> t[0]

1

>>> t[4]

‘abc’

>>> t[6]

(10,11)

4. Sets:

  • A set stores multiple items, which can be of different types, but each item in a set must be  unique.
  • Use of sets is to find unions, intersections, differences, and so on.
  • Unlike sequence objects such as lists and tuples, in which each element is indexed.
  • Basic uses include membership testing and eliminating duplicate entries.

Operations on sets

#Creating set

>>> s1=set([‘a’, ‘i’, ‘e’, ‘u’, ‘o’])

>>> s2=set([‘m’, ‘w’, ‘d’, ‘i’, ‘t’, ‘o’])

>>> print (s1)

{‘a’, ‘i’, ‘e’, ‘u’, ‘o’}

>>> print (s2)

{d’, ‘i’, ‘m’, ‘o’, ‘t’, ‘w’}

#Add single member in set

>>> s1.add(32)

>>> print (s1)

{‘a’, 32, ‘e’, ‘i’, ‘o’, ‘u’}

#Add group of members in set

>>> s1.update([26, 9, 14])

>>> print (s1)

{‘a’, 32, ‘e’, ‘i’, 9, ‘o’, ‘u’, 14, 26}

#Different types of Membership Testing

>>> 32 in s1

True

>>> ‘o’ in s1

True

>>> 35 not in s1

True

>>> 32 not in s1

False

>>> ‘w’ in s1

False

#Intersection Operation

>>> s1 & s2                              OR                           >>> s1.intersection(s2)

output:  {[‘i’, ‘o’}

#Union Operation

>>> s1 | s2                              OR                           >>> s1.union(s2)

output:  {‘a’, ‘e’, ‘d’, ‘i’, ‘m’, ‘o’, ‘u’, ‘t’, ‘w’}

#Difference Operation

>>> s1 – s2                              OR                           >>> s1.difference(s2)

output: {‘a’, ‘u’, ‘e’}

#Symmetric Difference

>>>s1 ^ s2                                 OR                           >>> s1.symmetric_difference(s2)

output: {‘a’, ‘e’, ‘d’, ‘w’, ‘u’, ‘m’, ‘t’}

5. Mapping

This data type is unordered and mutable. Dictionaries fall under Mappings.

-> Dictionaries: Can store any number of python objects. What they store is a key – value pairs, which are accessed using key. Dictionary is enclosed in curly brackets.

Example

d = {1:’a’,2:’b’,3:’c’}

Syntax for creating dictionary→ >>> d = {‘key1′:’value1′,’key2′:’value2’,…. }

#Create dictionary

>>> phonebook={‘Andrew Parson’:8806336, ‘Emily Everett’:6784346, ‘Peter

Power’:7658344, ‘Lewis Lame’:1122345}

#Show dictionary phonebook

>>>phonebook

{‘Andrew Parson’:8806336, ‘Emily Everett’:6784346, ‘Peter Power’:7658344, ‘Lewis

Lame’:1122345}

#Display keys and its respective values of all the items from dictionary

>>> phonebook.items()

[(‘Emily Everett’, 6784346),(‘Andrew Parson’, 8806336), (‘Lewis Lame’, 1122345),(‘Peter Power’, 7658344)]

#Display the key of value from dictionary

>>> phonebook.keys()

[‘Emily Everett’, ‘Andrew Parson’, ‘Lewis Lame’, ‘Peter Power’]

#Display the value of lists from dictionary

>>> phonebook.values()

[6784346, 8806336, 1122345, 7658344]

#Display the value of a specific key

>>> phonebook.pop(‘Andrew Parson’)

8806336

#Add a new numbers to the phonebook

>>> phonebook[‘Gingerbread Man’] = 1234567

>>> phonebook

{‘Andrew Parson’:8806336, ‘Emily Everett’:6784346, ‘Peter Power’:7658344, ‘Lewis

Lame’:1122345, ‘Gingerbread Man’: 1234567}

#Remove item from dictionary

>>> del phonebook[‘Peter Power’]

>>> phonebook

{‘Andrew Parson’:8806336, ‘Emily Everett’: 6784346, ‘Lewis Lame’: 1122345,

‘Gingerbread Man’: 1234567}

Mutable and Immutable Variables

A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.

Example

>>>x=5

Will create a value 5 referenced by x

x 5

>>>y=x

This statement will make y refer to 5 of x

image1

>>> x=x+y

As x being integer (immutable type) has been rebuild.

In the statement, expression on RHS will result into value 10 and when this is assigned to LHS (x), x will rebuild to 10. So now

x    ————>       10 and

y   ————>        5

Operators:

  • These are those lexical units that trigger some computation when applied to variables and other objects in an expression.
  • Operators are functionality that do something and can be represented by symbols such as + or by special keywords.
  • Operators require some data to operate on and such data is called operands.
  • For example: >>>x = 2+ 3. In this case, 2 and 3 are the operands.
Unary Operator:  
unary plus + The unary (+) must have arithmetic type and the result is the value of the argument. If a = 5 then +a means 5.

If a = 0 then +a means 0.

If a = -4 then +a means -4.

unary minus The unary (+) must have arithmetic type and the result is the negative of its operand’s value If a = 5 then -a means -5.

If a = 0 then -a means 0.

If a = -4 then -a means 4.

Bitwise complement ~ The bit-wise inversion of x is -(x+1) ~5 give -6.
Logical negation not If x is True, it returns False. If x is False, it returns

True.

>>> x=4

>>> y=3

>>> not x<y

True

>>> not x>y

False

Arithmetic Operator:
Addition + Adds two objects 3 + 5 gives 8. ’a’ + ’b’ gives ’ab’.
Subtraction Gives the subtraction of one number from the other; if the first

operand is absent it is assumed to be zero.

-5.2 gives a negative number and 50 – 24 gives 26.
Multiplication * Gives the multiplication of the two numbers or returns the string

repeated that many times.

2 * 3 gives 6. ’la’ * 3 gives ’lalala’.
Division / Divide x by y 4 / 3 gives 1.3333333333333333.
Remainder % Returns the remainder of the division 8 % 3 gives 2. -25.5 % 2.25 gives 1.5.
Exponent ** Returns x to the power of y 3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3)
Floor division // Returns the floor of the quotient 4 // 3 gives 1.
Bitwise Operator:
Bitwise AND & Bit-wise AND of the numbers 5 & 3 gives 1.
Bitwise exclusive OR (XOR) ^ Bitwise XOR of the numbers 5 ˆ 3 gives 6
Bitwise OR | Bitwise OR of the numbers 5 | 3 gives 7
Shift operators:  
Shift left << Shifts the bits of the number to the left by the number of bits

specified. (Each number is represented in memory by bits or binary digits

i.e. 0 and 1)

2 << 2 gives 8. 2 is represented by 10 in bits.

Left shifting by 2 bits gives 1000 which represents the decimal 8.

Shift right >> Shifts the bits of the number to the right by the number of

bits specified.

11 >> 1 gives 5.

11 is represented in bits by 1011 which when right shifted by 1 bit gives

101which is the decimal 5.

Identity operator:  
Is the identity same? is  X ix Y Return True if both its operands are pointing to same object (i.e, both referring to same memory location), returns false otherwise
Is the identity not same? is not X is not Y Return True if both its operands are pointing to different object (i.e, both referring to different memory location), returns false otherwise
Relational Operator: Assume variable x holds 100 and y holds 200
Less than < Returns whether x is less than y. All comparison operators return

True or False.

x < y will return True
Greater than < Returns whether x is greater than y If both operands are numbers, they are first converted to a common type. Otherwise, it always returns False. x > y will return False
Less than or equal to >= Returns whether x is less than or equal to y x <= y will return True
Greater than or equal to >= Returns whether x is greater than or equal to y x >= y will return False
Equal to == Compares if the objects are equal x = 2; y = 2; x == y returns True.

x = ’str’; y = ’stR’; x == y returns False.

x = ’str’; y = ’str’; x == y returns True.

Not equal to != Compares if the objects are not equal x != y will return True
Not equal to <> Compares if the objects are not equal x < > y will return True
Assignment Operators: Assume variable x holds 12
Assignment = Assigned values from right side

operands to left variable

>>>x=12

>>>y=‟greetings‟

Assign quotient /= divided and assign back the

result to left operand

x/=2

x will become 6

Assign sum += added and assign back the result

to left operand

 

>>>x+=2

The operand/expression /constant written on RHS of operator is will change the

value of x to 14

Assign product *= multiplied and assign back the result to left operand x*=2 x will become 24
Assign remainder %= taken modulus using two operands and assign the result to left operand x%=2

x will become 0

Assign difference -= subtracted and assign back the result to left operand x-=2 x will become 10
Assign Exponent **= Performed exponential (power)

calculation on operators and

assign value to the left operand

x**=2

x will become 144

Assign floor division //= performed floor division on

operators and assign value to

the left operand

x / /= 2 x will become 6
Logical Operators:
Logical AND and If both the operands are true, then the condition becomes true. >>> True and True

True

>>> True and False

False

>>> False and True

False

>>> False and False

False

Logical OR or If any one of the operand is true, then the condition becomes true. >>> True or True

True

>>> True or False

True

>>> False or True

True

>>> False or False

False

Membership Operators:
Whether variable in sequence in
Whether variable not in sequence not in

 

Operator Description
 ** Exponentiation (raise to the power)
+ , – unary plus and minus
* , /, %, // Multiply, divide, modulo and floor division
+ , – Addition and subtraction
<, <=, >, >= Comparison operators
==, != Equality operators
% =, / =, // = , -=, + =, * = Assignment operators
not and or Logical operators

Precedence of operator – Listed from high precedence to low precedence.

Statement: A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.

Example of statement are:

>>> x=5

>>> area=x**2                                    #assignment statement

>>>print (x)                                            #print statement

        5

In Python, there are compound/ group statements also. They are sometimes called nested block. Statements belonging to a block are indented (usually by 4 spaces). Leading whitespace at the beginning of logical line is used to determine the indentation level of line. That means statement(s) which go together must have same indentation level.

Example

if i<0:

print (“i is negative”)

else:

print (“i is non-negative”)

Example

if i>0:

print (“i is positive”)

else:

print (“i is equal to 0”)

While writing Python statements, keep the following points in mind:

  1. Write one python statement per line (Physical Line). Although it is possible to write two statements in a line separated by semicolon.
  2. Comment starts with “#” outside a quoted string and ends at the end of a line. Comments are not part of statement. They may occur on the line by themselves or at the end of the statement. They are not executed by interpreter.
  3. For a long statement, spanning multiple physical lines, we can use “/” at the end of physical line to logically join it with next physical line. Use of the “/”for joining lines is not required with expression consists of ( ), [ ], { }
  4. When entering statement(s) in interactive mode, an extra blank line is treated as the end of the indented block.
  5. Indentation is used to represent the embedded statement(s) in a compound/ Grouped statement. All statement(s) of a compound statement must be indented by a consistent no. of spaces (usually 4)
  6. White space in the beginning of line is part of indentation, elsewhere it is not significant.

 

Expression:

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions

(Assuming that the variable x has been assigned a value):

It always evaluate into a single value.

17

x

x + 17

Types of expression:

1.Arithmetic Expression:-

Arithmetic expressions involve numbers and arithmetic operators. It can belong to one of these types:

a) Pure Expressions:-

Pure arithmetic expressions are those that have all operators of same numeric type.                    For Example:

x + y , c/y      ( integer expressions if x, y ,c are all integer type)

p + q , t/u      (real expressions if p, q, t and u all float type)

b) Mixed Expression:-

Mixed arithmetic expressions are that have operands of different numeric types.

For Example:

If a,b are integer variable and c, d are floating point and e, f are complex type than

i) 8+d                                  ii) c/a +a                    iii) e*a +f

2. Relational Expression:-

An expression having literals and /or variables of any valid type and relational operators is a relational expression.

For Example:

x > y ,        y>=z,        z==a

3. Logical Expression:-

An expression having literals and /or variables of any valid type and logical operators is a logical expression.

For Example:

x or y ,        y and z,        not z or not a

4. String Expression:-

Python also provides two string operators + and *, when combined with string operands and integer, form string expression.

With operator +, the concatenation operator, the operands should be of string type only.

With operator *, the replication operator, the operands should be one string type and one integer.

For Example:

“now” + “then”        =>    nowthen (concatenation of “now” and “then”)

“now” * 2                  =>    nownow (replication of now two times)

 

Program 1: Write a python program to input two numbers from user and calculate their
sum. The Python program to add two numbers and display their sum as output.
How to add two numbers in Python programming.

For Example

Input

Input first number: 20

Input second number: 10

Output

Sum = 30

For Solution Click on        Solution of Program 1

Program 2: Write a python program to input two numbers and perform all arithmetic operations. How to perform all arithmetic operation between two numbers in python programming. A Python program to find sum, difference, product, quotient and modulus of two given numbers.

For Example
Input
First number: 10
Second number: 5
Output
Sum = 15
Difference = 5
Product = 50
Quotient = 2
Modulus = 0

For Solution Click on  Solution of Program 2

Program 4. Write a python program to input temperature in Celsius (centigrade) and convert to Fahrenheit. How to convert temperature from degree centigrade to degree Fahrenheit in python programming. Python program for temperature conversion.

For Solution Click on  Solution of Program 4

Program 5. Write a python program to input radius of a circle from user and find diameter, circumference and area of the circle. How to calculate diameter, circumference and area of a circle whose radius is given by user in program programming. Logic to find diameter, circumference and area of a circle in python.

For Solution Click on  Solution of Program 5

Program 6. Write a python program to input number of days from user and convert it to years, weeks and days. How to convert days to years, weeks in python programming. Logic to convert days to years, weeks and days in python program.

For Solution Click on  Solution of Program 6

Program 7. Write a python program to input temperature in degree Fahrenheit and convert it to degree centigrade. How to convert temperature from Fahrenheit to Celsius in python programming. Python program for temperature conversion. Logic to convert temperature from Fahrenheit to Celsius in python program.

For Solution Click on  Solution of Program 7

Program 8. Write a python program to input length and width of a rectangle and calculate perimeter and area of the rectangle. How to find perimeter and area of a rectangle in python programming. Logic to find the perimeter and area of a rectangle if length and width are given in python programming.

For Solution Click on  Solution of Program 8

Program 9. Write a python program to input principle (amount), time and rate (P, T, R) from user and find Simple Interest. How to calculate simple interest in python programming.

For Solution Click on  Solution of Program 9

Program 10. Write a python program to input marks of five subjects of a student and calculate total, average and percentage of all subjects. How to calculate total, average and percentage of marks of five subjects in python programming.

For Solution Click on  Solution of Program 10

Program 11. Write a python Program to input two angles of a triangle and find third angle of the triangle. How to find all angles of a triangle if two angles are given by user using python programming. Python program to calculate the third angle of a triangle if two angles are given.

For Solution Click on  Solution of Program 11

 

Python Fundamentals

Python Character Set: Character set is asset of valid characters that a language can recognize.  A character can represents any letter, digit, or any other sign. Following are some of the python character set.

LETTERS                               A to Z and a to z

DIGITS                                   0 -9

SPECIAL SYMBOLS            space ,+ -* ^ \ [] {} = != < > . ‗ ‗ ; : & #, under score(_)

WHITE SPACE                     Blank space , horizontal tab ( – > ), carriage return , Newline, Form feed.

OTHER CHARACTERS      Python can process all ASCII and Unicode characters as part of data or  literals.

Tokens: The smallest individual unit in a program is known as token or lexical unit. A token can be any keyword, Identifier, Literals, Punctuators, and Operators.

1) Keywords: They are the words used by Python interpreter to recognize the structure of program. As these words have specific meaning for interpreter, they cannot be used for any other purpose.

A partial list of keywords in Python 3.6.x is

and del from not
while as elif global
or with assert else
if pass yield break
except import print class
exec in raise continue
finally is return def
for lambda try

2) Identifiers:  Identifiers are names given to identify something. Identifiers are fundamental building blocks of a program and are used as general terminology for the names given to different part of the program that is variables, objects, classes, functions, lists, dictionaries etc.

There are some rules you have to follow for naming identifiers:

  • The first character of the identifier must be a letter of the alphabet (uppercase ASCII or lowercase ASCII or Unicode character) or an underscore (‘_’).
  • The rest of the identifier name can consist of letters (uppercase ASCII or lowercase ASCII or Unicode character), underscores (‘_’) or digits (0-9).
  • Identifier names are case-sensitive.

For example, myname and myName are not the same.

Note the lowercase n in the former and the uppercase N in the latter.

  • Examples of valid identifier names are i, __my_name, name_23. Examples of ‘’invalid” identifier names are 2 things, this is spaced out, my-name, >a1b2_c3 and “this_is_in_quotes”.
  • An identifier must not be a keyword of Python.

3) Literals / Values: The data items which never change their value throughout the program run. There are several kind of literals:

  1. String Literals
  2. Numeric Literals
  3. Boolean Literals
  4. Special Literal None
  5. Literal Collections

1. String Literals: It is a sequence of letters surrounded by either by single or double or triple quotes. g  “abc” , ‘a’ , “raman”.

2. Numeric Literals: The numeric literals in Python can belong to any of the following different numerical types:

  • integer literals (both int and long): Integer constant (literal) must have at least one digit and must not contain any decimal point. It may contain either (+) or (-) sign. A number with no sign is assumed to be positive. Commas cannot appear in an integer constant.

For example: 12344, 41, +68, -23

 

  • Floating Point Literals: A real constant (literal) in fractional form must have at least one digit before a decimal point and at least one digit after the decimal point. It may also have either + or – sign preceding it. A real constant with no sign is assumed to be positive.

For example: 2.0 , 18.6 , -23.9 , +89.66

  • A real literal may be represented in Exponent form having Matissa and exponent with base 10 (E). Mantissa may be a proper real numbers while exponent must be integer.

The following are valid real in exponent form-

152E05, 1.52E07, 0.152E08, -0.12E-3, 1.5E+8

The following are invalid real exponent numbers-

172.E5, 1.7E, 0.17E2.3, 17,22E05, .25E-7

  • Complex number:

Complex number in python is made up of two floating point values, one each for              real and imaginary part. For accessing different parts of variable (object) x; we                will use x.real and x.image. Imaginary part of the number is represented by ‘j’                  instead of ‘i’, so 1+0j denotes zero imaginary part.

        For example

>>> x = 1+0j

>>> print x.real,x.imag

1.0 0.0

       Example

>>> y = 9-5j

>>> print y.real, y.imag

9.0 -5.0

3. Boolean Literals: A Boolean literals in Python is used to represent one of the two Boolean values that is True or A Boolean literal can either have value as True or as false.

A. Special Literal None:

  • None is a special type in Python that represents nothingness. For example, it is used to indicate that a variable has no value if it has a value of None.
  • The None literal is used to indicate something that has not yet been created. It is also used to indicate the end of lists.

          Python supports literal collections also such as tuples and list etc. these will                be discussed in next blog.

4. Punctuators:  The following nine ASCII characters are the separators:

( ) { } [ ] ; , . \ # @ : = ‘ “

5. Operators: Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

Unary Operator:
Description Symbol Example 1 Example 2

unary plus

+

If x=10, then +x means 10 If x=-10, then +x means -10

unary minus

If x=10, then -x means -10 If x=-10, then +x means 10
Arithmetic Operator:

Addition

+

>>>10+5

15

>>>’Hello’+’Amjad’

HelloAmjad

Subtraction

>>>10-5

5

>>>30-70

-40

Multiplication

*

>>>10*5

50

>>>’Hello’*3

HelleoHelloHello

Division

/

>>>17/5

3

>>>17/5.0

3.4

>>>17.0/5

3.4

>>28/3

9

>>28/7.0

4.0

Remainder / Modulo

%

>>>16%5

1

>>>13%5

3

Exponent

**

>>>2**3

8

>>>16**0.5

4

Floor division (integer division)

//

>>>7.0//2

3.0

>>>5//2

2

 

Bitwise Operator:

We assume the operation1is X and Operation2 is Y for better understanding of these operators

Operation Operator Use Description

Bitwise AND

&

X & Y The AND operator compare two bits and generate a result of 1 if both bits are 1; otherwise, it return 0.

Bitwise exclusive OR (XOR)

^

X^Y The EXCLUSIVE – OR operator compare two bits and returns 1 if either of the bits are 1 and gives 0 if both bits are 0 and 1.

Bitwise OR

|

X | Y The OR operator compare two bits and generate a result of 1 if both bits are complementary; otherwise, it return 0.

Bitwise Complement

~

~X The COMPLEMENT operator is used to invert all of the bits of the operands.

Identity operator:

Is the identity same?

is

X ix Y Return True if both its operands are pointing to same object (i.e, both referring to same memory location), returns false otherwise

Is the identity not same?

is not

X is not Y Return True if both its operands are pointing to different object (i.e, both referring to different memory location), returns false otherwise

Relational Operator:

Less than

<

>>>5<7

True

>>>7<5

False

>>> 5<7<10

True

>>> 5<7 and 7<10

True

>>>’Hello’ < ‘Amjad’

False

>>>’Amjad’ < ‘Hello’

True

Greater than

<

>>>7>5

True

>>>10<10

False

>>>’Hello’ > ‘Amjad’

True

>>>’Amjad’ > ‘Hello’

False

Less than or equal to

>=

>>> 2<=6

True

>>> 6<=4

False

 <<< ‘Hello’ <=’Amjad’

False

>>>’Amjad’<=’Hello’

True

Greater than or equal to

>=

>>> 2>=6

False

>>> 6>=4

True

 <<< ‘Hello’ >=’Amjad’

True

>>>’Amjad’>=’Hello’

False

Equal to

==

>>> 5==5

True

>>>10==11

False

>>>’Hello’==’Hello

True

>>>’Hello’==’Good Bye’

False

Not equal to

!= , < >

>>>10!=11

True

>>>10!=10

False

>>>’Hi!=’HI’

True

>>>’HI’!=’HI’

False

 

Assignment Operators: and Shorthand Assignment Operators

We assume the value of variable p as 10 for better understanding of these operators

=

Assignment It is use to assign the value to the variable a=6 A will become 6
/=

Assign quotient

Divided and assign back the result to left operand >>> p/=2 p will become 5
+=

Assign sum

Added and assign back the result to left operand >>> p+=2 p will become 12

*=

Assign product multiplied and assign back the result to left operand >>> p*=2 p will become 20
%= Assign remainder Taken modulus using two operands and assign the result to left operand >>> p%=2 p will become 0

-=

Assign difference subtracted and assign back the result to left operand >>> p-=2 p will become 8

**=

Assign Exponent Performed exponential(power) calculation on operators and assign value to the left operand >>> p**=2 p will become 100

//=

Assign floor division Performed floor division on operators and assign back the result to left operand >>> p//=2 p will become 5

Logical Operators:

and Logical AND X and Y If  both the operand is true, then the condition becomes True
or orLogical OR X or Y If any one of the operand is true, then the condition becomes True
not Logical NOT not X Reverses the state of the operand/ condition.
Membership Operators:
in Whether variable in sequence The in operator tests if a given value is contained in a sequence or not and return True or False Accordingly >>>3 in [1,2,3,4]

True

not in Whether variable not in sequence The not in operator tests if a given value is contained in a sequence or not and return True or False Accordingly >>>6 not in [1,2,3,4,5]

True (Because the value 6 is not in the sequence.)

>>>4 not in [1,2,3,4,5,6]

False

Structure of the Python’s Program

structureofprogram

So the above sample program contains various components:

  1. Expressions
  2. Statements
  3. Comments
  4. Function
  5. Blocks and indentation

1. Expressions:

An expression is any legal combination of symbols that represents a value.

For example

  1. c=a+b
  2. s>0

2. Statement:

A statement is a programming instruction that does something.

For example

  1. print (“The sum is:”,c)
  2. if s>0:

3.Comments:

Comments are any text to the right of the # symbol and are mainly useful as notes for the reader of the program.

For example:

print(‘Hello World’) # Note that print is a function

or:

# Note that print is a function

print(‘Hello World’)

Use as many useful comments as you can in your program to:

  • explain assumptions
  • explain important decisions
  • explain important details
  • explain problems you’re trying to solve
  • explain problems you’re trying to overcome in your program, etc.

 Code tells you how, comments should tell you why.

Two types of comments:

Single line Comment: # marks start of single line comment that must not be inside a string literal. All characters after the #

and up to the physical line end are part of the comment, and the Python interpreter ignores them.   Example

def getline():

return sys.stdin.readline()    # Get one line and return it

Multi – Line Comment:     Comments can be break up into multiple lines by inserting a multiline string with ”’as the delimiter one each end.

Example

def getline():

return sys.stdin.readline()            ”’this function

gets one line

and returns it’’’

4. Function:

A function is a group of statements that exist within a program for the purpose of performing a specific task and it can be reused (executed again) by specifying its name in the program, where needed.

How to define and Call a function in python:

A user-defined Python function is created or defined by the def statement followed by the function name and parentheses (()) as shown in the syntax given below:

Syntax:

def function_Name (comma_separated_list_of_parameters):

statements

NOTE: Statement below def begin with four spaces. This is called indentation. It is a requirement of Python that the code following a colon must be indented.

For Example

def sum ():                          #function definition of sum()

a=int (input ())

b=int (input ())

c=a+b

print(“The sum is “,c)

return c

print (“Enter any valid two integers”)

s=sum()            # Calling above defined function sum()

5. Block and Indentation:

A group of statements which are part of another statement or a function are called block or code – block or suite in Python.

Consider the following Example:

if n1<n2:

Tmp =n1

n1=n2

n2=Tmp

print “I Understand Block”

One of the most remarkable difference between Python and other most common programming  languages like C, C++, C#, Java will be encounter programmer’s is that in Python indentation is  very  important and there are no braces to indicate blocks of code for class and function definitions  or  flow control. There are no end/begin delimiters like {}.

Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.

Python uses indentation to create blocks of code. Statements at same indentation level are part of same block / suite.

Statements requiring suite / code bloc have a colon (:) at their end.

You cannot unnecessarily indent a statement; Python will raise error for that.

Another Example:

Picture1

 Variables:

Variables are exactly what the name implies – their value can vary, i.e., you can store anything using a variable. Variables are just parts of your computer’s memory where you store some information.

Named labels, whose values can be manipulated during program run, are called Variables.

Creating a Variable:

Python variables are created by assigning value of desired type to them, example: to create a numeric variable, assign a numeric value to variable_name; to create a sting variable, assign a string value to variable_name and so on.

Example:

X=10.8                                    # variable created of numeric (floating point) type

Y = 90                                     # variable created of numeric (integer) type

Name = “My Name”           # variable created of string type

Multiple Assignments:

  1. Assigning same value to multiple variables:

x = y = z = 100

It will assign value 100 to all three variables x, y and z.

  1. Assigning multiple value to multiple variables

p, q, r = 10, 20, 30

It will assign the value order wise that is value 10 assign to variable p, value 20 assign to variable q and value 30 assign to variable r.

IMPORTANT NOTE:

A variable is defined only when you assign some value to it. Using an undefined variable in an expression / statement cause error.

Example:
print (a)
              # Error name ‘a’ not defined

a = 20                                   

 print (a)

correct code:

a=10

print (a)

a = 20

print a)

While writing Python statements, keep the following points in mind:

  1. Write one python statement per line (Physical Line). Although it is possible to write two statements in a line separated by semicolon.
  2. Comment starts with “#” outside a quoted string and ends at the end of a line. Comments are not part of statement. They may occur on the line by themselves or at the end of the statement. They are not executed by interpreter.
  3. For a long statement, spanning multiple physical lines, we can use ‘/’ at the end of physical line to logically join it with next physical line. Use of the ‘/’ for joining lines is not required with expression consists of ( ), [ ], { }
  4. When entering statement(s) in interactive mode, an extra blank line is treated as the end of the indented block.
  5. Indentation is used to represent the embedded statement(s) in a compound/ Grouped statement. All statement(s) of a compound statement must be indented by a consistent no. of spaces (usually 4)
  6. White space in the beginning of line is part of indentation, elsewhere it is not significant.

Input and Output

A Program needs to interact with end user to accomplish the desired task, this is done using Input-Output facility. Input means the data entered by the user (end user) of the program. While writing algorithm(s), getting input from user was represented by Take/Input. In python, we have raw-input() and input ( ) function available for Input.

                        Picture1

If prompt is present, it is displayed on the monitor after which user can provide the data from keyboard. The function takes exactly what is typed from keyboard, convert it to string and then return it to the variable on LHS of “=”.

Example (in interactive mode)

>>>x=raw_input (“Enter your name: “)

Enter your name: ABC

x is a variable which will get the string (ABC), typed by user during the execution of program. Typing of data for the raw_input function is terminated by „enter‟ key. We can use raw_input() to enter numeric data also. In that case we typecast, i.e., change the datatype using function, the string data accepted from user to appropriate Numeric type.

Example

y=int(raw_input(“enter your roll no”))

enter your roll no. 5

will convert the accepted string i.e. 5 to integer before assigning it to ‘y’.

input()

Syntax for input() is:

Input ([prompt])

            Optional

If prompt is present, it is displayed on monitor, after which the user can provide data from keyboard. Input takes whatever is typed from the keyboard and evaluates it. As the input provided is evaluated, it expects valid python expression. If the input provided is not correct then either syntax error or exception is raised by python.

Example

x= input (“enter data:”)

Enter data: 2+1/2.0

Will supply 2.5 to x input ( ), is not so popular with python programmers as:

  1. i) Exceptions are raised for non-well formed expressions.
  2. ii) Sometimes well formed expression can wreak havoc.

Output is what program produces. In algorithm, it was represented by print. For output in Python we use print. We have already seen its usage in previous examples. Let’s learn more about it.

Important Link 

Python: More on input( ) function

Print Statement

Syntax:

print (expression/constant/variable)

Print evaluates the expression before printing it on the monitor. Print statement outputs an entire (complete) line and then goes to next line for subsequent output (s). To print more than one item on a single line, comma (,) may be used.

Example

>>> print (“Hello”)

Hello

>>> print (5.5)

5.5

>>> print (4+6)

10

Try this on the computer and evaluate the output generated

>>>print (3.14159* 7**2)

>>>print (“I”, “am” + “class XI”, “student”)

>>>print (“I’m”)

>>>print (“class XI student”)

>>print( “I’m “, 16, “years old”)

Important Link

Python: More on Print( ) function

Difference between input ( ) and raw_input ( ) method

input() raw_input()
Converts the user input to the right   matching python

type (int, str, list, tuple, dict etc.,)

For instance in the statement below:

a = input(‘Enter a value: ‘)

print type(a)

if user entered 1 then it is int

if user entered ‘Python’ then it is str

if user entered [1,2,3] then it is dict

Converts the user input always to string.

For instance in the statement below

a = raw_input(‘Enter a value: ‘)

print type(a)

Regardless of value entered by the type is always

string

Use when you write program quickly for yourself or for expert users since  you would not  need to any type conversion. Use when you write program for non expert users since you can handle exceptions  when converting from string to your  expected type.
Removed in Python 3 Renamed as input in Python 3
>>> n = input(“Please enter a value: “)

Please enter a value: 23

>>> n

23         # value returned as int

>>> n = raw_input(“Please enter a value: “)

Please enter a value: 23

>>> n

’23’       # value returned as str

Getting Started with Python

The official introduction to Python is:
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

In order to tell the computer ‘what you want to do’, we write a program in a language which computer can understand. Though there are many different programming languages such as BASIC, Pascal, C, C++, Java, Haskell, Ruby, Python, etc. but we will study Python in this course.

Story behind the name
Guido van Rossum, the creator of the Python language, named the language after the BBC show “Monty Python’s Flying Circus”. He doesn’t particularly like snakes that kill animals for food by winding their long bodies around them and crushing them.

Features of Python

i) Simple
Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English, although very strict English! This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the language itself.
ii) Easy to Learn
As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax, as already mentioned.
iii) Free and Open Source
Python is an example of a FLOSS (Free/Libré and Open Source Software). In simple terms, you can freely distribute copies of this software, read its source code, make changes to it, and use pieces of it in new free programs.
iv) High-level Language
When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc.
v) Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features.
vi) Object Oriented
Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.
vii) Extensible
If you need a critical piece of code to run very fast or want to have some piece of algorithm not to be open, you can code that part of your program in C or C++ and then use it from your Python program.
viii) Embeddable: You can embed Python within your C/C++ programs to give ‘scripting’ capabilities for your program’s users.
ix)Large Standard Library: Python comes with a large standard library that supports many common programming tasks such as connecting to web servers, searching text with regular expressions, reading and modifying files.
x) Garbage Collection: Automatic memory management system freed Python programmer from bothering about memory management like allocating and de-allocating memory space.
xi) Exception Handling: Python Exceptions handling system provide a way to handle the exceptional circumstances (like runtime errors) in our program.

Installation
Installation on Windows
Visit http://www.python.org/download/ and download the latest version. The installation is just like any other Windows-based software.
Caution When you are given the option of unchecking any “optional” components, don’t uncheck any.

Working in Python:
Python shell can be used in two ways.
i) Interactive mode
ii) Script mode.

i) Interactive mode: Interactive Mode, as the name suggests, allows us to interact with OS. For working in the interactive mode, we will start Python on our computer.

fig 1

Interactive mode is a command line environment called as Shell of Python which gives immediate result for each statement fed from the prompt. The >>> (prompt) is Python’s way of telling you that you are in interactive mode and here we can enter our one line statement.

Working in Script Mode:
In script mode, we type Python program in a file and then use the interpreter to execute the content from the file. Working in interactive mode is convenient for beginners and for testing small pieces of code, as we can test them immediately. But for coding more than few lines, we should always save our code so that we may modify and reuse the code.

To create and run a Python script, we will use following steps in IDLE, if the script mode is not made available by default with IDLE environment.

fig 2

After starting IDLE from start menu, IDLE open its window

fig 1

1. File>Open OR File>New Window (for creating a new script file)

fig 3

2. Write the Python code as function i.e. script

fig 4

3. Save it (^S)

4. Execute it in interactive mode- by using RUN option (^F5)

fig 5