1 of 69

E-CONTENT FOR CLASS-XI (IP)��CHAPTER - 3

BRIEF OVERVIEW OF PYTHON

NAVODAYA VIDYALAYA SAMITI, NOIDA

E-Content Prepared By:-

Lakshminarayana M

PGT (IT), JNV, Chittoor, A.P.

2 of 69

Introduction

Python was created by Guido Van Rossum when he was working at CWI (Centrum Wiskunde & Informatica) which is a National Research Institute for Mathematics and Computer Science in Netherlands. The language was released in 1991. Python got its name from a BBC comedy series from seventies called “Monty Python ′s Flying Circus”. It is based on two programming languages called ABC and Modula–3.

It is used in a variety of fields, including software development, web development, scientific computing, big data and Artificial Intelligence.

3 of 69

Introduction Contd…

Some of the features which make Python so popular are as follows:

  • It is a general purpose programming language which can be used for both � scientific and non scientific programming.
  • It is a platform independent programming language.
  • It is a very simple high level language with vast library of add–on modules.
  • It is excellent for beginners as the language is interpreted, hence gives � immediate results.
  • The programs written in Python are easily readable and understandable.
  • It is suitable as an extension language for customizable applications.
  • It is easy to learn and use.
  • It is case sensitive. i.e. Uppercase and Lowercase alphabets are different

4 of 69

Advantages Of Python

Easy to Use: Python is compact and very easy to use Object Oriented language with very simple syntax rules. It is programmer–friendly

 

Expressive Language: Because of simple syntax and fewer lines of code, it is more capable to express code's purpose than many other languages

C Language Codefor swapping values Python Code for swapping values

int a = 2, b = 3, temp; a, b = 2, 3

temp = a; a, b = b, a

a = b;

b = temp;

 

Interpreted Language: Python interprets and executes the code line by line at a time. It makes Python an easy–to–debug language and thus suitable for beginners and advanced users

5 of 69

Advantages Of Python Contd…..

Completeness: Python Standard Library provides various modules for different functionalities. For example, it can be used for different functionalities like email, web–pages, databases, GUI development, network connections and many more. Hence no additional libraries to be installed

 

Cross–Platform Language: Python can run on different platforms like Windows, Linux / Unix, Macintosh, Super Computers, Smart Phones etc. Hence it portable language

 

Free and Open Source: Python is freely available at free of cost and its source code is available to every body for further improvement

 

Variety of Usage: Python can be used for a variety of applications like Scripting, Web Applications, Game development, System Administration, Rapid Prototyping, GUI Programs, Database Applications etc.

6 of 69

Limitations of Python

Not the Fastest Language: Fully compiled languages are faster than interpreted languages. Python is an interpreted language. It is first semi–compiled into an internal byte–code, which is then executed by a Python interpreter. Hence Python is not faster compared to fully compiled languages

 

Lesser Libraries: Python offers library support for almost all computing programs, but its library is still not competent with languages like C, Java, Perl as they have larger collection of libraries

 

Not Strong on Type–Binding: Python is not strong on catching 'Type Mismatch'. For example, a String value can be stored in a variable declared as an integer, where Python never complain about it

 

Not Easily Convertible: The syntax of Python language is simple but different compared to other programming languages. Hence it is not easy to convert a program which is in Python into other language

7 of 69

Working In Python

To write and run Python program, install Python interpreter in computer. IDLE (GUI integrated) is the standard, most popular Python development environment. IDLE is an acronym of Integrated Development Environment. It lets edit, run, browse and debug Python Programs from a single interface. This environment makes it easy to write programs.

 

Python shell (interpreter) can be used in two ways �(i) Interactive Mode (ii) Script Mode

8 of 69

Working In Python Contd…..

Interactive Mode: As the name suggests, this mode allows to interact with OS. This mode does not save commands in form of a program. Some points to remember while working in interactive mode are,

 

  • The symbol '>>>' is called Python prompt, indicates that interpreter is ready to accept command
  • At the prompt, either a command or statement or expression can be given
  • The secondary prompt is '...', indicates that interpreter is waiting for additional input
  • Any statement starts with the symbol "#" is called comment
  • Alt+P and Alt+N are used to invoke and repeat prior commands provided interactive window

