You are on page 1of 314

RM434P

Fundamentals of Python
Programming
Instructor: Dr. Umesh V
RECAP of C
Difference C &Python
C Python
An Imperative programming model is basically An object-oriented programming model is basically followed
followed by C. by Python.
Variables are declared in C. Python has no declaration.
C doesn’t have native OOP. Python has OOP which is a part of the language.
Pointers are available in C language. No pointers functionality is available in Python.
C is a compiled language. Python is an interpreted language.
There is a limited number of built-in functions
There is a large library of built-in functions in Python.
available in C.
Implementation of data structures requires its It is easy to implement data structures in Python with built-in
functions to be explicitly implemented. insert, append functions.
C is compiled directly to machine code which is Python is firstly compiled to a byte-code and then it is
executed directly by the CPU interpreted by a large C program.
Declaring of variable type in C is a necessary
There is no need to declare a type of variable in Python.
condition.
C does not have complex data structures. Python has some complex data structures.
Comparison Parameter
Comparison Parameter C Python
The Python programming language was first
The C programming language was developed
Developed / Founded by worked upon by Guido van Rossum and was
by Dennis M. Ritchie in 1972.
released in the year 1991.
Python is an object oriented programming
Programming model C is a procedural programming language
language.
Python is a high-level language as the translation
C is a middle level language as it binds the bridges
Type of language of Python code takes place into machine
between machine level and high level languages.
language, using an interpreter.

C is a compiled programming language. Special


Python is an interpreted programming language.
Compilation and programs known as compilers check the C code and
Special programs known as interpreters, Errors in
Interpretation if any error is found on any line, the program
the entire Python code is reported at once.
compilation stops then and there.

C is a faster language compared to Python as it is Python programs are usually slower than C
Speed
compiled. programs as they are interpreted.
In Python, variables are untyped, that is, there is
no need to define the data type of a variable
In C, the type of the various variables must be
while declaring it.
Variable Declaration declared when they are created, and only values of
A given variable in Python can store values of
those particular types must be assigned to them.
different data types in different parts of the
Python code.
What is Python?
• Python is a widely-used, interpreted, object-oriented, and high-level
programming language with dynamic semantics, used for general-purpose
programming.
• And while you may know the python as a large snake, the name of the
Python programming language comes from an old BBC television comedy
sketch series called Monty Python's Flying Circus.
• At the height of its success, the Monty Python team were performing their
sketches to live audiences across the world, including at the Hollywood
Bowl.
• Monty Python is considered one of the two fundamental nutrients to a
programmer (the other being pizza), Python's creator named the language
in honor of the TV show.
INTRODUCTION
INTRODUCTION

Python is a high-level, interpreted and general-purpose dynamic


programming language that focuses on code readability.
The syntax in Python helps the programmers to do coding in fewer steps
as compared to Java or C++.

The language founded in the year 1991 by the developer Guido Van
Rossum has the programming easy and fun to do.
INTRODUCTION

• The Python is widely used in bigger organizations because


of its multiple programming paradigms.
• They usually involve imperative and object-oriented
functional programming.
• It has a comprehensive and large standard library that has
automatic memory management and dynamic features.
INTRODUCTION

Python is a general-purpose language, which means it can be used to


build just about anything, which will be made easy with the right
tools/libraries.
Professionally, Python is great for backend web development, data
analysis, artificial intelligence, and scientific computing. Many developers
have also used Python to build productivity tools, games, and desktop apps,
so there are plenty of resources to help you learn how to do those as well.
Who created Python?
• There are not many languages whose authors are known by name.
• Python was created by Guido van Rossum, born in 1956 in Haarlem, the
Netherlands.
GUIDO VAN ROSSUM

Guido van Rossum is a Dutch


programmer best known as the
author of the Python programming
language, for which he was the
"Benevolent Dictator For Life" until
he stepped down from the position
in July 2018.
GUIDO VAN ROSSUM
Born 31 January 1956 (age 62)
Haarlem, Netherlands
Residence Belmont, California, U.S.
Nationality Dutch
Alma mater University of Amsterdam
Occupation Computer programmer,
author
Employer Dropbox
Known for Creating the Python
programming language
Spouse(s) Kim Knapp (m. 2000)
Children Orlijn Michiel Knapp-van
Rossum
Website www.python.org/~guido/
Where does the Python
name come from?
Where does the Python name come from?

When he began implementing Python, Guido van Rossum


was also reading the published scripts from
“Monty Python's Flying Circus”, a BBC comedy series from the
1970s. Van Rossum thought he needed a name that was short,
unique, and slightly mysterious, so he decided to call the
language Python.
ADVTANGES OF PYTHON
AS
PYTHON ADVANTAGES
01. Easy to Use. 19. Effective as a Rapid
02. Expressive Language. Prototyping Tool
03. Interpreted Language. 20. A Memory Manager.
04. Its Completeness. 21. Interpreted and (Byte-)
05. Cross Plat Form Language. Compiled.
06. Free and Open Source. 22. Multi paradigm language.
07. Variety of sage/Applications. 23. Acts as foundation to learn other
08. Interactive. languages.
09. Modular. 24. Perfect to build prototypes.
10. Dynamic. 25. Flexible.
11. Object-oriented. 26. Case Sensitive Language.
12. Portable. 27. Structured programming language.
13. High level. 30. Scientific Language.
14. Extensible in C++ & C. 31. General purpose language.
15. Easy-to-learn .
16. Easy-to-read.
17. Easy-to-maintain.
18. Robust.
WHY COMPANIES PREFER PYTHON?
WHY COMPANIES PREFER PYTHON?

• Python has top the charts in the recent years over other programming
languages like C, C++ and Java and is widely used by the programmers.
• The language has undergone a drastic change since its release 25 years
ago as many add-on features are introduced.
• The Python 1.0 had the module system of Modula-3 and interacted with
Amoeba Operating System with varied functioning tools.
• Python 2.0 introduced in the year 2000 had features of garbage
collector and Unicode Support.
WHY COMPANIES PREFER PYTHON?

• Python 3.0 introduced in the year 2008 had a constructive design that

avoids duplicate modules and constructs.

• With the added features, now the companies are using Python 3.5.

• The software development companies prefer Python language because

of its versatile features and fewer programming codes.

• Nearly 14% of the programmers use it on the operating systems like

UNIX, Linux, Windows and Mac OS.


WHY COMPANIES PREFER PYTHON?

The programmers of big companies use Python as it has created a mark for
itself in the software development with characteristic features like:

✓Interactive
✓Interpreted
✓Modular
✓Dynamic
✓Object-oriented
✓Portable
✓High level
✓Extensible in C++ & C
WHY COMPANIES PREFER PYTHON?

The programmers of big companies use Python as it has created a mark


for itself in the software development with characteristic features like:

