You are on page 1of 29

ARMY PUBLIC SCHOOL NO 2, JAK RIF RC JABALPUR

PYTHON INTRODUCTION

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is


designed to be highly readable. It uses English keywords frequently whereas the other languages use
punctuations. It has fewer syntactical constructions than other languages.

 Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.

 Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.

 Python is Object-Oriented: Python supports Object-Oriented style or technique of programming


that encapsulates code within objects.

 Python is a Beginner's Language: Python is a great language for the beginner level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.

 Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.

 Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).

 Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.

 Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python 2.7.11 is the
latest edition of Python 2.

 Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2.
The emphasis in Python 3 had been on the removal of duplicate programming constructs and
modules so that "There should be one -- and preferably only one -- obvious way to do it." Python
3.5.1 is the latest version of Python 3.

Python Features

Python's features include-

 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows a student to pick up the language quickly.

 Easy-to-read: Python code is more clearly defined and visible to the eyes.

 Easy-to-maintain: Python's source code is fairly easy-to-maintain.

 A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode, which allows interactive testing
and debugging of snippets of code.

 Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.

 Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.

 Databases: Python provides interfaces to all major commercial databases.

 GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of UNIX.

 Scalable: Python provides a better structure and support for large programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features. A few are listed
below-

 It supports functional and structured programming methods as well as OOP.

 It can be used as a scripting language or can be compiled to byte-code for building large
applications.

 It provides very high-level dynamic data types and supports dynamic type checking.

 It supports automatic garbage collection.

 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

DIFFERENT MODES OF PYTHON IDLE

Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter
brings up the following prompt-
Script Mode Programming Invoking the interpreter with a script parameter begins execution of the
script and continues until the script is finished. When the script is finished, the interpreter is no
longer active.

Let us write a simple Python program in a script. Python files have the extension.py. Type the
following source code in a test.py file

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
Python.

Here are naming conventions for Python identifiers-

 Class names start with an uppercase letter. All other identifiers start with a lowercase letter.

 Starting an identifier with a single leading underscore indicates that the identifier is private.

 Starting an identifier with two leading underscores indicates a strong private identifier.

 If the identifier also ends with two trailing underscores, the identifier is a language defined special
name.

RESERVED WORDS (KEYWORDS):

Keywords are predefined reserved identifier that has special meaning.

The following list shows the Python keywords. These are reserved words and you
cannot use them as constants or variables or any other identifier names. All the Python keywords
contain lowercase letters only.
LINES AND INDENTATION

Python does not use braces ({}) to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. For example-

Comments in Python

A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters after the
#, up to the end of the physical line, are part of the comment and the Python interpreter ignores
them.

VARIABLE :

Variables are container or placeholder containing certain value which can be changed during the
execution of program.

Variables are nothing but reserved memory locations to store values. It means that when you create
a variable, you reserve some space in the memory. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by
assigning different data types to the variables, you can store integers, decimals or characters in
these variables.
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of
the = operator is the value stored in the variable. For example-

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result –

Multiple Assignment:

Python allows you to assign a single value to several variables simultaneously. For example

Here, an integer object is created with the value 1, and all the three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.

For example

Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.

Standard Data Types:

The data stored in memory can be of many types. For example, a person's age is stored as a numeric
value and his or her address is stored as alphanumeric characters. Python has various standard data
types that are used to define the operations possible on them and the storage method for each of
them.

Python has five standard data types-

 Numbers

 String

 List

 Tuple

 Dictionary

Python Numbers

Number data types store numeric values. Number objects are created when you assign a value to
them. For example

You can also delete the reference to a number object by using the del statement. The syntax of the
del statement is –

You can delete a single object or multiple objects by using the del statement.

For example

Python supports three different numerical types –

 int (signed integers)

 float (floating point real values)

 complex (complex numbers)

Examples Here are some examples of numbers


A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj,
where x and y are real numbers and j is the imaginary unit.

Python Strings

Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows either pair of single or double quotes. Subsets of strings can be taken using the slice
operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way
from -1 to the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
For example-

str = 'Hello World!'

print (str) # Prints complete string

This will produce the following result

Hello World!

Python Lists, Tuple and Dictionary: we discussed later

Data Type Conversion:


Sometimes, you may need to perform conversions between the built-in types. To convert between
types, you simply use the type-name as a function.

There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.

Basic Operators:
Operators are the constructs, which can manipulate the value of operands. Consider the expression
4 + 5 = 9. Here, 4 and 5 are called operands and + is called the operator.

Types of Operator

Python language supports the following types of operators-

 Arithmetic Operators

 Comparison (Relational) Operators

 Assignment Operators

 Logical Operators

 Bitwise Operators

 Membership Operators

 Identity Operators

Python Arithmetic Operators

Python Comparison Operators


These operators compare the values on either side of them and decide the relation among them.
They are also called Relational operators.