9 of 69

Working In Python Contd…..

  • The quit( ) or Ctrl+D is used to leave the interpreter
  • Ctrl+F6 will restarts the shell
  • Type Credits at the prompt to get information about the organization involved in Python development
  • The commands copyright and license( ) can be used to know more about Python
  • The command help( ), with empty parenthesis, will provides an interactive help
  • The command help( ), with a command inside parenthesis, will provide an exclusive help about required command
  • To leave help and return to interactive mode, quit command can be used

10 of 69

Working In Python Contd…..

Script Mode: In script mode, Python program is to be typed in a file and then interpreter to be used to execute the content from the file. Working in interactive mode is convenient for beginners and for testing small pieces of code. But for coding more than few lines, code is to be saved so that it can be modified and reused.

 

To create and run a Python script, the following steps to be used in IDLE

 

    • File→Open OR File→New Window (for creating a new script file)
    • Write the Python code as function i.e. script
    • Save it (Ctrl+S)
    • Execute it in interactive mode, by using RUN option (Ctrl+F5)

11 of 69

Understanding print( )

To print or display output, Python provides print( ) statement. It can be used as follows

 

print (<objects to be printed>...)

 

Ex: print ("Hello World")

In Python, a string may be provided in either double quotes or single quotes

12 of 69

Python Character Set

Python character set represents the set of valid characters that Python supports. It has the following character set

Letters A–Z, a–z

Digits 0–9

Special Symbols Space + – * / ** \ { } ( ) // = != == < , > . ' ' " " ; : % ! � & # <= >= @ _ (underscore)

Whitespace Blank Space, Tab, Carriage Return, Newline, Form feed

Other Characters Python can process all ASCII and Unicode characters as

part of data or literals

13 of 69

Tokens

The smallest individual unit in a program is known as Token. It is also called as Lexical Unit. Tokens present in Python are (i) Keywords (ii) Identifiers (iii) Literals (iv) Operators (v) Punctuators

Keywords: A keyword is a reserved word that has a predefined meaning to the compiler / interpreter. A keyword must not be used as identifier. Python has the following keywords

False

assert

del

for

in

or

while

None

break

elif

from

is

pass

with

True

class

else

global

lambda

raise

yield

and

continue

except

if

nonlocal

return

as

def

finally

import

not

try

14 of 69

Tokens Contd…

Identifiers: An identifier is a name given to a program element such as variable, function, list, dictionary etc. The rules to be followed while naming an identifier in Python are,

 

  • It may consist of letters (A–Z, a–z), digits (0–9), and underscore( _ )
  • It must begin with a letter or an underscore
  • It must not begin with a digit
  • Uppercase and lowercase alphabets are different. For example sum, Sum, � SUM all are different
  • A keyword must not be used as an identifier
  • It can be of any length. However, it is preferred to be short and meaningful

15 of 69

Tokens Contd…

Literals / Constants: A literal or constant is a program element that will never change its values during program execution. Python allows several kinds of literals like (i) String literals (ii) Numeric literals (iii) Boolean literals (iv) Special Literal None

String Literals: A string literal is a sequence of characters enclosed in either single quotes or double quotes. Either both single quotes or both double quotes to be used for a string. Example: "Python", 'Program' etc. A single quoted string inside double quotes and vice–versa is legal in Python. Ex: "Anu's" and 'Anu"s' are valid

Escape sequence will be given as a string and performs specified task. Some escape sequences are

\n New line character

\t Horizontal Tab

16 of 69

Tokens Contd…

Python allows (i) Single–line Strings (ii) Multiline Strings

Single–line Strings: The strings that create by enclosing text in single quotes or double quotes are called single–line strings. Ex: "Python", 'Apple'

Multiline Strings: To provide a string in multiline, it is to be provided in triple quotes (triple single quotes or triple double quotes)

Ex: print ("""Jawahar

Navodaya Vidyalaya""")

17 of 69

Tokens Contd…