✓Easy-to-learn
✓Easy-to-read
✓Easy-to-maintain
✓Robust
✓Effective as a Rapid Prototyping Tool
✓A Memory Manager
✓Interpreted and (Byte-) Compiled
COMPANIES USING PYTHON
COMPILERS AND INTERPRETERS
COMPILER
Its a translator used to convert HLL to MLL
and vice versa.
COMPILER
Its a translator used to convert HLL to MLL and vice versa.
INTERPRETER
Its a translator used to convert HLL to MLL and vice versa.
INTERPRETER
Its a translator used to convert HLL to MLL and vice
versa.
PYTHON DISTRIBUTION

What is Python distribution?

A Python distribution is a software bundle, which contains


a Python interpreter and the Python standard library.
• Installer programs for common operating systems.
PYTHON DISTRIBUTION

• Aside from the official CPython distribution available


from python.org, other distributions based on CPython include
the followings:
What is an IDE?
• An integrated development environment (IDE) is a software application
that provides comprehensive facilities to computer programmers for
software development.
• An IDE normally consists of a source code editor, build automation tools,
and a debugger.
• Most modern IDEs have intelligent code completion.
PYTHON SHELL

What is Shell?

A shell is usually an "interactive shell", usually termed a REPL which


stands for "Read - Execute - Print - Loop"
Most interpreted languages offer a REPL interface - whether its
LISP, python, BASIC or Javascript or even DOS batch language or Unix
Shells.
The interpreter is what actually executes the lines of code.
PYTHON SHELL

What is Python Shell or Python Interactive Shell?


• The Python interpreter can be used from an interactive shell.
• The interactive shell is also interactive in the way that it stands
between the commands or actions and their execution.
... Python offers a comfortable command line interface with
the Python shell, which is also known as the "Python interactive
shell".
PYTHON SHELL IDLE
PYTHON BASIC MODES
What are the basic modes of python?

Python has two basic modes:

1) Script and

2) Interactive.
PYTHON BASIC MODES
1) Script Mode:

The normal mode is the mode where the scripted and


finished .py files are run in the Python interpreter.

2) Interactive Mode

Interactive mode is a command line shell which gives


immediate feedback for each statement, while running
previously fed statements in active memory.
SCRIPT
What is Script?

Scripts are reusable. Basically, a script is a text file


containing the statements that comprise a Python program.
Once you have created the script, you can execute it over and
over without having to retype it each time. Scripts are editable.
INVOKING SCRIPT MODE
INVOKING SCRIPT MODE
INVOKING SCRIPT MODE
Saving Script / Program File

Click On File
Select Save
Give filename with
py extension

For Example:
first.py
Or
first.PY
Running or Executing Program / Script

Click On Run
Select

Run Module
Or
F5
Python Shell Window
• A shell window contains an opening message followed by the special
symbol >>>, called a shell prompt.
• The cursor at the shell prompt waits for you to enter a Python command.
• Note that you can get immediate help by entering help at the shell
prompt or selecting
• Help from the window’s drop-down menu.
Editing, Saving, and Running a Script
To compose and execute programs in this manner, you perform the following
steps:
1. Select the option New Window from the File menu of the shell window.
2. In the new window, enter Python expressions or statements on separate
lines, in the , order in which you want Python to execute them.
3. At any point, you may save the file by selecting File/Save. If you do this,
you should use a . py extension.
For example, your first program file might be named myprogram. py.
4. To run this file of code as a Python script, select Run Module from the Run
menu or press the F5 key.
Editing, Saving, and Running a Script
Editing, Saving, and Running a Script
• Note : Running the script from the IDLE window will allow you to
construct some complex programs, test them, and save them in
program libraries that you can reuse or share with others
How Python Works
Steps in interpreting a Python program
1. The interpreter reads a Python expression or statement, also called the
source code, and verifies that it is well formed.
• In this step, the interpreter behaves like a strict English teacher who rejects any sentence that does not adhere to
the grammar rules, or syntax, of the language.

2. If a Python expression is well formed, the interpreter then translates it to an equivalent


form in a low-level language called byte code. When the interpreter runs a script, it
completely translates it to byte code .

3. This byte code is next sent to another software component, called the Python Virtual
machine (PVM), where it is executed. If another error occurs during this step, execution also
halts with an error message
Keywords of Python
List of Keywords in Python
• And • From • Try • False
• as • non Local • elif • True
• not • continue • in • None
• assert • Global • While
• finally • raise • else
• or • def • is
• break • if • With
• for • return • except
• Pass • del • lambda
• class • import • yield
DATA HANDLING
INTRODUCTION

Data can be of many types e.g. character,


string, integer, real etc.

Python like any other language provides


ways and facilities to handle different types of
data by providing data types.
PYTHON DATA TYPES
PYTHON DATA TYPES

What is Data type?

DATA TYPES are means to identify the type of data and


associated operations of handling it.
PYTHON DATA TYPES
DATA TYPES IN PYTHON
• Python has the following data types built-in by default, in these
categories: Text Type: str
Numeric int, float, complex
Types:
Sequence list, tuple, range
Types:
Mapping dict
Type:
Set Types: set, frozenset
Boolean bool
Type:
Binary Types: bytes, bytearray, memoryview

None Type: NoneType


NUMBERS

The numbers can be represented in the


python as:
(i) Integers.
(ii) Floating point Numbers.
(iii) Complex Numbers.
(I) INTEGERS
(i) INTEGERS (SIGNED)
• Integers can be of any length. Its only limited by the memory
available.
• It’s a signed representation, i.e., the integers can be positive or
negative.
• The most common implementation of the int data type in many
programming languages consists of the integers from -
2,147,483,648 (-2^31 ) to 2,147,483,647 (2^31 -1).
(ii) FLOATING POINT NUMBERS
(ii) FLOATING POINT NUMBERS

A numbers containing fractional part is called floating point


number.
for example: 93.452
Floating point numbers can be written in two forms.
Note: Floating point numbers have precision of 16 Digits( double
precision) in python.
(ii) FLOATING POINT NUMBERS
• Python uses floating-point numbers to represent real numbers.
• Values of the most common implementation of Python’s float type range from
approximately -10^308 to 10^308 and have 16 digits of precision.
• A floating-point number can be written using either ordinary decimal notation or
Scientific notation. Scientific notation is often useful for mentioning very large
numbers.
(ii) FLOATING POINT NUMBERS

Exponent
Fractional Form
Notation

Floating
Point
Numbers

Note: Floating point numbers have precision of


15 Digits( double precision) in python.
(ii) Advantages of Floating Point Numbers

1. They can represent range of values between the integers.


2. They can represent a greater extent/ range of values.

Note: Floating point numbers have precision of


16 Digits( double precision) in python.
(iii) COMPLEX NUMBERS

A complex number is a number that can be expressed in the


form a + bi,
where,
a and b are real numbers, and
i is called an imaginary number.
For the complex number a + bi, a is called the real part, and b is
called the imaginary part.
(iii) COMPLEX NUMBERS
(iii) COMPLEX NUMBERS
COMPLEX NUMBERS IN PYTHON
COMPLEX NUMBERS IN PYTHON

Python library also has complex() function, which forms object


