Python UnitI
Python UnitI
INTRODUCTION TO PYTHON
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
GNU General Public License (GPL).
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, e
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
LANGUAGE FEATURES
Interpreted
o There are no separate compilation and execution steps like C and C++.
o Directly run the program from the source code.
o Internally, Python converts the source code into an intermediate form called
bytecodes which is then translated into native language of specific computer to
run it.
o No need to worry about linking and loading with libraries, etc.
Platform Independent
o Python programs can be developed and executed on multiple operating system
platforms.
o Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Free and Open Source; Redistributable
High-level Language
o In Python, no need to take care about low-level details such as managing the
memory used by the program.
Simple
o Closer to English language;Easy to Learn
o More emphasis on the solution to the problem rather than the syntax
Embeddable
o Python can be used within C/C++ program to give scripting capabilities for the
program‟s users.
Robust:
o Exceptional handling features
o Memory management techniques in built
Rich Library Support
o The Python Standard Library is very vast.
o Known as the “batteries included” philosophy of Python ;It can help do
various things involving regular expressions, documentation generation, unit
testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV
files, cryptography, GUI and many more.
o Besides the standard library, there are various other high-quality libraries such
as the Python Imaging Library which is an amazingly simple image
manipulation library.
Python vs JAVA
Python Java
Statically Typed
Dynamically Typed All variable names (along with their types)
No need to declare anything. An must be explicitly declared. Attempting to
assignment statement binds a name to an assign an object of the wrong type to a
object, and the object can be of any type. variable name triggers a type exception.
No type casting is required when using Type casting is required when using
container objects container objects.
Uses Indentation for structuring code Uses braces for structuring code
KEYWORDS
Keywords are some predefined and reserved words in python that have special meanings.
Keywords are used to define the syntax of the coding.
The keyword cannot be used as an identifier, function, and variable name. All the keywords in
python are written in lower case except True and False. There are 33 keywords in Python 3.7.
Python Keywords List
LITERALS
Types of Literals in Python
Python supports various types of literals, such as numeric literals, string literals, Boolean
literals, and more.
1. String literals
2. Character literal
3. Numeric literals
4. Boolean literals
5. Literal Collections
6. Special literals
String Literals
A string is literal and can be created by writing a text(a group of Characters ) surrounded by a
single(”), double(“), or triple quotes. We can write multi-line strings or display them in the
desired way by using triple quotes. Here geekforgeeks is a string literal that is assigned to a
variable(s). Here is an example of a Python string literal.
Example:
s = 'geekforgeeks'
t = "geekforgeeks"
m = '''geek
for
geeks'''
print(s)
print(t)
print(m)
Numerical literals in Python are those literals that contain digits only and are immutable.
They are immutable and there are three types of numeric literal:
Integer
Float
Complex
Integer
Both positive and negative numbers including 0. There should not be any fractional part. In
this example, We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different variables.
Here, „a„ is a binary literal, „b’ is a decimal literal, „c„ is an octal literal, and „d„ is a
hexadecimal literal. But on using the print function to display a value or to get the output they
were converted into decimal.
Example
# Binary Literals
a = 0b10100
# Decimal Literal
b = 50
# Octal Literal
c = 0o320
# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)
Output
20 50 208 299
Float
These are real numbers having both integer and fractional parts. In this example, 24.8 and 45.0
are floating-point literals because both 24.8 and 45.0 are floating-point numbers.
# Float Literal
e = 24.8
f = 45.0
print(e, f)
Output
24.8 45.0
Complex
The numerals will be in the form of a + bj, where „a’ is the real part and „b„ is the complex
part. Numeric literal [ Complex ]
z = 7 + 5j
# real part is 0 here.
k = 7j
print(z, k)
Output
(7+5j) 7j
Boolean literal
There are only two Boolean literals in Python. They are true and false. In
Python, True represents the value as 1, and False represents the value as 0. In this example „a„
is True and „b„ is False because 1 is equal to True.
Example
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7
print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
Output
a is True
b is False
c: 4
d: 7
List literal
The list contains items of different data types. The values stored in the List are separated by a
comma (,) and enclosed within square brackets([]). We can store different types of data in a
List. Lists are mutable.
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)
Output
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
Tuple literal
A tuple is a collection of different data-type. It is enclosed by the parentheses „()„ and each
element is separated by the comma(,). It is immutable.
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)
print(odd_number)
Output
(2, 4, 6, 8)
(1, 3, 5, 7)
Dictionary literal
The dictionary stores the data in the key-value pair. It is enclosed by curly braces „{}„ and each
pair is separated by the commas(,). We can store different types of data in a dictionary.
Dictionaries are mutable.
Example
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
information = {'name': 'amit', 'age': 20, 'ID': 20}
print(alphabets)
print(information)
Output
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'name': 'amit', 'age': 20, 'ID': 20}
Set literal
Set is the collection of the unordered data set. It is enclosed by the {} and each element is
separated by the comma(,).
Output
{'o', 'e', 'a', 'u', 'i'}
{'apple', 'banana', 'cherry'}
EXPRESSIONS
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
Example:
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on
both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated
first, and then compared as per relational operator and produce a boolean output in the end.
These expressions are also called Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal
to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also
come across some logical operators which can be seen in logical expressions most often. Here
are some logical operators in Python:
and P and Q It returns true if both P and Q are true otherwise returns false
Example:
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single
expression, and that will be termed as combinational expressions.
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
VARIABLES
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
Rules for creating variables in Python
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_ ).
Variable names are case-sensitive (name, Name and NAME are three different variables).
The reserved words(keywords) cannot be used naming the variable.
Example
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John
Declare the Variable
# declaring the var
Number = 100
# display
print( Number)
Output:
100
PYTHON OPERATORS
Operators are used to perform operations on variables and values.
OPERATORS: Are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Python divides the operators in the following groups:
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Python arithmetic operators are used to perform mathematical operations on numerical values.
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
** Exponent 4**2 = 16
Example
a = 21
b = 10
print ("a + b : ", a + b)
print ("a - b : ", a - b)
print ("a * b : ", a * b)
print ("a / b : ", a / b)
print ("a % b : ", a % b)
print ("a ** b : ", a ** b)
print ("a // b : ", a // b)
Output
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 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
print ("a == b : ", a == b)
print ("a != b : ", a != b)
print ("a > b : ", a > b)
print ("a < b : ", a < b)
print ("a >= b : ", a >= b)
print ("a <= b : ", a <= b)
Output
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
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
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
--------------------------
a&b = 12 (0000 1100)
a|b = 61 (0011 1101)
a^b = 49 (0011 0001)
~a = -61 (1100 0011)
a << 2 = 240 (1111 0000)
a>>2 = 15 (0000 1111)
<< 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
c=a&b # 12 = 0000 1100
print ("a & b : ", c)
# Binary OR
c=a|b # 61 = 0011 1101
print ("a | b : ", c)
# Binary XOR
c=a^b # 49 = 0011 0001
print ("a ^ b : ", c)
Logical Operators
There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then
Operator Description Example
and Logical If both the operands are true then condition becomes (a and b) is true.
AND true.
or Logical OR If any of the two operands are non-zero then condition (a or b) is true.
becomes true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is
false.
Example
a=1
b=6
print((a > 2) and (b >= 6))
print((a>2) or (b>=6))
print(not a)
Output
False
True
False
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 x not in y, here not in results in a
in the specified sequence and false otherwise. 1 if x is not a member of sequence
y.
Example
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list
Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below
Example
x=5
y=5
print(x is y)
id(x)
id(y)
Output
True
The following table lists all operators from highest precedence to lowest.
2 ~ + - Complement, unary plus and minus (method names for the last two are +@ and -@)
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable.
For example;
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
Example
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes
A multiline
string
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.
Example:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
Output
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Example:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a
hash table where each key stores a specific value. Key can hold any primitive data type, whereas
value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Example:
print ([Link]())
print ([Link]())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Example:
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set()
Example:
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
[Link](10)
print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
PYTHON INDENTATION
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.
You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Syntax
Input(prompt)
Output:
Enter a number: 10
You Entered: 10
Example
print('Python is powerful')
Syntax
Here,
Example
TYPE CONVERSION
Type conversion is the process of converting data of one type to another. For example:
converting int data to str.
There are two types of type conversion in Python.
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
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.
Example:
s = "10010"
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Python Type conversion using ord(), hex(), oct()
ord(): This function is used to convert a character to an integer.
hex(): This function is to convert an integer to a hexadecimal string.
oct(): This function is to convert an integer to an octal string.
ARRAY IN PYTHON
An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together.
Example
x = cars[0]
print(x)
Output:
Ford
Use the len() method to return the length of an array (the number of elements in an array).
Example
x = len(cars)
Output:
3
You can use the for in loop to loop through all the elements of an array.
Example
for x in cars:
print(x)
Output
Ford
Volvo
BMW
Example
[Link]("Honda")
You can use the pop() method to remove an element from the array.
Example
[Link](1)
['Ford', 'BMW']
You can also use the remove() method to remove an element from the array.
Example
[Link]("Volvo")
Output
['Ford', 'BMW']
ARRAY METHODS
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value