Numeric Literals: These literals are three types namely (i) Integer literals (ii) float literals (iii) complex literals

Integer Literals: An integer constant must have at least one digit and must not contain any decimal point. Different integer literals available are,

  1. Decimal Integer Literals: It consists of a sequence of digits between 0 and 9 and does not start with zero. Ex: 1234, –458 etc

  1. Octal Integer Literals: It consists of a sequence of digits between 0 and 7. It begins with 0o(Digit Zero Letter o) Ex: 0o24, 0o746 etc

  1. Hexadecimal Literals: It consists of a sequence of hexadecimal values between 0–9 and A–F. It begins with 0x. Ex: 0x14AC

18 of 69

Tokens Contd…

Floating Point Literals: These are also called as Real Literals. These can be expressed in two forms viz. Fractional Form and Exponent Form

  1. Fractional Form: A real constant in fractional form must have at least one digit either before or after decimal point. Ex; 2.0, 17.5, –14.6, –0.05, .3 (means 0.3), 6. (means 6.0)

  1. Exponent Form: A real constant in exponent form consists of two parts mantissa and exponent. The mantissa must be either an integer or a proper real constant. The mantissa is followed by a letter E or e and the exponent. The exponent must be an integer.

Ex: 152E05, 1.52e07, 0.152E08, 152e+8,–0.172E–3, .25e–4

Boolean Literals: A Boolean literal represent one of the two Boolean values i.e. True or False. A Boolean literal can either have value as True or as False

19 of 69

Tokens Contd…

Special Literal None:

None is a special literal in Python. It indicates the absence of value. It means "There is not useful information" or "There is nothing here“

Ex: >>>a = None

>>>print (a)

None

20 of 69

Tokens Contd…

Operators: An operator is a symbol that is used in a program in respect of some operation. Each operation is denoted by some operator. For example the operation addition is denoted by + and the operation “finding remainder” is denoted by %. Each programming language will have its own set of operators.

 

The constants or variables that participate in the operation are called operands

Unary Operator: If an operator takes only one operand then it is called Unary Operator

Binary Operator: If an operator takes two operands then it is called Binary Operator.

Ternary Operator: If an operator takes three operands then it is called Ternary Operator

Punctuators: These are the symbols used in programming to organize sentence structures and indicate the emphasis of expressions, statements and program structure. Some punctuators available in Python are,

�' " # \ ( ) [ ] { } @ , : . =

21 of 69

Basic Structure Of Python Program

The following is a simple Python program

22 of 69

Basic Structure Of Python Program Contd…..

Expression: An expression is any valid combination of symbols and represents a value

 

Statement: A statement is a programming instruction that does something i.e. performs some action

 

Comments: These are the statements that will be ignored by Python interpreter and will increase readability of program. A single line comment starts with the symbol #. For multiline comment content will be enclosed in triple quotes (" " ") or triple apostrophe (' ' '). A multiline comment is also known as docstring.

 

Functions: A function is a code that has collection of statements to do some task. It has a name and a function can be executed repeatedly as many times required

 

Blocks and Indentation: A group of statements which are part of another statement or a function are called block or code–block or suite.

23 of 69

Variables

A variable is a program element that can change its value during program execution. It is an identifier that has a named location and refers to a value and that value can be processed during program run. As a variable is an identifier, all the rules for naming an identifier are applicable for naming a variable

Creating a Variable: A variable is created by assigning a value of desired type to it. For example, an integer variable can be created by assigning an integer value, and a string variable can be created by assigning a string. It is not possible to create a variable with assigning a value to it

 

Ex: age = 20 # Means variable age is integer

average = 95.6 # Means variable average is of type float

name = "CBSE" # Means variable name is of type string

24 of 69

Variables Contd…

LValues and RValues: The LValues are the variables that hold a value or expression, and may present on either left–hand side or right–hand side of assignment. The RValues are the literals or expressions or variables that are assigned to LValues and can present on only right–hand side of assignment

 Ex: Valid Statements a = 20

d = b*b–4*a*c

temp = a

  Invalid Statements 20 = a

a * 2 = b