from two float arguments
>>> no=complex(5,6)
>>> no (5+6j)
>>> no.real o/p 5.0
>>> no.imag o/p 6.0
>>> type(no)
<class 'complex'>
Character Sets
• All data and instructions in a program are translated to binary numbers
before being run on a real computer.
• To support this translation, the characters in a string each map to an integer
value.
• This mapping is defined in character sets, among them the ASCII set and
the Unicode set.
• (The term ASCII stands for American Standard Code for Information
Interchange.)
Character Sets
• Table shows the mapping of character values to the first
128 ASCII codes.
• The digits in the left column represent the leftmost
digits of an ASCII code, and the digits in the top row
are the rightmost digits.
• Thus, the ASCII code of the character 'R' at row 8,
column 2 is 82.
Character Sets
Character Sets
• Python’s ord and chr functions convert characters to their numeric ASCII
codes and back again, respectively.
STRINGS
STRINGS

• Like many other popular programming languages, strings in


Python are arrays of bytes representing Unicode characters.
• However, Python does not have a character data type, a single
character is simply a string with a length of 1.
• Square brackets can be used to access elements of the string.
How to create a string in Python?
Creating
• In computer programming, a string is a sequence of characters. For
example, "hello" is a string containing a sequence of characters 'h', 'e', 'l',
'l', and 'o'.
• We use single quotes or double quotes to represent a string in Python. For
example,
STRINGS

How to create a string in Python?

• Strings can be created by enclosing characters inside a


single quote or double quotes.
• Even triple quotes can be used in Python but generally
used to represent multiline strings and docstrings.
REPRESENTATION OF STRING
REPRESENTATION OF STRING
>>> s = “Hello Python”
This is how Python would index the string:

Backward Indexing

Forward Indexing
Example: Python String
Access String Characters in Python
• We can access the characters in a string in three ways.
1. Indexing: One way is to treat strings as a list and use index values. For
example,

2. Negative Indexing: Similar to a list, Python allows negative indexing for its strings.
For example,
3. Slicing: Access a range of characters in a string by using the slicing
operator colon : For example,

• Python Strings are immutable. That means the characters of a string


