top

Search

Python Tutorial

Use of Python interpreter’s interactive mode and script mode has been explained in earlier chapter of this tutorial series (Python Getting started). So far we learned about Python data types mainly using interactive mode. From here on scripted mode will be used most of the time.Interactive mode is a good way to try out the language syntax get comfortable with Python. However, interactive mode is not suitable when it comes to automate certain process. Instead of writing and executing one statement at a time from Python prompt, it is better to store all statements in a text file with .py extension. This script is normally called as Python program. Instructions stored in a text file and executed at once by interpreter from command line as follows:First enter following code and save as test.py and is called Python script.price=50 quantity=5 amount=price*quantity print ("price : {} quantity : {} amount : {}".format(price, quantity, amount))Then execute it from command line. Shown below are windows and Linux command line examples to execute test.pyC:\python36>python test.py price : 50 quantity : 5 amount : 250 $python test.py price : 50 quantity : 5 amount : 250What is a program?In computer science, program is a sequence of instructions submitted to computer processor. When the instructions are executed in the defined sequence, processor will accomplish a certain task, or solve given problem.What is programming?To make computer processor solve a problem, its algorithm should first be planned and then it is translated into a sequence of instructions which when executed by computer processor, the desired task will be accomplished.Python provides a predefined set of keywords using which the algorithm is coded. This code is what we call a program. Python’s interpreter software translates the code in processor readable format so that it can be executed to perform desired task.Writing a script of statements provides following advantagesIt is easily possible to add/insert/update/delete statements in the script with help of any Python aware IDE.Code in one script can be used in another by importing it.Scripts enable automating and scheduling certain taskPython script can be converted in self executable. In Linux, use chmod command to do so. For Windows py2exe utility converts script with .py extension to executable.An expression that evaluates to Boolean values either True or False if it contains comparison operators. (explained in previous chapter Python Operators). Python keywords And, Or and Not combine two Boolean expressions. Assuming x=True and y=False, their result is as shown in following table:AndTrue if both are truex and y returns TrueOrTrue if at least one is truex or y returns trueNotTrue only if falsenot x returns FalseComparison operators along with above keywords are useful in controlling flow of program.By default, statements in script are executed sequentially from first to last. If the processing logic requires, sequential flow can be altered in two ways.Conditional execution: block of one or more statements will be executed if a certain expression is true.Repetitive execution: Block of one or more statements is repetitively executed till a certain expression remains true.In this chapter we shall discuss decision control statements in Python.A simple sequential process follows input-process-output path. A program involving one or more inputs to compute an unknown result is an example of such a sequential process. However, real life computer applications require that computer takes appropriate decisions depending on varying situations. Following flowchart describes how block of one or more statements is executed conditionally.Conditional statements (if keyword)Python uses if keyword to implement decision control. Python’s syntax for executing block conditionally is as below:if expr==True:    stmt1 stmt2Any Boolean expression evaluating to True or False appears after if keyword. Use : symbol and press Enter after the expression to start a block with increased indent. One or more statements written with same level of indent will be executed if the Boolean expression evaluates to True. To end the block, press backspace to de-dent. Subsequent statements after the block will be executed if expression is false or after the block if expression is true.Let us write a Python program that calculates amount payable from price and quantity input by user and applies 10% discount if the amount exceeds 1000, and no discount otherwise.Discounts needs to applied only if amount is greater than 1000, hence the process is put in a block with increased indent following the conditional expression.The print() statement is written after conditional block is over, hence it will be executed if expression is false (i.e. amount not greater than 1000) as well as after applying discount if expression is true (i.e. amount is greater than 1000)price=int(input("enter price")) qty=int(input("enter quantity")) amt=price*qty if amt>1000:    print ("10% discount applicable")    discount=amt*10/100    amt=amt-discount print ("amount payable:",amt)Save above script as discount.py and run it from command line as:python discount.pyTwo scenarios of running the code are shown below. In first, inputs for price and quantity are such that amount is greater than 1000. Payable amount after applying discount will be displayed.enter price100 enter quantity20 10% discount applicable amount payable: 1800.0In second case, inputs are such that the expression doesn’t become true. Hence, print statement will display payable amount which will not have discount.enter price10 enter quantity20 amount payable: 200else keywordAlong with if statement, else clause can also be optionally used to define alternate block of statements to be executed if the Boolean expression (in if statement) is not true. Following flowchart shows how else block is used.This is how else block is used in Python:if expr==True:     stmt1 else:     stmt2 stmt3As earlier, indented block started by : symbol after Boolean expression in front of if keyword gets executed when it is true. We have another block that should be executed when the expression is false. First, complete the if block by backspace and write else, put : symbol in front of it to start another block and put required statements in it. De-dent the else block and enter statements that should be executed irrespective of the Boolean expression being true or false.Let us extend earlier code for applying discount and provide for computation of 5% discount if amount is not greater than 1000. To do that, use else and : after first block. New indented block will start. Enter two statements to apply 5% discount and subtracting it from amount in it. Statement to print payable amount should be executed in both cases. So, de-dent second block and enter it.price=int(input("enter price")) qty=int(input("enter quantity")) amt=price*qty if amt>1000:    print ("10% discount applicable")    discount=amt*10/100    amt=amt-discount else:    print ("5% discount applicable")    discount=amt*5/100    amt=amt-discount print ("amount payable:",amt)Let us run this code to test first possibility, price and quantity having inputs such that amount greater than 1000. We should see 10% discount being appliedenter price200 enter quantity10 10% discount applicable amount payable: 1800.0In second run, inputs are such that amount is not greater than 1000. We see 5% discount deducted from amount.enter price150 enter quantity6 5% discount applicable amount payable: 855.0elif keywordLet us modify the discount example further. Discounts applicable are 10%, 5%, 2% and 1% for amount exceeding 10000, between 5,000 to 10,000, between 2,000 and 5000 and between 1000 and 2000  respectively. No discount is applicable for amount less than 2000.Following code implements above graded computation of discount, setting aside one possibility at a time by successive if statements.price=int(input("enter price")) qty=int(input("enter quantity")) amt=price*qty if amt>10000:    print ("10% discount applicable")    discount=amt*10/100    amt=amt-discount else:    if amt>5000:        print ("5% discount applicable")        discount=amt*5/100        amt=amt-discount    else:        if amt>2000:            print ("2% discount applicable")            discount=amt*2/100            amt=amt-discount        else:            if amt>1000:                print ("1% discount applicable")                discount=amt/100                amt=amt-discount            else:                print ("no discount applicable") print ("amount payable:",amt)If above code is executed to test all discount scenarios, following output will be displayedenter price1000 enter quantity11 10% discount applicable amount payable: 9900.0 ======================== enter price1000 enter quantity6 5% discount applicable amount payable: 5700.0 ======================== enter price1000 enter quantity4 2% discount applicable amount payable: 3920.0 ======================== enter price500 enter quantity3 1% discount applicable amount payable: 1485.0 ======================== enter price250 enter quantity3 no discount applicable amount payable: 750In above program indent level of each block increases because if block starts after empty else. More elegant way to avoid these indentations is to combine empty else and subsequent if by elif keyword.General syntax of if – elif – else usage is as below:if expr1==True:    #Block To Be Executed If expr1 is True elif expr2==True:     #Block To Be Executed If expr1 is false and expr2 is true elif expr3==True:     #Block To Be Executed If expr2 is false and expr3 is true elif expr4==True:     #Block To Be Executed If expr3 is false and expr4 is true else:    #Block To Be Executed If all preceding expressions falseIn this code, one if block, followed by one or more elif blocks and one else block at the end will appear. Boolean expression in front of elif is evaluated if previous expression fails. Last else block is run only when all previous expressions turn out to be not true. Importantly all blocks have same level of indentation.price=int(input("enter price")) qty=int(input("enter quantity")) amt=price*qty if amt>10000:    print ("10% discount applicable")    discount=amt*10/100    amt=amt-discount elif amt>5000:    print ("5% discount applicable")    discount=amt*5/100    amt=amt-discount elif amt>2000:    print ("2% discount applicable")    discount=amt*2/100    amt=amt-discount elif amt>1000:    print ("1% discount applicable")    discount=amt/100    amt=amt-discount else:    print ("no discount applicable") print ("amount payable:",amt)Identical output will be shown when above code is run to test different discount scenarios.
Rated 5/5 based on 11 customer reviews
logo