25 of 69

Variables Contd…

Multiple Assignments: Different ways of assignments are,

 

1. Assigning same value to multiple variables

Ex: a = b = c = 18

 

2. Assigning multiple values to multiple variables

 

Ex1: x, y, z = 10, 20, 30 # Means x=10, y=20, z=30

 

Ex2: x,y = y,x # This makes x=20, y = 10

 

Ex3: a, b, c = 5, 10, 7

b, c, a = a+1, b+2, c–1

print (a, b, c) # a=6, b=6, c=12

 

Here, first evaluations of RHS expression(s) and then assigns them to LHS

26 of 69

Variables Contd…

Dynamic Typing: A variable having a value of certain data type can be assigned with value of some other data type. In this case, it automatically assumed to change the data type of that variable. This is referred as Dynamic Typing

 

x = 10

print (x)

x = "Informatics Practices"

print(x)

 

This code will results in

 

10

Informatics Practices

27 of 69

Displaying type of variable : The type( ) can be used to display the data type of a variable or constant or object

 

Example: >>> a=10

>>> type(a)

<class 'int'>

>>> a=20.5

>>> type(a)

<class 'float'>

>>> a="Python"

>>> type(a)

<class 'str'>

Variables Contd…

28 of 69

Input And Output In Programming

Input: The input( ) function is used to input during runtime of a program. But, this function always returns a value of string type. i.e. even a number inputted using input( ) method is not a number and is a string

 

Syntax: variable = input(<Message to be displayed>)

 

>>>x = input ("Enter a Number")

>>>Enter a Number10

 

In the above case the value 10 inputted is assumed as string. Hence type of x is

string

 

To input as a number it is to be appropriately converted into desired data type,

like below

 

>>> a=int(input("Enter a Number"))

Enter a Number10

>>> print(a+2)

12

29 of 69

Input And Output In Programming Contd…

Output: The print( ) function is used for output to standard output device, monitor.

 

Syntax:

print(object1, [object2, object3, ....., sep=' ' or seperator_string, end=' ' or end_string])

Example

Command

Output

1

print("Informatics Practices")

Informatics Practices

2

print("Sum of 2 and 3 is", 2+3)

Sum of 2 and 3 is 5

3

a=2

b=3

print("Sum of", a, "and", b, "is", a+b)

Sum of 2 and 3 is 5

4

a=2

b=3

print("Sum of",a,"and",b,"is",a+b, sep='$')

Sum of$2$and$3$is$5

5

a=2

b=3

print("Sum of",a,"and",b,"is",a+b, end='*')

Sum of 2 and 3 is 5*

30 of 69

Data Types

A data type represents the type of data like character, integer, real, string etc. Different types of data types in Python are,

Numbers: Number data type stores numerical values. This data type is immutable, mean that the value of its object cannot be changed. These are of three different types

31 of 69

Data Types - Numbers

Integers: Integers are the whole numbers like 100000, –99, 0, 17 etc. They have no decimal point. Integers can be positive or negative. If an integer has no sign, then it is positive. There are two types of Integers

 

int: While writing an integer value, commas must not be used to separate digits. Also integers should not have leading zeros. The data type int can store any integer, either big or small.

 

bool: These represent the truth values False and True, that resembles integers 0 and 1 respectively. The bool( ) function returns the boolean equivalent digit.

>>> bool(1)

True

>>> bool(0)

False

32 of 69

Data Types – Numbers Contd…

Floating Point Numbers: 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 be written in two forms

 

  1. Fractional Form Examples 3500.75, 0.00005, 147.9101 etc

  1. Exponent Form Examples 3.50075E03, 0.5E–04, 1.479101E02 etc

 

The advantage of floating point numbers over integers are, they can represent values between integers and can be used to represent much greater range of values

33 of 69

Complex Numbers: 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.imag. Imaginary part of the number is represented by “j” instead of “i”, so 1+0j denotes zero imaginary part.

>>> c=2–3j

>>> c.real

2.0

>>> c.imag

–3.0

Data Types – Numbers Contd…

34 of 69

Data Types – None

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. It is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.