cannot be changed.
Python Multiline String
• We can also create a multiline string in Python.
• For this, we use triple double quotes """ or triple single quotes '''. For
example,
Python String Operations

• There are many operations that can be performed with strings which
makes it one of the most used data types in Python.
1. Compare Two Strings
• We use the == operator to compare two strings. If two strings are equal,
the operator returns True. Otherwise, it returns False. For example
2. Join Two or More Strings
• In Python, we can join (concatenate) two or more strings using the +
operator.
Iterate Through a Python String
Python String Length
• In Python, we use the len() method to find the length of a string. For
example
STRINGS
LISTS
A list is a collection of similar or different types of data.

Note : Lists are mutable in nature.

General format of list is :


my_list = [item_1, item_2, item_3]

colors = ["Orange" , "red" , "Green" , "White“]

Python also allows creation of an empty list:


my_list = [ ]
Create a Python List
• A list is created in Python by placing items inside [ ], separated by
commas .

A list can have any number of items and they may be of different types (integer, float,
string, etc.). For example,
Access Python List Elements
• In Python, each item in a list is associated with a number. The number is
known as a list index.
• We can access elements of an array using the index number (0, 1, 2 …). For
example,
Negative Indexing in Python
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing of a Python List
• In Python it is possible to access a section of items from the list using the
slicing operator :, not just a single item. For example,

Note: When we slice lists, the start index is inclusive but the end index is exclusive.
TUPLE
• A tuple in Python is similar to a list.
• The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas we can change
the elements of a list.
Creating a Tuple

• A tuple is created by placing all the items (elements) inside parentheses


(), separated by commas.
• The parentheses are optional, however, it is a good practice to use
them.
• A tuple can have any number of items and they may be of different
types (integer, float, list, string, etc.).
Creating Tuples without parenthesis
• As mentioned earlier, we can also create tuples without using
parentheses:

Access Python Tuple Elements
• Like a list, each element of a tuple is represented by index numbers (0, 1,
...) where the first element is at index 0.
• We use the index number to access tuple elements. For example,

1. Indexing
We can use the index operator [] to access an item in a tuple, where the
index starts from 0.
2. Negative Indexing

• Python allows negative indexing for its sequences.


• The index of -1 refers to the last item, -2 to the second last item and so
on. For example,

In the above example,


letters[-1] - accesses last element
letters[-3] - accesses third last element
3. Slicing
• We can access a range of items in a tuple by using the slicing operator
colon :

Note: When we slice lists, the start index is inclusive but the
end index is exclusive.
Python Tuple Methods

• In Python ,methods that add items or remove items are not available
with tuple.
• Only the following two methods are available.

• Some examples of Python tuple methods:


Python Sets
• A set is a collection of unique data. That is, elements of a set cannot be
duplicate. For example,
• Suppose we want to store information about student IDs. Since student
IDs cannot be duplicate, we can use a set.
Create a Set in Python

• In Python, we create sets by placing all the elements inside curly braces {},
separated by comma.

• A set can have any number of items and they may be of different types
(integer, float, tuple, string etc.). But a set cannot have mutable elements
like lists, sets or dictionaries as its elements.
• A set can have any number of items and they may be of different types
(integer, float, tuple, string etc.).
• But a set cannot have mutable elements like lists, sets or dictionaries as its
elements.
• Let's see an example,
• Note: In the above example, we have created different types of sets by
placing all the elements inside the curly braces {}.
• Note: When you run this code, you might get output in a different order.
This is because the set has no particular order.
Create an Empty Set in Python
• Creating an empty set is a bit tricky. Empty curly braces {} will make an
empty dictionary in Python.
• To make a set without any elements, we use the set() function without
any argument. For example,
• Here,
• empty_set - an empty set created using set()
• empty_dictionary - an empty dictionary created using {}
• Finally we have used the type() function to know which class empty_set
and empty_dictionary belong to.
Python Dictionary
• Python dictionary is an ordered collection of items.

• It stores elements in key/value pairs. Here, keys are unique identifiers


that are associated with each value.
Example
• If we want to store information about countries and their capitals, we
can create a dictionary with country names as keys and capitals as
values.
Create a dictionary in Python

• In the above example, we have created a dictionary named capital_city. Here,


• Keys are "Nepal", "Italy", "England"
• Values are "Kathmandu", "Rome", "London"

Note: Here, keys and values both are of string type. We can also have keys and
values of different data types.
Example 1: Python Dictionary

In the above example, we have created a dictionary


named numbers.
Here, keys are of integer type and values are of string type.
Add Elements to a Python Dictionary

• We can add elements to a dictionary using the name of the dictionary


with []. For example,
Change Value of Dictionary
• We can also use [] to change the value associated with a particular key.
For example,
BOOLEANS
• Boolean data types are the truth values, i.e., True form or False
form.
• Boolean data type is a one kind of integer type they can be
represented in the integer form i.e., 0 and 1.

practically one can execute as

>>>bool(0)
will give result as false

>>>bool(True)
will produce 1 result.
Python bytes() Function

• It can convert objects into bytes objects, or create empty bytes object of
the specified size.
• The difference between bytes() and bytearray() is that bytes() returns an
object that cannot be modified, and bytearray() returns an object that can
be modified.
Getting the Data Type

You can get the data type of any


object by using the type() function:
Setting the Data Type
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Setting the Specific Data Type
• If you want to specify the data type, you can use the following
constructor functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
TYPE CONVERSION
Type Conversion
• You can convert from one type to another with the int(),
float(), and complex() methods:
Random Number
• Python has a built-in module called random that can be used to make
random numbers:
• Example
• Import the random module, and display a random number between 1 and 9:

• import random

• print(random.randrange(1, 10))
Escape Sequences in Python
• The escape sequence is used to escape some of the characters present
inside a string.
• Suppose we need to include both double quote and single quote inside a
string

Since strings are represented by single or double quotes, the compiler will treat "He
said, " as the string. Hence, the above code will cause an error.
• To solve this issue, we use the escape character \ in Python
Here is a list of all the escape sequences
supported by Python.
PYTHON OPERATORS
Python Operators
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Python Arithmetic Operators
• Arithmetic operators are used with numeric values
to perform common mathematical operations
Operator Name Example

+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
• Assignment operators are used to assign values to
variables: Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Python Comparison Operators
• Comparison operators are used to compare two
values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal x >= y
to
<= Less than or equal to x <= y
Python Logical Operators
• Logical operators are used to combine conditional
statement
Operator Description Example
Returns True if both statements are true x < 5 and x < 10
and
Returns True if one of the statements is true x < 5 or x < 4
or
Reverse the result, returns False if the result is true not(x < 5 and x <
not 10)
Python Identity Operators
• In Python, is and is not are used to check if two values are located on the
same part of the memory.
• Two variables that are equal does not imply that they are identical.

Operator Description Example


Returns True if both x is y
is variables are the same
object
Returns True if both x is not y
is not variables are not the same
object
• Note :
• Here, we see that x1 and y1 are integers of the same
values, so they are equal as well as identical. Same is
the case with x2 and y2 (strings).

• But x3 and y3 are lists. They are equal but not


identical. It is because the interpreter locates them
separately in memory although they are equal.
Python Membership Operators

• In Python, in and not in are the membership operators. They are


used to test whether a value or variable is found in a sequence (string,
list, tuple, set and dictionary).

• In a dictionary we can only test for presence of key, not the value.

Operator Description Example


Returns True if a sequence
in with the specified value is
x in y
present in the object
Returns True if a sequence
not in with the specified value is not
x not in y
present in the object
Python Membership Operators
• Note:
• Here, 'H' is in x but 'hello' is not present in x (remember,
Python is case sensitive)
• Similarly, 1 is key and 'a' is the value in dictionary y. Hence,
'a' in y returns False.
Python Bitwise Operators

• Bitwise operators are used to compare (binary) numbers:


Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost
shift bits fall off

>> Signed right Shift right by pushing copies of the leftmost bit in from the left,
shift and let the rightmost bits fall off
Precedence and Associativity of Operators in Python
• Precedence of Python Operators
• The combination of values, variables, operators, and function calls is termed as
an expression.
• For example, multiplication has higher precedence than subtraction.
• But we can change this order using parentheses () as it has higher
precedence than multiplication.
Precedence rules
• Parenthesis has the highest precedence and its evaluated first
• Exponentiation has the next highest precedence and is evaluated.
• Unary negation is evaluated next, before multiplication, division,
and remainder.
• Multiplication, both types of division, and remainder are evaluated
before addition and subtraction.
• Addition and subtraction are evaluated before assignment.
• With two exceptions, operations of equal precedence are left
associative, so they are evaluated from left to right. Exponentiation
and assignment operations are right associative, so consecutive
instances of these are evaluated from right to left.
• You can use parentheses to change the order of evaluation.
Operators Meaning
() Parenthesis
** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

Multiplication, Division, Floor division,


*, /, //, %
Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR
= Assignment
Associativity of Python Operators
• If two operators have the same precedence, associativity helps to
determine the order of operations.
• Associativity is the order in which an expression is evaluated that has
multiple operators of the same precedence.
• Almost all the operators have left-to-right associativity.
• For example, multiplication and floor division have the same precedence.
• Hence, if both of them are present in an expression, the left one is
evaluated first.
Note: Exponent operator ** has right-to-left
associativity in Python.

We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).


Detecting Errors
• Syntax errors:
• These errors occur when your code is not well formed, according to the
syntax or grammar rules of Python.
• For example, the expression abs(-34) is syntactically correct, but the
expression abs(-34)) is not. (It contains an extra right paren.)

• Semantic errors:
• These errors occur when a syntactically correct expression is evaluated,
but Python cannot carry out the evaluation.
• For example, Python cannot divide a number by zero, cannot compute the
square root of a negative number.
Detecting Errors
• Logic errors—Also called design errors, these errors occur when Python
successfully evaluates an expression, but the expression returns an
incorrect result.
• For example, the expression math.pi * 34 ** 2 does return a value, but
if you expect this value to be the volume of a sphere of radius 34, your
code contains a logic or design error.
• Note : When an expression becomes long or complex, you can
move to a new line by placing a backslash character \ at the
end of the current line.

• Make sure to insert the backslash before or after an operator.


• If you break lines in this manner in IDLE, the editor automatically indents
the code properly.
Input, Processing, and Output
• Most useful programs accept inputs from some source, process these inputs,
and then finally output results to some destination.

• In terminal-based interactive programs, the input source is the keyboard, and


the output destination is the terminal display.

• The Python shell itself is such a program; its inputs are Python expressions or
statements.

• Its processing evaluates these items.

• Its outputs are the results displayed in the shell.


Input, Processing, and Output
• The simplest form for using this function looks like the following:
• print(<expression>)
• The following is another example:
• >>> print ("Hi there")
• Note : print function always ends its output with a newline. In other
words, it displays the values of the expressions, and then it moves the
cursor to the next line on the console window
• Note : To begin the next output on the same line as the previous one,
you can place the expression end = "", which says “end the line with an
empty string instead of a newline
• print(<expression>, end = "")
• In Python, we can simply use the print() function to print output. For
example,

• Syntax of print() :The actual syntax of the print function accepts


5 parameters
• Here,
• object - value(s) to be printed
• sep (optional) - allows us to separate multiple objects inside print().
• end (optional) - allows us to add specific values like new line "\n",
tab "\t"
• file (optional) - where the values are printed. It's default value is
sys.stdout (screen)
• flush (optional) - boolean specifying if the output is flushed or
buffered. Default: False
Example 1: Python Print Statement
Example 2: Python print() with end Parameter

Notice that we have included the end= ' ' after the end of the first print()
statement.
Hence, we get the output in a single line separated by space.
Example 3: Python print() with sep parameter

In the above example, the print() statement includes multiple items separated
by a comma.

Notice that we have used the optional parameter sep= ". " inside the print()
statement.
Output formatting
• Sometimes we would like to format our output to make it look
attractive.
• This can be done by using the str.format() method. For example

Here, the curly braces {} are used as placeholders. We can specify the order in which they
are printed by using numbers (tuple index).
InputFunction

The input function does the following:


1. Displays a prompt for the input.
2. In this example, the prompt is "Enter a number : ".
2. Receives a string of keystrokes, called characters, entered at the keyboard
and returns the string to the shell.
Input Function
• The input function always builds a string from the user’s keystrokes
and returns it to the program.
• After inputting strings that represent numbers, the programmer
must convert them from strings to the appropriate numeric types.
• In Python, there are two type conversion functions for this purpose,
called int (for integers) and float (for floating point numbers).
• To convert user input into a number we can use int() or float()
functions as:
Example
• >>> first = int(input("Enter the first number: "))
• Enter the first number: 23
• >>> second = int(input("Enter the second number: "))
• Enter the second number: 44
• >>> print("The sum is", first + second)
• The sum is 67
Basic Python functions for input and output
Case Study: Income Tax Calculator
let’s assume the following tax laws:
• All taxpayers are charged a flat tax rate of 20%.
• All taxpayers are allowed a $10,000 standard deduction.
• For each dependent, a taxpayer is allowed an additional $2000
deduction.
• Gross income must be entered to the nearest penny.
• The income tax is expressed as a decimal number.
Case Study: Income Tax Calculator
Implementation (Coding)
The Main Module
• To differentiate this script from the other modules in a program (and there
could be many), we call it the main module.
• Like any module, the main module can also be imported. Instead of
launching the script from a terminal prompt or loading it into the shell from
IDLE, you can start Python from the terminal prompt and import the script
as a module.
• Let’s do that with the taxform.py script, as follows
• After importing a main module, you can view its documentation by running
• the help function:
Program Format and Structure
1. Start with an introductory comment stating the author’s name, the purpose
of the program, and other relevant information.

2. Then, include statements that do the following:

3. Import any modules needed by the program.

4. Initialize important variables, suitably commented.

5. Prompt the user for input data and save the input data in variables.

6. Process the inputs to produce the results.

7. Display the results.


UNIT-II
CONTROL STATEMENTS
Python if...else Statement
• In Python, there are three forms of the if...else
statement.

•if statement
•if...else statement
•if...elif...else statement
1. Python if statement
• The syntax of if statement in Python is:

• If condition is evaluated to True, the code inside the body of if is executed.


• If condition is evaluated to False, the code inside the body of if is skipped.
If else
• The if-else statement is the most common type of selection statement.
• It is also called a two-way selection statement, because it directs the
computer to make a choice between two alternative courses of action.
2. Python if...else Statement
• An if statement can have an optional else clause.
• The syntax of if...else statement is:

• If the condition evaluates to True,


• the code inside if is executed
• the code inside else is skipped

• If the condition evaluates to False,


• the code inside else is executed
• the code inside if is skipped
Multi-Way if Statements
The process of testing several conditions and responding accordingly can be
described in code by a multi-way selection statement.
Python if...elif...else Statement
• The if...else statement is used to execute a block of code among
two alternatives.
• However, if we need to make a choice between more than two
alternatives, then we use the if...elif...else statement.
• The syntax of the if...elif...else statement is:
• Here,
• If condition1 evaluates to True, code block 1 is executed.
• If condition1 evaluates to False, then condition2 is evaluated.
• If condition2 is True, code block 2 is executed.
• If condition2 is False, code block 3 is executed.
Example
Example
Python Nested if statement
• We can also use an if statement inside of an if statement. This is known as a
nested if statement.
• The syntax of nested if statement is:
• Note:
• We can add else and elif statements to the inner if
statement as required.
• We can also insert inner if statement inside the
outer else or elif statements(if they exist)
• We can nest multiple layers of if statements.
Sample Program
• Calculate the student's grade based on the results of five subjects.
• Based on marks obtained in N number of subjects
• The grade must be calculated as per the following rules:
Average Mark Grade
91-100 A1
81-90 A2
71-80 B1
61-70 B2
51-60 C1
41-50 C2
33-40 D
21-32 E1
0-20 E2
Sample Program
• This program finds and prints the grade of a student based on marks
obtained in five subjects entered by the user at run-time.
• To calculate the grade of students in Python, you have to ask the user to
enter marks obtained in five subjects.
• Now calculate the sum of all the marks and then calculate the average
marks to find the grade according to the average marks obtained by the
student, as shown in the program given below:
Python Switch Statement – Switch Case Example
• Until version 3.10, Python never had a feature that implemented what
the switch statement does in other programming languages.
• So, if you wanted to execute multiple conditional statements, you
would've had to use the elif keyword like this
Using a function and the elif keyword was one of them
and you can do it this way:
Implement Switch Statements with the match and
case Keywords
• To write switch statements with the structural pattern matching feature,
you can use the syntax below:

Note that the underscore symbol is what you


use to define a default case for the switch
statement in Python.
Example:
Short-Circuit Evaluation
• The Python virtual machine sometimes knows the value of a Boolean
expression before it has evaluated all of its parts.

• For instance, in the expression (A and B), if A is false, then so is the


expression, and there is no need to evaluate B.

• Likewise, in the expression (A or B), if A is true, then so is the expression, and


again there is no need to evaluate B.

• This approach, in which evaluation stops as soon as possible, is called short-


circuit evaluation
Consider the following example:

If the user enters 0 for the count, the condition contains a potential
division by zero; however, because of short-circuit evaluation the
division by zero is avoided
Definite Iteration: The for Loop
There are two types of loops—
• those that repeat an action a predefined number of times (definite
iteration)
• those that perform the action until the program determines that it needs
to stop (indefinite iteration).
Python for Loop
• In Python, the for loop is used to run a block of code for a certain number
of times.
• It is used to iterate over any sequences such as list, tuple, string, etc
• The syntax of the for loop is:

• Here, val accesses each item of sequence on each iteration.


• Loop continues until we reach the last item in the sequence.
• In the above example, we have created a list called languages.

• Initially, the value of language is set to the first element of the array, i.e. Swift,
so the print statement inside the loop is executed.

• language is updated with the next element of the array and the print statement
is executed again.
• This way the loop runs until the last element of an array is accessed.
Python for Loop with Python range()

• The first line of code in a loop is sometimes called the loop header.
• The colon (:) ends the loop header.
• The loop body comprises the statements in the remaining lines of code, below
the header.
Python for Loop with Python range()
• A range is a series of values between two numeric intervals.
• We use Python's built-in function range() to define a range of values. For
example,
Example
Count-Controlled Loops
Loops that count through a range of numbers are also called count-controlled
loops
• To count from an explicit lower bound, the programmer can supply a
second integer expression in the loop header.
• When two arguments are supplied to range, the count ranges from the
first argument to the second argument minus 1.
Example
Loop Errors: Off-by-One Error
• The loop fails to perform the expected number of iterations. Because
this number is typically off by one, the error is called an off-by-one
error.

Note that this is not a syntax error, but rather a logic error. Unlike syntax errors, logic errors
are not detected by the Python interpreter, but only by the eyes of a programmer who
carefully inspects a program’s output
Traversing the Contents of a Data Sequence
• In this example, the sequence of numbers generated by the function range is
fed to Python’s list function, which returns a special type of sequence called
a list.
• >>> list(range(4))
• [0, 1, 2, 3]
• >>> list(range(l, 5))
• [1, 2, 3, 4]
• Strings are also sequences of characters. The values contained in any
sequence can be visited by running a for loop, as follows:
Specifying the Steps in the Range
• Python’s range functions expects a third argument that allows you to
nicely skip some numbers.
• The third argument specifies a step value, or the interval between the
numbers used in the range, as shown in the examples that follow:
Loops That Count Down
• All of our loops until now have counted up from a lower bound to an
upper bound.
• suppose for counting in the opposite direction, from the upper bound
down to the lower bound
Formatting Text for Output
• Many data-processing applications require output that has a tabular format,
like that used in spreadsheets or tables of numeric data.
• In this format, numbers and other information are aligned in columns that
can be either left-justified or right-justified.
• A column of data is left-justified if its values are vertically aligned beginning
with their leftmost characters.
• A column of data is right-justified if its values are vertically aligned
beginning with their rightmost characters.
• To maintain the margins between columns of data, left-justification requires
the addition of spaces to the right of the datum, whereas right-justification
requires adding spaces to the left of the datum.
• A column of data is centered if there are an equal number of spaces on
either side of the data within that column
Formatting Text for Output
• The total number of data characters and additional spaces for a given
datum in a formatted string is called its field width.
• The print function automatically begins printing an output datum in
the first available column.
• The next example, which displays the exponents 7 through 10 and the
values of 10^7 through 10^10, shows the format of two columns
produced by the print function
• Python includes a general formatting mechanism that allows the programmer
to specify field widths for different types of data.
• shows how to right-justify and left-justify the string “four” within a field width
of 6:

• The first line of code right-justifies the string by padding it with two spaces to
its left.
• The next line of code left-justifies by placing two spaces to the string’s right
• The simplest form of

• When the field width is positive, the datum is right-justified; when the field
width is negative, you get left-justification.
• If the field width is less than or equal to the datum’s print length in characters,
no justification is added.
• The % operator works with this information to build and return a formatted
string.
• The format information for a data value of type float has the
form:

• where .<precision> is optional


Python for loop with else
• A for loop can have an optional else block as well.
• The else part is executed when the loop is finished.
• For example,
Python while Loop
• Python while loop is used to run a specific code until a certain condition is met.
• The syntax of while loop is:
Example
Count Control with a while Loop
The while True Loop and the break Statement
• Our next example modifies the input section of the grade-conversion
program to continue taking input numbers from the user until she
enters an acceptable value.
• The logic of this loop is similar to that of the previous example.
Random Numbers
• Python’s random module supports several ways to do this, but the
easiest is to call the function random.randint with two integer
arguments.
• The function random.randint returns a random number from among
the numbers between the two arguments and including those numbers.
Random Numbers
• We can now use random.randint, selection, and a loop to develop a simple
guessing game.
• At start-up, the user enters the smallest number and the largest number in
the range. The computer then selects a number from this range. On each
pass through the loop, the user enters a number to attempt to guess the
number selected by the computer.
• The program responds by saying “You’ve got it,” “Too large, try again,” or
“Too small, try again.”
• When the user finally guesses the correct number, the program congratulates
him and tells him the total number of guesses.
• Here is the code, followed by a sample run:
Infinite while Loop in Python
• If the condition of a loop is always True, the loop runs for infinite times
(until the memory is full). For example,
Python While loop with else
• A while loop can have an optional else block as well.
• The else part is executed after the condition in the while loop evaluates to
False. For example,
Python break and continue
• The break statement is used to terminate the loop immediately when it is
encountered.

• The syntax of the break statement is:


• break
Python break Statement with for Loop
• We can use the break statement with the for loop to terminate the loop when
a certain condition is met. For example,

Here, when i is equal to 3, the break statement terminates the


loop. Hence, the output doesn't include values after 2.
Python break Statement with while Loop
• We can also terminate the while loop using the break statement. For
example,
Python continue Statement
• The continue statement is used to skip the current iteration of the loop
and the control flow of the program goes to the next iteration.
• The syntax of the continue statement is:
Python continue Statement with for Loop
• We can use the continue statement with the for loop to skip the current
iteration of the loop.
• Then the control of the program jumps to the next iteration. For example,

Here, when i is equal to 3, the continue statement is executed.


Hence, the value 3 is not printed to the output.
Python continue Statement with while Loop
In Python, we can also skip the current iteration of the while loop
using the continue statement. For example,
Python pass Statement
• In Python programming, the pass statement is a null statement which can
be used as a placeholder for future code.
• Suppose we have a loop or a function that is not implemented yet, but
we want to implement it in the future.
• In such cases, we can use the pass statement. The syntax of the pass
statement is:
Python Functions compile() Returns the specified source as an object,
Function Description ready to be executed
abs() Returns the absolute value of a complex() Returns a complex number
number delattr() Deletes the specified attribute (property or
all() Returns True if all items in an method) from the specified object
iterable object are true dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's
any() Returns True if any item in an properties and methods
iterable object is true
divmod() Returns the quotient and the remainder
ascii() Returns a readable version of an when argument1 is divided by argument2
object. Replaces none-ascii enumerate() Takes a collection (e.g. a tuple) and returns it
characters with escape character as an enumerate object
bin() Returns the binary version of a eval() Evaluates and executes an expression
number exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an
bool() Returns the boolean value of the iterable object
specified object
float() Returns a floating point number
bytearray() Returns an array of bytes format() Formats a specified value
bytes() Returns a bytes object frozenset() Returns a frozenset object
callable() Returns True if the specified object getattr() Returns the value of the specified attribute
(property or method)
is callable, otherwise False
globals() Returns the current global symbol table as a
chr() Returns a character from the dictionary
specified Unicode code. hasattr() Returns True if the specified object has the
classmethod() Converts a method into a class specified attribute (property/method)
method hash() Returns the hash value of a specified object
Python Functions
id() Returns the id of an object pow() Returns the value of x to the power of y
input() Allowing user input print() Prints to the standard output device
int() Returns an integer number property() Gets, sets, deletes a property
isinstance() Returns True if a specified object is an range() Returns a sequence of numbers, starting
instance of a specified object from 0 and increments by 1 (by default)
issubclass() Returns True if a specified class is a repr() Returns a readable version of an object
subclass of a specified object
reversed() Returns a reversed iterator
iter() Returns an iterator object
round() Rounds a numbers
len() Returns the length of an object
set() Returns a new set object
list() Returns a list
setattr() Sets an attribute (property/method) of an
locals() Returns an updated dictionary of the object
current local symbol table
slice() Returns a slice object
map() Returns the specified iterator with the
specified function applied to each item sorted() Returns a sorted list

max() Returns the largest item in an iterable staticmethod() Converts a method into a static method

memoryview() Returns a memory view object str() Returns a string object

min() Returns the smallest item in an iterable sum() Sums the items of an iterator

next() Returns the next item in an iterable super() Returns an object that represents the
parent class
object() Returns a new object
tuple() Returns a tuple
oct() Converts a number into an octal
type() Returns the type of an object
open() Opens a file and returns a file object
vars() Returns the __dict__ property of an object
ord() Convert an integer representing the
Unicode of the specified character zip() Returns an iterator, from two or more
iterators
pow() Returns the value of x to the power of y
Python Functions
• A function is a block of code that performs a specific task.

• Dividing a complex problem into smaller chunks makes our program


easy to understand and reuse.
Types of function

• There are two types of function in Python programming:

• Standard library functions - These are built-in


functions in Python that are available to use.
• User-defined functions - We can create our own
functions based on our requirements.
Python Function Declaration
• The syntax to declare a function is:

• Here,
• def - keyword used to declare a function
• function_name - any name given to the function
• arguments - any value passed to function
• return (optional) - returns value from a function
Calling a Function in Python
• In the above example, we have declared a function named greet()
• Now, to use this function, Here's how we can call the greet() function
in Python. we need to call it.

• Here's how we can call the greet() function in Python.


Example: Python Function

Here,
• When the function is called, the control of the program goes to
the function definition.
• All codes inside the function are executed.
• The control of the program jumps to the next statement after
the function call.
Python Function Arguments
• As mentioned earlier, a function can also have arguments.
• An argument is a value that is accepted by a function. For example,

If we create a function with arguments, we need to pass the corresponding values while
calling them. For example,
Example 1: Python Function Arguments

In the above example, we have created a function named add_numbers() with arguments:
num1 and num2.
We can also call the function by mentioning the argument
name as:
The return Statement in Python
• A Python function may or may not return a value.
• If we want our function to return some value to a function call, we
use the return statement. For example,
Example 2: Function return Type
Python Library Functions
• In Python, standard library functions are the built-in functions that can
be used directly in our program.
• For example,
• print() - prints the string inside the quotation marks
• sqrt() - returns the square root of a number
• pow() - returns the power of a number
• These library functions are defined inside the module. And, to use them
we must include the module inside our program.

• For example, sqrt() is defined inside the math module.


Example 4: Python Library Function

Output
Example 1: Python Function Arguments

In the above example, the function add_numbers() takes two parameters: a and
b. Notice the line,
Function Argument with Default Values
• In Python, we can provide default values to function arguments.
• We use the = operator to provide default values. For example,
Python Keyword Argument

• In keyword arguments, arguments are assigned based on the name of


arguments. For example,
Python Function With Arbitrary Arguments
• Sometimes, we do not know in advance the number of arguments
that will be passed into a function. To handle this kind of situation, we
can use arbitrary arguments in Python.

• Arbitrary arguments allow us to pass a varying number of values


during a function call.

• We use an asterisk (*) before the parameter name to denote this kind
of argument. For example,
Python Recursion
• Recursion is the process of defining something in terms of itself.
Python Recursive Function
• In Python, we know that a function can call other functions. It is even
possible for the function to call itself. These types of construct are
termed as recursive functions.

• The following image shows the working of a recursive function called


recurse.
Python Recursive Function
• Following is an example of a recursive function to find the factorial of
an integer.
• Factorial of a number is the product of all the integers from 1 to that
number. For example, the factorial of 6 (denoted as 6!) is
1*2*3*4*5*6 = 720.
• When we call this function with a positive integer, it will recursively call
itself by decreasing the number.
• Each function multiplies the number with the factorial of the number
below it until it is equal to one. This recursive call can be explained in
the following steps.
• Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.
• The Python interpreter limits the depths of recursion to help avoid infinite
recursions, resulting in stack overflows.
• By default, the maximum depth of recursion is 1000. If the limit is crossed,
it results in RecursionError. Let's look at one such condition.
Advantages of Recursion
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-problems using
recursion.
• Sequence generation is easier with recursion than using some nested
iteration.
• Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
• Recursive functions are hard to debug.
Python Lambda/Anonymous Function
• In Python, a lambda function is a special type of function without the
function name. For example,

• Here, we have created a lambda function that prints 'Hello World'.


Python lambda Function Declaration
• We use the lambda keyword instead of def to create a lambda function.
Here's the syntax to declare the lambda function:

Here,
argument(s) - any value passed to the lambda function
expression - expression is executed and returned

Here, we have defined a lambda function and assigned it to the variable named greet.
To execute this lambda function, we need to call it. Here's how we can call the lambda
function
Example: Python lambda Function
Python lambda Function with an Argument
• Similar to normal functions, the lambda function can also accept
arguments. For example,

In the above example, we have assigned a lambda function to the greet_user variable.

Here, name after the lambda keyword specifies that the lambda function accepts the argument named name.

Notice the call of lambda function,


How to use the lambda function with filter()?
• The filter() function in Python takes in a function and an iterable (lists,
tuples, and strings) as arguments.

• The function is called with all the items in the list and a new list is
returned which contains items for which the function evaluates to
True.
How to use the lambda function with map()?
• The map() function in Python takes in a function and an iterable (lists,
tuples, and strings) as arguments.

• The function is called with all the items in the list and a new list is
returned which contains items returned by that function for each
item.

• Let's see an example,


Python Variable Scope
• In Python, we can declare variables in three different scopes: local
scope, global, and nonlocal scope.

• A variable scope specifies the region where we can access a variable.


For example,
• Based on the scope, we can classify Python variables into three types:

• Local Variables
• Global Variables
• Nonlocal Variables
Python Local Variables
• When we declare variables inside a function, these variables will have
a local scope (within the function). We cannot access them outside
the function.
• These types of variables are called local variables. For example,
Python Global Variables
• In Python, a variable declared outside of the function or in global scope
is known as a global variable.
• This means that a global variable can be accessed inside or outside of
the function.
Python Nonlocal Variables
• In Python, nonlocal variables are used in nested functions whose local
scope is not defined.
• This means that the variable can be neither in the local nor the global
scope

In the above example, there is a nested inner() function. We


have used the nonlocal keywords to create a nonlocal variable.

The inner() function is defined in the scope of another


function outer()

Note : If we change the value of a nonlocal variable, the


changes appear in the local variable.
Python Global Keyword
• In Python, the global keyword allows us to modify the variable
outside of the current scope.
• It is used to create a global variable and make changes to the variable
in a local context.
Access and Modify Python Global Variable

This is because we can only access the global variable but cannot modify it from inside the
function.

The solution for this is to use the global keyword.


Example: Changing Global Variable From Inside
a Function using global

In the above example, we have defined c as the global keyword


inside add().

Then, we have incremented the variable c by 2, i.e c = c + 2.


Global in Nested Functions
In the above example, we declared a global variable inside the
nested function inner_function().

Inside outer_function(), num has no effect of the global


keyword.

Before and after calling inner_function(), num takes the value


of the local variable i.e num = 20.

Outside of the outer_function() function, num will take the


value defined in the inner_function() function i.e x = 25.

This is because we have used the global keyword in num to


create a global variable inside the inner_function() function
(local scope).

So, if we make any changes inside the inner_function()


function, the changes appear outside the local scope, i.e.
outer_function().
Rules of global Keyword
• The basic rules for global keyword in Python are:

• When we create a variable inside a function, it is local by default.


• When we define a variable outside of a function, it is global by default.
You don't have to use the global keyword.
• We use the global keyword to read and write a global variable inside a
function.
• Use of the global keyword outside a function has no effect.
• A package is a container that contains various functions to perform specific
tasks. For example, the math package includes the sqrt() function to
perform the square root of a number.

• While working on big projects, we have to deal with a large amount of


code, and writing everything together in the same file will make our code
look messy. Instead, we can separate our code into multiple files by
keeping the related code together in packages.

• Now, we can use the package whenever we need it in our projects. This
way we can also reuse our code.
Importing module from a package
• In Python, we can import modules from packages using the dot (.)
operator.

• For example, if we want to import the start module in the above


example, it can be done as follows:

• Now, if this module contains a function named select_difficulty(), we


must use the full name to reference it.
Import Without Package Prefix
• If this construct seems lengthy, we can import the module without
the package prefix as follows:

• We can now call the function simply as follows:


Strings and Text Files - UNIT3
• A string is a sequence of zero or more characters
• The string is an immutable data structure. This means that its internal data
elements, the characters, can be accessed, but cannot be replaced, inserted,
or removed.
• Fig illustrates the sequence of characters and their positions in the string "Hi
there!". Note that the ninth and last character, '!', is at position 8.
The Subscript Operator
• To inspect one character at a given position we can use the subscript
operator [ ] .
• The simplest form of the subscript operation is the following:
• In the following examples, the subscript operator is used to access
characters in the string "Alan Turing":

Note that attempting to access a character using a position that equals the string’s length
results in an error.
The positions usually range from 0 to the length minus 1
• The subscript operator is also useful in loops where you want to use the
positions as well as the characters in a string.
• The next code segment uses a count-controlled loop to display the characters
and their positions:
Slicing for Substrings
• Python’s subscript operator to obtain a substring through a process called
slicing.
• To extract a substring, the programmer places a colon (:) in the subscript. An
integer value can appear on either side of the colon. Here are some examples
that show how slicing is used
String Methods
• Let’s start with counting the words in a single sentence and finding the
average word length.
• This task requires locating the words in a string.
• Python includes a set of string operations called methods that make tasks
like this one easy.
Python String Operations
1. Compare Two String
• We use the == operator to compare two strings. If two strings are equal,
the operator returns True. Otherwise, it returns False. For example,
• 2. Join Two or More Strings
• In Python, we can join (concatenate) two or more strings using the +
operator.
Iterate through a Python String
Python String Length
• In Python, we use the len() method to find the length of a string. For
example,
String Membership Test
• We can test if a substring exists within a string or not, using the
keyword in.
String Methods

In Python, a method is a function that is


defined with respect to a particular object.
Syntax:

object.method(arguments)
For Example: the first position
>>>name=“Classic” where “s” appears
>>>name.find(“s”)
3
String object String Method Method Argument
Methods of Python String
• Besides those mentioned above, there are various string methods
present in Python.
• Here are some of those methods:
Testing for a Substring with the in Operator
• For example, you might want to pick out filenames with a .txt extension.
• A slice would work for this, but using Python’s in operator is much simpler.
When used with strings, the left operand of in is a target substring, and the
right operand is the string to be searched.
• The operator in returns True if the target string is somewhere in the search
string, or False otherwise.
• The next code segment traverses a list of filenames and prints just the
filenames that have a .txt extension:
Data Encryption
• A very simple encryption method that has been in use for
thousands of years is called a Caesar cipher.
• The Caesar Cipher technique is one of the earliest and simplest
methods of encryption technique.
• It’s simply a type of substitution cipher, i.e., each letter of a given
text is replaced by a letter with a fixed number of positions down
the alphabet. For example with a shift of 1, A would be replaced by
B, B would become C, and so on.
• This encryption strategy replaces each character in the plaintext with
the character that occurs a given distance away in the sequence.
The formula of encryption is: En ( X ) = ( X i + n) mod 26

The formula of decryption is: Dn ( X ) = ( X i − n) mod 26

If any case D value becomes negative (-ve), in this case,


n

we will add 26 in the negative value.


Where,
E denotes the encryption
n

D denotes the decryption


n

x denotes the letters value


n denotes the key value (shift value)
Use the Caesar cipher to encrypt and decrypt the message "JAVA" and the key
(shift) value of this message is 3.
• The formula of encryption is:
En ( X ) = ( X i + n) mod 26

The encrypted message is "MDYD”


Decryption
We apply decryption formulas by character, based on alphabetical order.

The formula of decryption is: Dn ( X ) = ( X i − n) mod 26


Python’s ord and chr functions convert characters to
their numeric ASCII codes and back again, respectively
Strings and Number Systems
• When you perform arithmetic operations, you use the decimal number
system.

• This system, also called the base ten number system, uses the ten characters
0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 as digits

• The two digits in this base two number system are 0 and 1.

• Because binary numbers can be long strings of 0s and 1s, computer


scientists often use other number systems, such as octal (base eight) and
hexadecimal (base 16) as shorthand for these number
Strings and Number Systems
• For example, the following numbers represent the quantity 41510 in the
binary, octal, decimal, and hexadecimal systems:
• 415 in binary notation 1100111110
• 415 in octal notation 6378
• 415 in decimal notation 41510
• 415 in hexadecimal notation 19F16
• The digits used in each system are counted from 0 to n – 1, where n is the
system’s base.
• Thus, the digits 8 and 9 do not appear in the octal system.
• To represent digits with values larger than 9,10, systems such as base 16
use letters.
• Thus, A16 represents the quantity 1010, whereas 1016 represents the
quantity 1610.
Converting Binary to Decimal
• The input to the script is a string of bits, and its output is the integer that
the string represents.
• The algorithm uses a loop that accumulates the sum of a set of integers.
• The sum is initially 0.
• The exponent that corresponds to the position of the string’s leftmost bit is
the length of the bit string minus 1.
• The loop visits the digits in the string from the first to the last (left to right),
but counts from the largest exponent of 2 down to 0 as it goes.
• Each digit is converted to its integer value (1 or 0), multiplied by its
positional value, and the result is added to the ongoing total.
• A positional value is computed by using the ** operator.
Converting Decimal to Binary
How are integers converted from decimal to binary?
• One algorithm uses division and subtraction instead of multiplication and
addition.
• This algorithm repeatedly divides the decimal number by 2.
• After each division, the remainder (either a 0 or a 1) is placed at the
beginning of a string of bits.
• The quotient becomes the next dividend in the process.
• The string of bits is initially empty, and the process continues while the
decimal number is greater than 0.

You might also like