Assume variable a holds the value 10 and variable b holds the value 20, then

Python Assignment Operators


Python Logical Operators

The following logical operators are supported by Python language. Assume variable a holds True and
variable b holds False then.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below.

Python Identity Operators:

Identity operators compare the memory locations of two objects. There are two Identity operators
as explained below:

Python Operators Precedence: The following table lists all the operators from highest precedence to
the lowest.
Control Flow Statement:

Control flow statements are those statements that alter the default flow of program.

A program’s control flow is the order in which the program’s code executes. The control
flow of a Python program is regulated by branching, looping, and jumping statement.
Jumping Looping

Conditional Statement:

It is also known as conditional statement. Decision-making is the anticipation of conditions


occurring during the execution of a program and specified actions taken according to the
conditions. Decision structures evaluate multiple expressions, which produce TRUE or FALSE
as the outcome. You need to determine which action to take and which statements to
execute if the outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the
programming languages.
Python programming language assumes any non-zero and non-null values as TRUE, and any zero or
null values as FALSE value. Python programming language provides the following types of decision-
making statements.

One Way Branching (IF Statement):

The if statement contains a logical expression using which the data is compared and a decision is
made based on the result of the comparison.

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is
executed. In Python, statements in a block are uniformly indented after the : symbol. If boolean
expression evaluates to FALSE, then the first set of code after the end of block is executed.

Flow Diagram
When the above code is executed, it produces the following result −

Two Way Branching Statements (if…….else):

An else statement can be combined with an if statement. An else statement contains a block of code
that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at the most only one else statement
following if.

Syntax :

The syntax of the if...else statement is


In the above example, discount is calculated on the input amount. Rate of discount is 5%, if the
amount is less than 1000, and 10% if it is above 10000. When the above code is executed, it
produces the following result
Ladder statement (if…..elif….else):

The elif statement allows you to check multiple expressions for TRUE and execute a block of code as
soon as one of the conditions evaluates to TRUE.

Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the
most one statement, there can be an arbitrary number of elif statements following an if.

Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case as follows.

When the above code is executed, it produces the following result-


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.

Syntax:

The syntax of the nested if...elif...else construct may be


When the above code is executed, it produces the following result

LOOPING

In general, statements are executed sequentially- The first statement in a function is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of
code several number of times. Programming languages provide various control structures that allow
more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement.
Python programming language provides the following types of loops to handle looping
requirements.

While Loop Statements:

A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.

Syntax:
The syntax of a while loop in Python programming language is

Here, statement(s) may be a single statement or a block of statements with uniform indent. The
condition may be any expression, and true is any non-zero value. The loop iterates while the
condition is true. When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method
of grouping statements.

Flow Diagram

Here, a key point of the while loop is that the loop might not ever run. 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.

Example

When the above code is executed, it produces the following result


The block here, consisting of the print and increment statements, is executed repeatedly until count
is no longer less than 9. With each iteration, the current value of the index count is displayed and
then increased by 1.

for Loop Statements

The for statement in Python has the ability to iterate over the items of any sequence, such as a list or
a string.

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. Next, the statements block is executed. Each item in
the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence
is exhausted.

The range () function:


The built-in function range() is the right function to iterate over a sequence
of numbers. It generates an iterator of arithmetic progressions.
range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a list object of
the sequence, it is typecasted to list(). Now this list can be iterated using the for statement.

This will produce the following output

NESTED LOOPS:

Python programming language allows the use of one loop inside another loop. The following section
shows a few examples to illustrate the concept.

Syntax

The syntax for a nested while loop statement in Python programming language is as follows:

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For
example a for loop can be inside a while loop or vice versa.
The print() function inner loop has end=' ' which appends a space instead of default newline. Hence,
the numbers will appear in one row.

Last print() will be executed at the end of inner for loop.

When the above code is executed, it produces the following result –

JUMPING STATEMENT:

The Loop control statements change the execution from its normal sequence. When the execution
leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements.

The break statement is used for premature termination of the current loop. After abandoning the
loop, execution at the next statement is resumed, just like the traditional break statement in C.

The most common use of break is when some external condition is triggered requiring a hasty exit
from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost loop and
starts executing the next line of the code after the block.
Syntax

The syntax for a break statement in Python is as follows:

FLOW

EXAMPLE
When the above code is executed, it produces the following result

CONTINUE STATEMENT

The continue statement in Python returns the control to the beginning of the current loop. When
encountered, the loop starts next iteration without executing the remaining statements in the
current iteration.

The continue statement can be used in both while and for loops.

Syntax
When the above code is executed, it produces the following result

pass Statement:

It is used when a statement is required syntactically but you do not want any command or code to
execute. The pass statement is a null operation; nothing happens when it executes. The pass
statement is also useful in places where your code will eventually go, but has not been written yet
i.e. in stubs).

Syntax
When the above code is executed, it produces the following result-

You might also like