>>> x=None

>>> print(x)

None

35 of 69

Data Types - Sequences

Sequence: A sequence is an ordered collection of items, indexed by positive integers. It is combination of mutable and immutable data types. Three types of sequence data type available in Python are Strings, Lists & Tuples.

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.

 

Example

>>> a = 'Ram'

36 of 69

Data Types - Sequences Contd…

Every string is a sequence of characters. Every character in a string has an index and the character can be accessed using its index

Ex:

Index

0

1

2

3

4

5

String

P

Y

T

H

O

N

Index

–6

–5

–4

–3

–2

–1

Every character has two indexes like above and can be accessed using either of the two indexes

>>> name="PYTHON"

>>> print(name[2])

T

>>> print(name[–4])

T

37 of 69

Data Types - Sequences Contd…

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( )

 

Example1 Example2

>>> a= 12.34 >>>a=25

>>> b= int(a) >>>y=float(a)

>>> print (b) >>>print (y)

12 25.0

38 of 69

Data Types - Sequences Contd…

Lists: List is also a sequence of values of any type. Values in the list are called elements / items. These are mutable and indexed/ordered. List is enclosed in square brackets.

 

Example: lt = ['spam', 20.5,5]

 

Tuples: Tuples are a sequence of values of any type, and are indexed by integers. They are immutable. Tuples are enclosed in ( ).

Example: >>> T=10, 20, 30, 40

>>> print (T)

(10, 20, 30, 40)

39 of 69

Data Types – Sets and Mappings

Sets: Set is an unordered collection of values, of any type, with no duplicate entry. Sets are mutable. Duplicate values given, if any, will be considered only once. Set elements cannot be accessed individually.

 

Example: s = set ([1,2,3,4])

 

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

 

Dictionaries: These 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'}

40 of 69

Data Types – Mutable And Immutable Types

Immutable Types: The immutable types are those that can never change their value in place. Integers, Floating Point Numbers, Booleans, Strings and Tuples are immutable types

 

Mutable Types: The mutable types are those that can change their value in place. Lists, Dictionaries and Sets are mutable types

41 of 69

The data or values are referred to as object. Similarly, a variable is also an object that refer to a value. Every object has three key attributes associated to it. These are,

Variable Internals

(i) type of object: The data type of a constant or variable can be displayed using type( ) statement with the required argument

 

Ex: >>> type(11) Ex: >>> t=10,20,30,40

<class 'int'> >>> type(t)

>>> type(12.5) <class 'tuple'>

<class 'float'> >>> lt=['Spam',20.5,5]

>>> type(2+3j) >>> type(lt)

<class 'complex'> <class 'list'>

>>> type('Vidyalaya') >>> s=set([1,2,3,4])

<class 'str'> >>> type(s)

<class 'set'>

42 of 69

(ii) value of object: The print( ) can be used to print the value of an object like a variable or constant

 

Ex: >>> a=4

>>> print(a)

4

>>> print(4+2j)

(4+2j)

Variable Internals Contd…

(iii) id of an object: The id of an object is the memory location of it. The function id( ) is used for this purpose

 

Ex: >>> x=10

>>> id(x)

1722770752

>>> y=20

>>> id(y)

1722770912

>>> z=10

>>> id(z)

1722770752

43 of 69

  • Operators are special symbols which represents computation.
  • They are applied on operand(s), which can be values or variables.
  • Same operator can behave differently on different data types.
  • Operators when applied on operands form an expression.
  • Operators are categorized as Arithmetic, Relational, Logical and Assignment.
  • Value and variables when used with operator are known as operands.

Operators and Operands

44 of 69

Arithmetic or Mathematical Operators

Symbol

Description

Example 1

Example 2

+

Addition

>>>55+45

100

>>>'Good'+'Morning'

GoodMorning

Subtraction

>>>55–45

10

>>>30–80

–50

*

Multiplication

>>>55*45

2475

>>>'Good'*3

GoodGoodGood

/

Division

>>>17/5

3.4

>>>17/5.0

3.4

>>>17.0/5

3.4

>>>28/3

9.33