Python Tutorial

Use of Python interpreter’s interactive mode and script mode has been explained in earlier chapter of this tutorial series (Python Getting started). So far we learned about Python data types mainly using interactive mode. From here on scripted mode will be used most of the time.

Interactive mode is a good way to try out the language syntax get comfortable with Python. However, interactive mode is not suitable when it comes to automate certain process. Instead of writing and executing one statement at a time from Python prompt, it is better to store all statements in a text file with .py extension. This script is normally called as Python program. Instructions stored in a text file and executed at once by interpreter from command line as follows:

First enter following code and save as test.py and is called Python script.

price=50
quantity=5
amount=price*quantity
print ("price : {} quantity : {} amount : {}".format(price, quantity, amount))

Then execute it from command line. Shown below are windows and Linux command line examples to execute test.py

C:\python36>python test.py
price : 50 quantity : 5 amount : 250
$python test.py
price : 50 quantity : 5 amount : 250

What is a program?

In computer science, program is a sequence of instructions submitted to computer processor. When the instructions are executed in the defined sequence, processor will accomplish a certain task, or solve given problem.

What is programming?

To make computer processor solve a problem, its algorithm should first be planned and then it is translated into a sequence of instructions which when executed by computer processor, the desired task will be accomplished.

Python provides a predefined set of keywords using which the algorithm is coded. This code is what we call a program. Python’s interpreter software translates the code in processor readable format so that it can be executed to perform desired task.

