Chapter 2
Chapter 2
Chapter 2
Introduction to Python
12/2/2024
History of Python
Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer
Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C,
C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
Smalltalk is considered as the first truly object-oriented programming
language.
Python is copyrighted. Like Perl, Python source code is now available under
the free and open source General Public License (GPL).
Python is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its progress.
Python is a high-level, general-purpose, and very popular programming
language.
Python is currently the most widely used multi-purpose, high-level
programming language, which allows programming in Object-Oriented and
Procedural paradigms.
1 12/2/2024
Introduction to python
This Python tutorial has been written for the beginners to help them
understand the basic to advanced concepts of Python Programming
Language.
What is Python?
is a very popular general-purpose interpreted, interactive, object-
oriented, and high-level programming language.
Python is dynamically-typed and garbage-collected programming
language.
It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the free and open source
General Public License (GPL).
It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other
languages.
2 12/2/2024
Cont…
Python supports multiple programming paradigms, including
Procedural, Object Oriented and Functional programming
language.
Python design philosophy emphasizes code readability with the use of
significant indentation
Python Jobs
python is very high in demand and all the major companies are looking
for great Python Programmers to develop websites, software
components, and applications or to work with Data Science, AI,
and ML technologies. t's impossible to list all of the companies using
Python, to name a few big companies are:
Example:- Google, NASA, Facebook, IBM, Amazon, Uber
2 12/2/2024
key advantages of learning Python:
5 12/2/2024
Python Online Compiler/Interpreter
Python Online Compiler/Interpreter which helps you to Edit and Execute
the code directly from your browser.
Below code box allows you to change the value of the code. Try to change
the value inside print() and run it again to verify the result.
# This is my first Python program.
# This will print 'Hello, World!' as the output
print ("Hello, World!");
Here are just a few of the career options where Python is a key
skill:
Game developer, Web designer, Python developer, Full-stack
developer, Machine learning engineer, Data scientist, Data
analyst
Data engineer
DevOps engineer
Software engineer
6 12/2/2024
Following are important characteristics of Python
Programming
7 12/2/2024
Why to Learn Python?
It is consistently rated as one of the world's most popular programming
languages.
There are many other good reasons which makes Python as the top
choice of any programmer:
Python is Open Source which means its available free of cost.
3 12/2/2024
Applications/ Features of Python
Easy-to-learn − Python has few keywords, simple structure, and a
clearly defined syntax.
Easy-to-read − Python code is more clearly defined and visible to the
eyes.
Easy-to-maintain − source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
Interactive Mode − support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − run on a wide variety of HW platforms and has the same
interface on all platforms.
9 12/2/2024
Cont…
Extendable −You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial
databases.
GUI Programming − Python supports GUI applications that can be
created and ported to many system calls, libraries and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
Scalable − Python provides a better structure and support for
large programs than shell scripting.
10 12/2/2024
Python - Environment Setup
Python is available on a wide variety of platforms including Linux and
Mac OS X.
Python has also been ported to the Java and .NET virtual machines
Installing Python
Python distribution is available for a wide variety of platforms.You
need to download only the binary code applicable for your platform
and install Python.
If the binary code for your platform is not available, you need a C
compiler to compile the source code manually. Compiling the source
code offers more flexibility in terms of choice of features that you require
in your installation.
11 12/2/2024
Windows Installation
Here are the steps to install Python on Windows machine.
Open a Web browser and go to
https://www.python.org/downloads/.
Follow the link for the Windows installer python-XYZ.msi file where
XYZ is the version you need to install.
Run the downloaded file. This brings up the Python install wizard,
which is really easy to use. Just accept the default settings, wait until
the install is finished, and you are done.
12 12/2/2024
Setting path at Windows
To add the Python directory to the path for a particular
session in Windows −
13 12/2/2024
Python Environment Variables
14 12/2/2024
Integrated Development Environment
You can run Python from a Graphical User Interface (GUI) environment as well, if
you have a GUI application on your system that supports Python.
Unix − Integrated Development and Learning Environment (IDLE) is the very
first Unix IDE for Python.
Windows − Python Win is the first Windows interface for Python and is an IDE
with a GUI.
Macintosh − The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.
We have provided Python Online Compiler/Interpreter which helps you to
Edit and Execute the code directly from your browser. Try to click the icon run
button to run the following Python code to print conventional "Hello, World!".
# This is my first Python program.
# This will print 'Hello, World!' as the output
print ("Hello, World!")
The print() function prints a message on the screen.
15 12/2/2024
Cont..
Python has a free integrated development environment known as
IDLE. IDLE stands for Integrated Development and Learning
Environment. To write Python codes, the interactive interpreter
or the text editor of the IDLE can be used.
The interactive interpreter is used to write one line of Python code
at a time and is less convenient to write and execute a large
number of codes. Using the text editor, however, any
number of codes can be written and get executed with a single
command.
16 12/2/2024
Cont..
Programs normally accept input and process the input to produce an
output. The print() function is used to produce output on the IDLE
shell. As shown in multiple examples in the preceding sections, the
print() function has the following syntax:
print([value])
A function is a piece of code that performs some task and is called by
its name. It can be passed data as input to operate on, and can optionally
return data as output. print(), input() and type() are examples of
functions.
17 12/2/2024
Cont..
18 12/2/2024
Python - Basic Syntax
The Python syntax defines a set of rules that are used to create Python
statements while writing a Python Program.
The Python Programming Language Syntax has many similarities to Perl,
C, and Java Programming Languages. However, there are some definite
differences between the languages.
Python - Interactive Mode Programming
We can invoke a Python interpreter from command line by typing
python at the command prompt as following −
In Python, >>> is the prompt that indicates the interactive interpreter is
ready to accept commands.
Let's type the following text at the Python prompt and press
the Enter −
>>> print ("Hello, World!")
19 12/2/2024
Cont..
If you are running older version of Python, like Python 2.4.x, then you
would need to use print statement without parenthesis as in print
"Hello, World!". However in Python version 3.x, this produces the following
result − Hello, World!
Python - Script Mode Programming
We can invoke the Python interpreter with a script parameter
which begins the execution of the script and continues until the
script is finished. When the script is finished, the interpreter is no
longer active.
Let us write a simple Python program in a script which is simple text
file. Python files have extension .py. Type the following source code in a
test.py file −
20 12/2/2024
Python Identifiers
A Python identifier is a name used to identify a Variable, Function,
Class, Module or other Object.
In Python, modules are simply files that contain Python code. A
module can define functions, classes, and variables, and it can also include
runnable code.
An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and %
within identifiers.
Python is a case sensitive programming language. Thus,
Manpower and manpower are two different identifiers in Python.
21 12/2/2024
Here are naming conventions for Python identifiers −
Python Class names start with an uppercase letter.
All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that
the identifier is private identifier.
In Python, a single leading underscore (_) before an identifier
(such as a variable or method name) is a convention that indicates that
the identifier is intended for internal use.
Starting an identifier with two leading underscores indicates a
strongly private identifier.
In Python, a strongly private identifier is indicated by using a
double leading underscore (__).
If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
22 12/2/2024
Cont…
# Valid Identifiers
my_variable = 10
MyVariable = 20
_variable = 30
variable1 = 40
# Using the identifiers in the program
print(my_variable) # Output: 10
print(MyVariable) # Output: 20
print(_variable) # Output: 30
print(variable1) # Output: 40
# Invalid Identifiers
1st_variable = 50 # Invalid: cannot start with a digit
my-variable = 60 # Invalid: hyphen is not allowed
class = 70 # Invalid: 'class' is a reserved keyword
total sum = 80 # Invalid: space is not allowed
23 12/2/2024
# Uncommenting the invalid identifiers will raise a SyntaxError
Python Reserved Words
The following list shows the Python keywords.These are
reserved words and you cannot use them as constant or
variable or any other identifier names. All the Python keywords
contain lowercase letters only.
24 12/2/2024
Python Lines and Indentation
Python programming provides no braces to indicate blocks of code
for class and function definitions or flow control. Blocks of code
are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
For example −
25 12/2/2024
Cont..
Thus, in Python all the continuous lines indented with same
number of spaces would form a block. The following example has
various statement blocks −
Do not try to understand the logic at this point of time. Just
make sure you understood various blocks even if they are without
braces.
Python Multi-Line Statements
Statements in Python typically end with a new line. Python does,
however, allow the use of the line continuation character (\) to
denote that the line should continue. For example −
In Python, the line continuation character is the backslash \. It is used
to continue a logical line of code across multiple physical lines.
26 12/2/2024
Cont..
Statements contained within the [], {}, or () brackets do not need
to use the line continuation character. For example following
statement works well in Python −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday’]
Quotations in Python
Python accepts single ('), double (") and triple (''' or """) quotes
to denote string literals, as long as the same type of quote starts
and ends the string. The triple quotes are used to span the string across
multiple lines. For example, all the following are legal −
27 12/2/2024
Comments in Python
A comment is a programmer-readable explanation or
annotation in the Python source code.
They are added with the purpose of making the source code easier
for humans to understand, and are ignored by Python interpreter
Just like most modern languages, Python supports single-line (or end-
of-line) and multi-line (block) comments.
Python comments are very much similar to the comments available in
PHP, BASH and Perl Programming languages.
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.
28 12/2/2024
Cont..
comments enhance the readability of the code and help the
programmers to understand the code very carefully.
There are three types of comments available in Python
Single line Comments
Multiline Comments
Docstring Comments
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are part of
the comment and the Python interpreter ignores them.
Following is an example of a single line comment in Python:
29 12/2/2024
Cont.
Python does not provide a direct way to comment multiple line.
You can comment multiple lines as follows −
Following triple-quoted string is also ignored by Python
interpreter and can be used as a multiline comments:
30 12/2/2024
Docstring Comments
Docstring comments are used to provide documentation for
functions, classes, modules and Method. They are enclosed in
triple quotes (''' ''') and are accessible through the `__doc__`
attribute of the object. Docstrings are used to describe the purpose,
usage, and parameters of the object..
31 12/2/2024
Cont…
You can type a comment on the same line after a statement or expression −
name = "Madisetti" # This is again comment
You can comment multiple lines as follows −
33 12/2/2024
Multiple Statement Groups as Suites
A group of individual statements, which make a single code block
are called suites in Python. Compound or complex statements,
such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate
with a colon ( : ) and are followed by one or more lines which make up
the suite. For example −
34 12/2/2024
Cont
In Python, multiple statement groups are referred to as "suites" or "blocks
of code". A suite is a collection of one or more statements that are
executed as a unit.
There are several constructs in Python that require a suite, such as:
Compound Statements:
if-else statements
for loops
while loops
try-except blocks
class and def definitions
Functions and Methods:
The body of a function or method is a suite.
Modules and Classes:
The top-level statements in a Python module or class are also
35 12/2/2024
considered a suite.
Python - Variables
Python variables are the reserved memory locations used to store values with in a
Python Program.
This means that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, Python interpreter allocates memory and decides
what can be stored in the reserved memory
Therefore, by assigning different data types to Python variables, you can store integers,
decimals or characters in these variables.
Creating Python Variables
Python variables do not need explicit declaration to reserve memory space
or you can say to create a variable. A Python variable is created
automatically when you assign a value to it. The equal sign (=) is used to
assign values to variables.
The operand to the left of the = operator is the name of the variable and
the operand to the right of the = operator is the value stored in the
variable. For example −
36 12/2/2024
Printing Python Variables
Once we create a Python variable and assign a value to it, we can print
it using print() function. Following is the extension of previous
example and shows how to print different variables in Python:
Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter,
miles, and name variables, respectively. When running the above
Python program, this produces the following result −
37 12/2/2024
Delete a Variable
You can delete the reference to a number object by using the del
statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del
statement. For example
del var
del var_a, var_b
The Following examples shows how we can delete a variable and if we
try to use a deleted variable then Python interpreter will throw an
error:
38 12/2/2024
Multiple Assignment
Python allows you to assign a single value to several variables
simultaneously which means you can create multiple variables at a
time. For example −
Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location.You can also
assign multiple objects to multiple variables. For example −
39 12/2/2024
Python Variable Names
Every Python variable should have a unique name like a, b, c.
A variable name can be meaningful like color, age, name etc.
There are certain rules which should be taken care while naming a
Python variable:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number or any special character
like $, (, * % etc.
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Python variable names are case-sensitive which means Name and
NAME are two different variables in Python.
Python reserved keywords cannot be used naming the variable.
40 12/2/2024
Cont.
Example the following are valid Python variable names:
41 12/2/2024
Python Local Variable
Python Local Variables are defined inside a function. We can not
access variable outside the function.
A Python functions is a piece of reusable code and you will learn
more about function in Python - Functions tutorial.
42 12/2/2024
Python - Data Types
Python Data Types are used to define the type of a variable. It
defines what type of data we are going to store in a variable.
The data stored in memory can be of many types. For example,
a person's age is stored as a numeric value and his or her
address is stored as alphanumeric characters.
Python has various built-in data types which we will discuss with
in this tutorial:
Numeric - int, float, complex
String - str
Sequence - list, tuple, range
Binary - bytes, bytearray, memoryview
Mapping - dict
Boolean - bool
Set - set, frozenset
None - NoneType
43 12/2/2024
Python Numeric Data Type
Python numeric data types store numeric values. Number
objects are created when you assign a value to them. For example −
44 12/2/2024
Examples Here are some examples of numbers −
Python allows you to use a lowercase l with long, but it is
recommended that you use only an uppercase L to avoid confusion
with the number 1. Python displays long integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point
numbers denoted by x + yj, where x and y are the real numbers and j
is the imaginary unit.
45 12/2/2024
Following is an example to show the usage of Integer, Float and
Complex numbers:
47 12/2/2024
Cont.
The values stored in a Python list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the beginning of the
list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition
operator. For example −
49 12/2/2024
Cont..
The following code is invalid with tuple, because we attempted
to update a tuple, which is not allowed. Similar case is possible
with lists −
Python Ranges:
Python range() is an in-built function in Python which returns a sequence of
numbers starting from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of
numbers. Following is the syntax of the function:
50 12/2/2024
Cont.
The Following Examples is a program which uses for loop to print
number
from 0 to 4 −
Now let's modify above program to print the number starting from 1
instead of 0:
Python Dictionary
Python dictionaries are kind of hash table type. They work like associative
arrays or and consist of key-value pairs. A dictionary key can be almost any
Python type hashes found in Perl , but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example −
51 12/2/2024
Cont.
52 12/2/2024
Python Boolean Data Types
Python Boolean type is one of built-in data types which represents one of the two values either
True or False. Python bool() function allows you to evaluate the value of any expression and
returns either True or False based on the expression.
Following is another program which evaluates the expressions and prints the return values:
53 12/2/2024
Python Data Type Conversion
Sometimes, you may need to perform conversions between the
built-in data types. To convert data between different Python
data types, you simply use the type name as a function.
Conversion to int
Following is an example to convert number, float and string into
integer data type:
54 12/2/2024
Conversion to string
example to convert number, float and string into string data type:
Data Type Conversion Functions: there are several built-in functions to perform
conversion from one data type to another. These functions return a new object representing
the converted value.
55 12/2/2024
Cont.
56 12/2/2024
Python - Operators
Python operators are the constructs which can manipulate the value of
operands. These are symbols used for the purpose of logical, arithmetic
and various other operations.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and
+ is called operator. In this tutorial, we will study different types of Python
operators.
Types of Python Operators
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
57 12/2/2024
Python Arithmetic Operators
are used to perform mathematical operations on numerical values.
These operations are Addition, Subtraction, Multiplication,
Division, Modulus, Exponents and Floor Division.
58 12/2/2024
Python Comparison Operators
compare the values on either sides of them and decide the relation
among them. They are also called relational operators. These operators
are equal, not equal, greater than, less than, greater than or equal to
and less than or equal to.
59 12/2/2024
Python Assignment Operators
are used to assign values to variables. These operators include simple
assignment operator, addition assign, subtraction assign,
multiplication assign, division and assign operators etc.
60 12/2/2024
Cont.
61 12/2/2024
Python Bitwise Operators
It works on bits and performs bit by bit operation. Assume if a =
60; and b = 13; Now in the binary format their values will be 0011
1100 and 0000 1101 respectively. Following table lists out the bitwise
operators supported by Python language with an example each in
those, we use the above two variables (a and b) as operands −
62 12/2/2024
Cont.
63 12/2/2024
Python Logical Operators
There are following logical operators supported by Python
language. Assume variable a holds 10 and variable b holds 20 then
64 12/2/2024
Python Identity Operators
Identity operators compare the memory locations of two
objects. There are two Identity operators explained below −
65 12/2/2024
Cont.
66 12/2/2024
67 12/2/2024