%

Remainder /

Modulo Division

>>>17%5

2

>>>23%2

1

**

Exponentiation

>>>2**3

8

>>>16**.5

4.0

>>>2**8

256

//

Integer Division (or) Floor Division

>>>7.0//2

3.0

>>>3//2

1

45 of 69

Relational Operators

Symbol

Description

Example 1

Example 2

<

Less Than

>>>7<10

True

>>>7<5

False

>>>7<10<15

True

>>>7<10 and 10<15

True

>>>'Hello'<'Goodbye'

False

>>>'Goodbye'<'Hello'

True

>

Greater Than

>>>7>5

True

>>>10>10

False

>>>'Hello'>'Goodbye'

True

>>>'Goodbye'>'Hello'

False

<=

Less Than or Equal To

>>>2<=5

True

>>>7<=4

False

>>>'Hello'<='Goodbye'

False

>>>'Goodbye'<='Hello'

True

>=

Greater Than or Equal To

>>>10>=10

True

>>>10>=12

False

>>>'Hello'>='Goodbye'

True

>>>'Goodbye'>='Hello'

False

!=

Not Equal To

>>>10!=11

True

>>>10!=10

False

>>>'Hello'!='HELLO'

True

>>>'Hello’!='Hello'

False

==

Equal To

>>>10==10

True

>>>10==11

False

>>>'Hello'=='Hello'

True

>>>'Hello'=='Goodbye'

False

46 of 69

Logical Operators

Symbol

Description

and

If any one of the operand is true, then the condition becomes true

or

If both the operands are true, then the condition becomes true

not

Reverses the state of operand/condition

Truth Tables for Logical Operators

A

B

A and B

A or B

not A

True

True

True

True

False

True

False

False

True

False

False

True

False

True

True

False

False

False

False

True

47 of 69

Assignment Operators

Symbol

Description

Example

Explanation

=

Assigns value from right side operand to left side variable

>>>x=12

>>>y='greetings'

+=

Add and assign the result to left side variable

>>>x+=2

Means x=x+2

x becomes 14

–=

Subtract and assign the result to left side variable

>>>x–=2

Means x=x–2

x becomes 10

*=

Multiply and assign the result to left side variable

>>>x*=2

Means x=x*2

x becomes 24

/=

Divide and assign the result to left side variable

>>>x/=2

Means x=x/2

x becomes 6

%=

Modulo Divide and assign result to left side variable

>>>x%=2

Means x=x%2

x becomes 0

**=

Performs exponential calculation and assign result to left side variable

>>>x**=2

Means x=x**2

x becomes 144

//=

Performs floor division on operators and assign result to left side variable

>>>x//=2

Means x=x//2

x becomes 6

48 of 69

Identity Operators

Symbol

Description

Example

Explanation

is

Returns True only if both the operands a and b are pointing to the same object, returns False otherwise

>>> x=10

>>> y=20

>>> z=10

>>> x is z

True

>>> x is y

False

Here, the operands x and z are pointing to the same object 10, hence resulted in True where as x and z are pointing to different objects, hence resulted in false

is not

Returns True if both the operands a and b are pointing to different objects, returns False otherwise

49 of 69

Membership Operators

Symbol

Description

Example

in

Returns True if the variable or value is found in the specified sequence and False otherwise

>>> numSeq = [1,2,3]

>>> 2 in numSeq

True

>>> '1' in numSeq

False

#'1' is a string while numSeq contains number 1.

not in

Returns True if the variable/value is not found in the specified sequence and False otherwise

>>> numSeq = [1,2,3]

>>> 10 not in numSeq

True

>>> 1 not in numSeq

False

50 of 69

Precedence of Operators

While evaluating an expression the precedence of operators will be like below. It gives the order of evaluation of operators in an expression. However the precedence can be changed by using parenthesis

51 of 69

Expressions

An expression is a combination of literals, operators and variables. In Python, an expression may be an arithmetic expression, string expression, relational expression, logical expression, compound expression etc.

 

Arithmetic Expressions: These expressions involve numbers (integers, floating point numbers, complex numbers) and arithmetic operators