Writing a script of statements provides following advantages

  • It is easily possible to add/insert/update/delete statements in the script with help of any Python aware IDE.
  • Code in one script can be used in another by importing it.
  • Scripts enable automating and scheduling certain task

Python script can be converted in self executable. In Linux, use chmod command to do so. For Windows py2exe utility converts script with .py extension to executable.

An expression that evaluates to Boolean values either True or False if it contains comparison operators. (explained in previous chapter Python Operators). Python keywords And, Or and Not combine two Boolean expressions. Assuming x=True and y=False, their result is as shown in following table:

AndTrue if both are truex and y returns True
OrTrue if at least one is truex or y returns true
NotTrue only if falsenot x returns False

Comparison operators along with above keywords are useful in controlling flow of program.

By default, statements in script are executed sequentially from first to last. If the processing logic requires, sequential flow can be altered in two ways.

Conditional execution: block of one or more statements will be executed if a certain expression is true.

Repetitive execution: Block of one or more statements is repetitively executed till a certain expression remains true.

In this chapter we shall discuss decision control statements in Python.

A simple sequential process follows input-process-output path. A program involving one or more inputs to compute an unknown result is an example of such a sequential process. However, real life computer applications require that computer takes appropriate decisions depending on varying situations. Following flowchart describes how block of one or more statements is executed conditionally.

Conditional statements (if keyword)

Python uses if keyword to implement decision control. Python’s syntax for executing block conditionally is as below:

if expr==True:
   stmt1
stmt2

Any Boolean expression evaluating to True or False appears after if keyword. Use : symbol and press Enter after the expression to start a block with increased indent. One or more statements written with same level of indent will be executed if the Boolean expression evaluates to True. To end the block, press backspace to de-dent. Subsequent statements after the block will be executed if expression is false or after the block if expression is true.

Let us write a Python program that calculates amount payable from price and quantity input by user and applies 10% discount if the amount exceeds 1000, and no discount otherwise.

Discounts needs to applied only if amount is greater than 1000, hence the process is put in a block with increased indent following the conditional expression.

The print() statement is written after conditional block is over, hence it will be executed if expression is false (i.e. amount not greater than 1000) as well as after applying discount if expression is true (i.e. amount is greater than 1000)

price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>1000:
   print ("10% discount applicable")
   discount=amt*10/100
   amt=amt-discount
print ("amount payable:",amt)

Save above script as discount.py and run it from command line as:

python discount.py

Two scenarios of running the code are shown below. In first, inputs for price and quantity are such that amount is greater than 1000. Payable amount after applying discount will be displayed.

enter price100
enter quantity20
10% discount applicable
amount payable: 1800.0

In second case, inputs are such that the expression doesn’t become true. Hence, print statement will display payable amount which will not have discount.

enter price10
enter quantity20
amount payable: 200

else keyword

