Python Ch-2_Notes
Python Ch-2_Notes
Introduction to python
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
Python is a general-purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
Python is an easy-to-learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
Python supports multiple programming patterns, including object-oriented and functional
or procedural programming styles.
Python makes development and debugging fast because no compilation step is included
in Python development, and the edit-test-debug cycle is very fast.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Python features
Python provides many useful features which make it popular and valuable from the other
programming languages.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute,
while Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a
time. The advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to
develop the software for several competing platforms by writing a program only once.
Python is freely available for everyone. It is freely available on its official website
www.python.org. The open-source means, "Anyone can download its source code without
paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter,
Kivy are the libraries which are used for developing the web application.
9) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line
by line like C,C++ Java. It makes easy to debug the code.
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language
into our code.
In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.
Suppose we are assigned integer value 15 to x, then we don't need to write int x = 15. Just
write x = 15.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautiful Soup,
Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python
provides many useful frameworks, and these are given below:
Django and Pyramid framework(Use for heavy applications)
Flask and Bottle (Micro-framework)
Plone and Django CMS (Advance Content management)
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute. This kind of application was more
popular in the old generation of computers.
Python provides many free library or module which helps to build the command-line apps.
The necessary IO libraries are used to read and write. It helps to parse argument and create
console help text out-of-the-box. There are also advance libraries that can develop
independent console apps.
4) Software Development
Python is useful for the software development process. It works as a support language and
can be used to build control and management, testing, etc.
SCons is used to build control.
Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
Round or Trac for bug tracking and project management.
6) Business Applications
Python is also used to build ERP and e-commerce systems:
Odoo is an all-in-one management software that offers a range of business
applications that form a complete suite of enterprise management applications.
Tryton is a three-tier high-level general purpose application platform.
Identifiers
Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that’s called identifier.
Rules for Writing Identifiers
There are some rules for writing Identifiers. But first you must know Python is case
sensitive. That means Name and name are two different identifiers in Python.
Here are some rules for writing Identifiers in python.
1. Identifiers can be combination of uppercase and lowercase letters, digits or an
underscore(_). So myVariable, variable_1, variable_for_print all are valid python
identifiers.
2. An Identifier cannot start with digit. So while variable1 is valid, 1variable is not valid.
3. We can’t use special symbols like !,#,@,%,$ etc in our Identifier.
4. Identifier can be of any length.
Check following variable names and indicate whether it is valid or invalid. SUMMER-
2022
i) _my_var = "IT"
ii) 16myvar="AHMedabad"
iii) iii) MYVAR = "computer2"
Define variable and mention rules for choosing name of variable.WINTER-2022
Variables
Variables are containers for storing data values.
A variable, as the name indicates is something whose value is changeable over time. In fact a
variable is a memory location where a value can be stored.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 7
Python Programming (UNIT-2) | 4311601
Later we can retrieve the value to use. But for doing it we need to give a variable name to
that memory location so that we can refer to it. That’s identifier, the variable name.
Declaring Variable and Assigning Values
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.
The equal (=) operator is used to assign value to a variable.
Example:
x=5
y = "John"
List out various data types in python. Explain any three data types with example.
WINTER-2022
Data types
Every value has a datatype, and variables can hold values.
Python is a powerfully composed language; consequently, we don't have to characterize the
sort of variable while announcing it. The interpreter binds the value implicitly to its type.
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
1. Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities
have a place with a Python Numbers datatype. Python offers the type() function to
determine a variable's data type.
Python supports three kinds of numerical data.
Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. Its worth has a place with int.
Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like 2.14j,
2.0 + 2.3j, etc.
Example:
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using single, double, or triple quotes.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python, Python" the operator * is referred to as
a repetition operator.
Example:
str = "string using double quotes"
print(str)
Output:
string using double quotes
2. List
Lists are used to store multiple items in a single variable.
Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
Example:
list1 = [1, "hi", "Python", 2]
print(type(list1)) #Checking type of given list
print (list1) #Printing the list1
O/P:
<class 'list'>
[1, 'hi', 'Python', 2]
3. Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this.
False can be represented by the 0 or the letter "F," while true can be represented by any value
that is not zero.
Example:
print(type(True))
print(type(False))
print(false)
O/P:
<class 'bool'>
Set
It is iterable, mutable(can change after creation), and has remarkable components. The
elements of a set have no set order; It might return the element's altered sequence.
Either a sequence of elements is passed through the curly braces and separated by a comma
to create the set or the built-in function set() is used to create the set. It can contain different
kinds of values.
Example:
set1 = set()
O/P:
List out arithmetic operations. Build python code which performs three arithmetic
operations. SUMMER-2022
Operators
The operator is a symbol that performs a specific operation between two operands, according
to one definition.
Python also has some operators, and these are given below –
1. Arithmetic operators
2. Comparison operators
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 12
Python Programming (UNIT-2) | 4311601
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are many
arithmetic operators. These operations are Addition, Subtraction, Multiplication, Division,
Modulus, Expoents and Floor Division.
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
Example:
a = 21
b = 10
# Addition
# Subtraction
# Multiplication
# Division
# Exponent
# Floor Division
O/P:
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
2.Comparison Operators
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.
Example
a=4
b=5
# Equal
# Not Equal
# Greater Than
# Less Than
O/P:
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
3.Assignment Operators
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.
= Assignment Operator a = 10
Example:
# Assignment Operator
a = 10
# Addition Assignment
a += 5
# Subtraction Assignment
a -= 5
# Multiplication Assignment
a *= 5
# Division Assignment
a /= 5
O/P:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 16
Python Programming (UNIT-2) | 4311601
a += 5 : 105
a -= 5 : 100
a *= 5 : 500
a /= 5 : 100.0
4. Bitwise Operators
Bitwise operator 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 −
a = 0011 1100
b = 0000 1101
--------------------------
<< Binary Left Shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off
>> Binary Right Shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
# Binary AND
# Binary OR
# Binary XOR
O/P:
a & b : 12
a | b : 61
a ^ b : 49
a >> 2 : 240
a >> 2 : 15
5. Logical Operators
There are following logical operators supported by Python language. Assume variable a
holds 10 and variable b holds 20 then
and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.
or Logical OR If any of the two operands are non-zero then condition becomes true. (a or b) is
true.
not Logical Used to reverse the logical state of its operand. Not(a and
NOT b) is false.
Example:
x=5
O/P:
True
6. Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below –
not in Evaluates to true if it does not finds a variable in the x not in y, here not in results
specified sequence and false otherwise. in a 1 if x is not a member of
sequence y.
Example:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 19
Python Programming (UNIT-2) | 4311601
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
else:
if ( b not in list ):
else:
O/P:
7. Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below –
is not Evaluates to false if the variables on either side of the x is not y, here is
operator point to the same object and true otherwise. not results in 1 if id(x) is
not equal to id(y).
Example:
a = 20
b = 20
if ( a is b ):
else:
if ( id(a) == id(b) ):
else:
O/P:
Develop python code which calculate the value of c using equation c=a/b. Apply explicit
type conversion, Take a=50 and b=2.7 SUMMER-2022
Type Conversion
Python defines type conversion functions to directly convert one data type to another which
is useful in day-to-day and competitive programming.
In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement. To get a more clear view of
the topic see the below examples.
Example:
x = 10
print("x is of type:",type(x))
y = 10.6
z=x+y
print(z)
print("z is of type:",type(z))
O/P:
20.6
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data
type of the objects.
Example:
num_string = '12'
num_integer = 23
num_string = int(num_string)
print("Sum:",num_sum)
O/P:
Sum: 35
Comment in Python
They are added with the purpose of making the source code easier for humans to understand,
and are ignored by Python interpreter.
Comments enhance the readability of the code and help the programmers to understand the
code very carefully.
Just like most modern languages, Python supports single-line (or end-of-line) and multi-line
(block) 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.
2. Multi-Line Comments
Python does not provide a direct way to comment multiple line. You can comment multiple
lines as follows −
# This is a comment.
triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comments:
'''
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 23
Python Programming (UNIT-2) | 4311601
This is a multiline
comment.
'''
**********
“Do not give up, the beginning is always hardest!”