Ex: 2+8/3, 5.6–4.2/8*1.2

 

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

Ex: x>y, y<=z, z<>x, z==q, x<y>, x==y<>z

 

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

Ex: a or b, b and c, a and not b, not c or not b

 

String Expressions: An expression that have string operands and results to string are string expression.

Ex: "Pine"+"Apple", "Hello"*3

52 of 69

A bug is an error caused in a program. Correcting an error is called Debugging. Different types of errors that will be encountered while developing any application are as follows

 

      • Syntax Errors
      • Runtime Errors
      • Logical Errors

 

Syntax Errors: A set of rules for writing a statement in a program is called Syntax. Hence, syntax errors occur when the syntax rules of program are not followed. These errors are visible during interpretation of program. For example, parentheses mismatch the following statement will results into a syntax error

 

d = (b * b – (4 * a * c)

Debugging

53 of 69

Runtime Errors: These errors are so called because these will be occurred during runtime of program. A program may be syntactically correct, but may generate errors during run time. For example,

 

a = 10, b = 0;

c = a / b;

 

The above code is syntactically correct. But during runtime division with 0 is not possible and hence error will be generated. These errors will cause abnormal termination of code.

Debugging Contd…

54 of 69

Logical Errors: A program, without having any syntax and runtime errors, may give wrong results. The errors that will give wrong results due to the mistakes made by programmer are called Logical Errors. These errors are hard to locate. Consider the below example:

 

hin_marks = 82, eng_marks = 90, gk_marks = 94;

 

average = hin_marks + eng_marks + gk_marks / 3;

 

The above statement is not having syntax error or runtime error, but gives a wrong result. It should be as,

double average = (hin_marks + eng_marks + gk_marks) / 3;

 

It is an error by programmer and is called as Logical Error

Debugging Contd…

55 of 69

Functions

A function refers to a set of statements or instructions grouped under a name that perform specified tasks. A function is defined once and can be reused at places in a program by simply writing the function name, i.e., by calling that function.

 

Python has many predefined functions called built‑in functions. A module is a python file in which multiple functions are grouped together. These functions can be easily used in a Python program by importing the module using import command. Use of built‑in functions makes programming faster and efficient.

56 of 69

Functions Contd…

A function will have the following parts

 

  • Function Name — name of the function.

  • Arguments / Parameters — These are variables or constants passed in parentheses while calling a function. A function may or may not have argument(s).

  • Return Value — A function may or may not return one or more values. A function performs operations on the basis of argument(s) passed to it and the result is passed back to the calling point. Some functions do not return any value.

57 of 69

Functions Contd…

Consider the following Python program using three built–in functions input( ), int( ) and print( ):

 

#Calculate square of a number

num = int(input("Enter the first number"))

square = num * num

print("the square of", num, " is ", square)

58 of 69

In the above program, 

  • In the first statement, two built–in functions used are int( ) and input( ). � The third line has a function print( )

  • The input function accepts an argument, “Enter your name”. � Argument(s) is the value(s) passed within the parenthesis.

  • Similarly the print function has four arguments "the square of", num, "is", � square separated by commas.

  • The int function in the first line takes as argument the value entered by the � user from the keyboard and converts it into a string and returns it. Thus � the return value from the int( ) function is an integer.

Some examples for built–in functions are print( ), bool( ), dict( ), list( ), abs( ), max( ), sum( ), pow( ), len( ), range( ), type( ) etc.

Functions Contd…

59 of 69

Statement Flow Control

In general, all the statements in a program will be executed sequentially. i.e. no statement will be skipped or no statement will be executed repeatedly. Such execution is referred as Sequential execution. Python allows selection statements to execute selected statements from the available set of statements and iterative statements to execute a set of statements repeatedly

60 of 69

Types of Statements

A statement is a part of program and an instruction given to python interpreter to perform some action such as taking input, generating output, evaluating an expression etc. It is the smallest executable unit within a program. In Python, statements are as follows

 

      • Empty Statement
      • Simple (Single) Statement
      • Compound(Multiple) Statement

Empty Statement: An empty statement is pass statement, which does nothing. When Python interpreter encounters pass statement, it does nothing and moves to next statement in the flow of control

 

A pass statement is useful in those instances where the syntax of the language requires the presence of a statement but where the logic of the program does not. A pass statement is also known as null operation statement

61 of 69

Types of Statements Contd…

Simple Statement: A single line executable statement is a Simple Statement.

 

Example 1: name = input("Enter Your Name:")

 

Example 2: print(name)

Compound Statement: A Compound Statement is a group of simple statements which are executed to be whole or not to be executed whole. A compound statement may consists of another compound statement.

 

In Python, a compound statement has the following

 

Header Line: It begins with a keyword and ends with a colon

 

Body: It consists of one or more indented statements inside the header line. All the statements in the body are at the same level of indentation

 

Syntax:

<compound statement header>:

<indented body containing multiple simple and / or compound statements>

62 of 69

Selection / Conditional Statements

63 of 69

Selection / Conditional Statements Contd…

64 of 69

Selection / Conditional Statements Contd…

The if–elif Statement:

 

The if–elif statement is useful for putting multipath decisions. A multipath decision is a chain of ifs in which the statement associated with each else is an if. It takes the following general form.

 

if <condition>:

statements1

elif <condition>:

statements2

elif <condition>:

statements3

else:

statements

65 of 69

Selection / Conditional Statements Contd…

The nested if statement:

 

In the different forms of if statements viz. if statement, if–else statement and if–elif statements any statement can be used in another statement that results in nesting of if statement

 

Ex:

if <condition>:

if <condition>:

statements1a

else:

statements1b

elif <condition>:

statements2

elif <condition>:

statements3

else:

statements

66 of 69

Iterative / Repetitive / Loop Statements

The while loop:

 

  • The syntax of while statement is,

while <logical_expression >:

statements_to_repeat

else:

statements

  • When the control enters while loop the logical expression will be evaluated

  • If it evaluates to true then the statements part will be executed and again control � transfers to logical_expression part

  • If the logical expression returns false then the control will be exited from while loop

  • Statements will be continuously executed as long as the condition is true

  • If the condition becomes false then the else part will be executed, if present

67 of 69

Iterative / Repetitive / Loop Statements Contd…

The range( ) function:

 

This function generates a list which is a special sequence type. A sequence is a succession of values bound together by a single name. Some sequence are: strings, lists, tuples etc.

 

Syntax : range(<lower limit>, <upper limit> [,<step value>])

Use : The function in the form range(l, u) will produce a list having values

starting from l to u–1(Upper limit not included), where l and u are integers.

If step value is ignored then default step value is +1

Statement

Values generated

range(10)

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

range(5,10)

5, 6, 7, 8, 9

range(7,3)

No values will be generated

range(8, 8)

No values will be generated

range(5, 15, 3)

5, 8, 11, 14

range(9, 3, –1)

9, 8, 7, 6, 5, 4

range(–10, –5)

–10, –9, –8, –7, –6

range(–10)

No values will be generated

range(–10, –5, 2)

–10, –8, –6

68 of 69

Iterative / Repetitive / Loop Statements Contd…

The in and not in Operators:

 

These operators are used along with range( ) to check whether a value is contained inside a list or not. These operators returns a value either True or False

Example

Expression

Boolean Value

Returned

1

3 in [1, 2, 3, 4]

True

2

5 in [1, 2, 3, 4]

False

3

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

True

4

′a′ in ″trade″

True

5

″ash″ in ″trash″

True

6

″the″ in ″Python″

False

69 of 69

Iterative / Repetitive / Loop Statements Contd…

The for loop:

  • The syntax of for statement is,

for <variable> in <sequence>:

statements_to_repeat

else:

statements

 

  • The loop–variable is assigned the first value in the sequence

  • All the statements in the body of for loop are executed with assigned value of � loop variable

  • Now, the loop–variable is assigned the next value in the sequence and the � loop–body is executed with new value of loop–variable

  • This continues until all values in the sequences are processed

  • After processing all the elements in the sequence the else part will be executed,

if present