Python Material
Python Material
Python Material
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 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
The language founded in the year 1991 by the developer Guido Van
Rossum has the programming easy and fun to do.
INTRODUCTION
• 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
• With the added features, now the companies are using Python 3.5.
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?
✓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 Shell?
1) Script and
2) Interactive.
PYTHON BASIC MODES
1) Script Mode:
2) Interactive Mode
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.
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
Exponent
Fractional Form
Notation
Floating
Point
Numbers
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,
• 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.
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
1. Indexing
We can use the index operator [] to access an item in a tuple, where the
index starts from 0.
2. Negative Indexing
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.
• 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.
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
>>>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
• 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.
• In a dictionary we can only test for presence of key, not the value.
<< 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
==, !=, >, >=, <, <=, 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.
• 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.
• The Python shell itself is such a program; its inputs are Python expressions or
statements.
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
5. Prompt the user for input data and save the input data in variables.
•if statement
•if...else statement
•if...elif...else statement
1. Python if statement
• The syntax of if statement in Python is:
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:
• 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:
max() Returns the largest item in an iterable staticmethod() Converts a method into a static method
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.
• 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,
• 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.
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
• 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.
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.
• 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.
• 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
This is because we can only access the global variable but cannot modify it from inside the
function.
• 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.
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
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
• 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.