Along with if statement, else clause can also be optionally used to define alternate block of statements to be executed if the Boolean expression (in if statement) is not true. Following flowchart shows how else block is used.

This is how else block is used in Python:

if expr==True:
    stmt1
else:
    stmt2
stmt3

As earlier, indented block started by : symbol after Boolean expression in front of if keyword gets executed when it is true. We have another block that should be executed when the expression is false. First, complete the if block by backspace and write else, put : symbol in front of it to start another block and put required statements in it. De-dent the else block and enter statements that should be executed irrespective of the Boolean expression being true or false.

Let us extend earlier code for applying discount and provide for computation of 5% discount if amount is not greater than 1000. To do that, use else and : after first block. New indented block will start. Enter two statements to apply 5% discount and subtracting it from amount in it. Statement to print payable amount should be executed in both cases. So, de-dent second block and enter it.

price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>1000:
   print ("10% discount applicable")
   discount=amt*10/100
   amt=amt-discount
else:
   print ("5% discount applicable")
   discount=amt*5/100
   amt=amt-discount
print ("amount payable:",amt)

Let us run this code to test first possibility, price and quantity having inputs such that amount greater than 1000. We should see 10% discount being applied

enter price200
enter quantity10
10% discount applicable
amount payable: 1800.0

In second run, inputs are such that amount is not greater than 1000. We see 5% discount deducted from amount.

enter price150
enter quantity6
5% discount applicable
amount payable: 855.0

elif keyword

Let us modify the discount example further. Discounts applicable are 10%, 5%, 2% and 1% for amount exceeding 10000, between 5,000 to 10,000, between 2,000 and 5000 and between 1000 and 2000  respectively. No discount is applicable for amount less than 2000.

Following code implements above graded computation of discount, setting aside one possibility at a time by successive if statements.

price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>10000:
   print ("10% discount applicable")
   discount=amt*10/100
   amt=amt-discount
else:
   if amt>5000:
       print ("5% discount applicable")
       discount=amt*5/100
       amt=amt-discount
   else:
       if amt>2000:
           print ("2% discount applicable")
           discount=amt*2/100
           amt=amt-discount
       else:
           if amt>1000:
               print ("1% discount applicable")
               discount=amt/100
               amt=amt-discount
           else:
               print ("no discount applicable")
print ("amount payable:",amt)

If above code is executed to test all discount scenarios, following output will be displayed

enter price1000
enter quantity11
10% discount applicable
amount payable: 9900.0
========================
enter price1000
enter quantity6
5% discount applicable
amount payable: 5700.0
========================
enter price1000
enter quantity4
2% discount applicable
amount payable: 3920.0
========================
enter price500
enter quantity3
1% discount applicable
amount payable: 1485.0
========================
enter price250
enter quantity3
no discount applicable
amount payable: 750

In above program indent level of each block increases because if block starts after empty else. More elegant way to avoid these indentations is to combine empty else and subsequent if by elif keyword.

General syntax of if – elif – else usage is as below:

if expr1==True:
   #Block To Be Executed If expr1 is True
elif expr2==True:
    #Block To Be Executed If expr1 is false and expr2 is true
elif expr3==True:
    #Block To Be Executed If expr2 is false and expr3 is true
elif expr4==True:
    #Block To Be Executed If expr3 is false and expr4 is true
else:
   #Block To Be Executed If all preceding expressions false

In this code, one if block, followed by one or more elif blocks and one else block at the end will appear. Boolean expression in front of elif is evaluated if previous expression fails. Last else block is run only when all previous expressions turn out to be not true. Importantly all blocks have same level of indentation.

price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>10000:
   print ("10% discount applicable")
   discount=amt*10/100
   amt=amt-discount
elif amt>5000:
   print ("5% discount applicable")
   discount=amt*5/100
   amt=amt-discount
elif amt>2000:
   print ("2% discount applicable")
   discount=amt*2/100
   amt=amt-discount
elif amt>1000:
   print ("1% discount applicable")
   discount=amt/100
   amt=amt-discount
else:
   print ("no discount applicable")
print ("amount payable:",amt)

Identical output will be shown when above code is run to test different discount scenarios.

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

C# Tutorial

By KnowledgeHut

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
Rated 5/5 based on 12 customer reviews
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More