Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

python unit 1

The document provides an overview of Python, including its history, features, and comparisons with other programming languages like C and Java. It highlights Python's ease of use, versatility, and object-oriented nature, as well as its memory management and garbage collection mechanisms. Additionally, it discusses the significance of indentation and comments in Python programming.

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python unit 1

The document provides an overview of Python, including its history, features, and comparisons with other programming languages like C and Java. It highlights Python's ease of use, versatility, and object-oriented nature, as well as its memory management and garbage collection mechanisms. Additionally, it discusses the significance of indentation and comments in Python programming.

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Ankur

(Python [601] – Unit 1)


COLLEGE ==> MATRUSHRI L.J.
GANDHI BCA COLLEGE, MODASA
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Python
 Python is a popular programming language which was created by Guido van Rossum and
released in 1991.
 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 code can connect to database systems.
 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.
 Data Analysis and Processing, Artificial Intelligence, Games, Sensor/Robots are the general
areas where Python is widely used.

History of python
 There is a fact behind choosing the name of python.
 Guido van Rossum was reading the script of a popular BBC comedy series "Monty
Python's Flying Circus" which 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 implementation of Python was started in December 1989 by Guido Van Rossum at CWI
in Netherland.
 In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
 In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
 Python 2.0 added new features such as list comprehensions, garbage collection systems.
 On December 3, 2008, Python 3.0 (also called "Py3K") was released and much more comes.

ANKUR 1
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Features of python
1. Easy to learn and use
 Python is easy to learn as compared to other programming languages.
 Its syntax is straightforward and much the same as the English language.
 There is no use of the semicolon or curly-bracket, the indentation defines the code block.
 It is the recommended programming language for beginners.

2. Free and Open Source


 Python language is freely available at the official website www.python.org.
 Since it is open-source, this means that source code is also available to the public, So you can
download it as, use it as well as share it.

3. 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"), In which
it will take only one line to execute, while Java or C takes multiple lines.

4. Object-Oriented Language
 Python supports object-oriented language and concepts of classes and objects.
 It supports inheritance, polymorphism, and encapsulation, etc.
 The object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.

5. Portable language
 Python language is also a portable language. For example, if we have python code for
windows and if we want to run this code on other platforms such as Linux, Unix, and Mac
then we do not need to change it, we can run this code on any platform.

6. Integrated language
 It can be easily integrated with languages like C, C++, and JAVA.
 Python code runs line by line like C, C++, and JAVA which makes easy to debug the code.

7. Interpreted Language
 Python program is executed one line at a time.
 The advantage of being interpreted language, it makes debugging easy and portable.

8. High-Level Language
 Programmers write in high-level languages because they are easier to understand and are less
complex than machine code.

ANKUR 2
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

 They allow the programmer to focus on what needs to be done, rather than on how the
computer actually works.

9. Extensible
 It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our Python code.
 It converts the program into byte code, and any platform can use that byte code.

10. Large Standard Library


 Python has a large standard library which provides a rich set of module and functions so you
do not have to write your own code for every single thing.
 There are many libraries present in python for regular expressions, machine learning and
many more.

11. Dynamic Memory Allocation


 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 7 to a, then we don't need to write int a = 7. Just write
a = 7.

12. GUI Programming Support


 Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or
Tk in python.
 PyQt5 is the most popular option for creating graphical apps with Python.

ANKUR 3
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Python virtual machine


 Python Virtual Machine (PVM) is a program which provides programming environment.
 The role of Python Virtual Machine (PVM) is to convert the byte code instructions into
machine code so that the computer can execute those machine code instructions and display
the final output.
 We know that computers understand only machine code that comprises 1s and 0s.
 Since computer understands only machine code, it is necessary that we should convert any
program into machine code before it is submitted to the computer for execution.
 For this purpose, we should take the help of a compiler. A compiler normally converts the
program source code into machine code.
 A Python compiler does the same task but in a slightly different manner.
 It converts the program source code into another code, called byte code.
 Each Python program statement is converted into a group of byte code instructions.

 Following Figure shows the role of virtual machine in converting byte code instructions into
machine code:

 The Python source code goes through the following to generate an executable code :
 STEP 1: The python compiler reads a python source code or instruction. Then it verifies
that the instruction is well-formatted, i.e. it checks the syntax of each line. If it encounters
an error, it immediately halts the translation and shows an error message.

 STEP 2: If there is no error, i.e. if the python instruction or source code is well-formatted
then the compiler translates it into its equivalent form in an intermediate language called
“Byte code”.

 STEP 3: Byte code is then sent to the Python Virtual Machine(PVM) which is the python
interpreter. PVM converts the python byte code into machine-executable code. If an error
occurs during this interpretation then the conversion is halted with an error message.

ANKUR 4
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Indentation in Python
 Most of the programming languages like C, C++ and Java use braces { } to define a block of
code, But Python uses indentation.
 A code block (body of a function, loop, etc.) starts with indentation and ends with the first
unindented line.
 The amount of indentation is up to you, but it must be consistent throughout that block.
 Generally, four whitespaces are used for indentation and are preferred over tabs.
 Indentation can be ignored in line continuation, but it's always a good idea to indent.
 Incorrect indentation will result in IndentationError.
 Here is an example of indentation which displays hii Daksh as output..
name = ‘Daksh’
if name == ‘Daksh’ :
print(‘hii Daksh….’)
else:
print(‘string not match’)

Python comments
 Comments are very important while writing a program.
 They describe what is going on inside a program, so that a person looking at the source code
does not have a hard time figuring it out.
 In Python, we use the hash (#) symbol to start writing a comment.
 Comments are for programmers to better understand a program.
 Python Interpreter ignores comments.
#This is a comment
#print out Hello
print('Hello')

 We can have comments that extend up to multiple lines.


 One way is to use the hash(#) symbol at the beginning of each line.
 For example:
#This is a long comment
#and it extends
#to multiple lines

 Another way of doing this is to use triple quotes, either ''' or """.
 These triple quotes are used as a multi-line comment.
"""This is also a
perfect example of
multi-line comments"""

ANKUR 5
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Comparison between c-Python


Comparison Python Programming
C Programming Language
Parameter Language

The C programming language was The Python programming language


Developed /
developed by Dennis M. Ritchie in was first worked by Guido van
Founded by
1972. Rossum and was released in 1991.

Programming C is a procedural programming Python is an object oriented


model language programming language.

Pointers C has support for pointers. Python has no support pointers.

Python is a high-level language as


Type of C is a middle level language as it
the translation of Python code takes
language binds the bridges between machine
place into machine language, using
level and high level languages.
an interpreter.

In C, variable types must be In Python, variables are untyped,


Variable declared when they are created, and that is, there is no need to define the
Declaration only values of those particular types data type of a variable while
must be assigned to them. declaring it..

Memory management is
Memory Memory management needs to be
automatically handled in Python. by
Management done manually in C.
the Garbage Collector provided by it.

Python is a more robust language


C is a less robust language compared
Robustness compared to C as it has strong
to Python.
memory management schemes.

Identification of C uses {} to identify a separate Python uses indentation to identify


block block of code. separate blocks of code.

ANKUR 6
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

To use various data structures like It is easier to use Data Structures in


Usage of Data
stacks, queues, etc. in C, we need to Python as it provides built in
Structures
implement them on our own. libraries for the same.

It is not mandatory to mark end of


It is mandatory to mark end of every
End of line every statement with a semicolon in
statement with a semicolon in C.
Python.

Complexity C is complex than Python. Python is much easier than C.

Code length In c, More than python In python, less than c

Python codes are stored with .py


Type of File C codes are stored with .c extension.
extension.

Built-in The number of built-in functions in C There are a lot of built-in functions
functions are very limited. in Python.

C is a compiled programming Python is an interpreted


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

Speed C is a faster language compared to Python programs are slower than C


Python as it is compiled. programs as they are interpreted.

ANKUR 7
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Comparison between c-java


Comparison
C Programming Language Java Programming Language
Parameter

The C programming language was Java was developed by James


Developed by developed by Dennis M. Ritchie in Gosling at Sun Microsystems in
1972 1995.
.

Programming C is a procedural programming Java is an object-oriented


model language programming language.

Garbage Garbage Collection needs to be done Garbage Collector automatically


Collection manually. does the Garbage Collection.

Language Type C is a middle-level language as it Java is a high-level language as the


binds the bridges between machine- translation of Java code takes place
level and high-level languages. into machine language.

Compilation & C is only compiled and not Java is both compiled and
Interpretation interpreted. interpreted.

Pointers C has support for pointers. Java does not support pointers.

In order to do memory allocation in


Memory C, functions like malloc(), calloc(), In order to do memory allocation in
Allocation etc. can be used. But there is no Java, the ‘new’ keyword can be used.
‘new’ keyword in C.

Free( ) is used for freeing the A compiler will free up the memory
Free the memory in C. internally by calling the garbage
Memory collector.

ANKUR 8
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Overloading Overloading functionality is not Java supports method overloading


supported by C. which helps in code readability.

OOPS C doesn’t supports OOPS concept. Java supports OOPS concept.

Keywords About thirty-two keywords in C. About fifty keywords in Java.

Security C is a less secure. Java is more secure.

File Extension C codes are stored with the .c file Java codes are stored with the .java
extension. file extension.

Exception Java provide the features of


C does not provide the features of
Handling Exception Handling using the
Exception Handling.
‘try’,‘catch’, ‘finally’, etc. keywords.

datatypes Union and structure datatypes are Java does not supports union and
supported by C. structures.

Members Default members of C are public. Java’s default members are private.

Threading C does not supports Threading. Java supports threading.

Java is a robust programming


C is not a robust programming
language as it has strong memory
Robustness language.
management schemes.

Go-to statements are supported in C Java does not supports go-to


Statements
language. statements.

ANKUR 9
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Memory management in Python


 In C or C++, the programmer should allocate and deallocate (or free) memory dynamically,
during runtime.
 For example, to allocate memory, the programmer may use malloc() function and to
deallocate the memory, he may use the free() function.
 But in Python, memory allocation and deallocation are done during runtime automatically.
 The programmer need not allocate memory while creating objects or deallocate memory
when deleting the objects.
 Python's PVM will take care of such issues.
 Everything is considered as an object in Python. For example, strings are objects. Lists are
objects. Functions are objects. Even modules are also objects.
 For every object, memory should be allocated.
 Memory manager inside the PVM allocates memory required for objects created in a Python
program.
 All these objects are stored on a separate memory called heap.
 Heap is the memory which is allocated during runtime.
 The size of the heap memory depends on the Random Access Memory (RAM) of our
computer and it can increase or decrease its size depending on the requirement of the
program.

ANKUR 10
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Garbage collection in Python


 A module represents Python code that performs a specific task.
 Garbage collector is a module in Python that is useful to delete objects from memory which
are not used in the program.
 The module that represents the garbage collector is named as gc.
 Garbage collector in the simplest way to maintain a count for each object regarding how
many times that object is referenced (or used).
 When an object is referenced twice, its reference count will be 2.
 When an object has some count, it is being used in the program and hence garbage collector
will not remove it from memory.
 When an object is found with a reference count 0, garbage collector will understand that the
object is not used by the program and hence it can be deleted from memory.
 Hence, the memory allocated for that object is deallocated or freed.
 This system destroys the unused object and reuses its memory slot for new objects.
 You can imagine this as a recycling system in computers.

 Every Python object has 3 things as shown in figure.


 Python objects have three things: Type, value, and reference count.
 When we assign a name to a variable, its type is automatically detected by Python as we
mentioned above.
 Value is declared while defining the object.
 Reference count is the number of names pointing that object.

 Python has an automated garbage collection.


 It has an algorithm to deallocate objects which are no longer needed.
 Python has two ways to delete the unused objects from the memory named as Reference
Counting and Generational Garbage Collection.

ANKUR 11
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

1. Reference counting
 The references are always counted and stored in memory.
 In the example below, we assign c to 50. Even if we assign a new variable with same value,
the reference count increases by 1!
 Every object has its own ID, we print the IDs of objects to check they are same or different.

 Now suppose, a points to 60, b and c point to 50.


 When we change a to None, we create a none object.
 Now the previous integer object has no reference, it is deleted by the garbage collection.
 We assign b to a boolean object but the previous integer object is not deleted because it still
has a reference by c.

ANKUR 12
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

 Now we delete c, so we decrease the reference count to c by one.

 As you can see above, del() statement doesn’t delete objects, it removes the name (and
reference) to the object.
 When the reference count is zero, the object is deleted from the system by the garbage
collection.
 There are advantages and disadvantages of garbage collection by reference counting.
 For example, Programmers don’t have to worry about deleting objects when they are no
longer used.
 The most important issue in reference counting garbage collection is that it doesn’t work
in cyclical references which is a situation in which an object refers to itself.
 The simplest cyclical reference is appending a list to itself as shown below.

ANKUR 13
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

 Reference counting alone can not destroy objects with cyclic references.
 If the reference count is not zero, the object cannot be deleted.
 The solution to this problem is the second garbage collection method.

2. Generational Garbage Collection


 Generational garbage collection is a type of trace-based garbage collection.
 It can break cyclic references and delete the unused objects even if they are referred by
themselves.

 Generational Garbage Collection works as follow:


 Python keeps track of every object in memory.
 3 lists are created when a program is run which are referred as Generation 0, 1, and 2 lists.
 Newly created objects are put in the Generation 0 list.
 A list is created for objects to discard and reference cycles are detected.
 If an object has no outside references it is discarded.
 The objects who survived after this process are put in the Generation 1 list.
 The same steps are applied to the Generation 1 list.
 Survivals from the Generation 1 list are put in the Generation 2 list.
 The objects in the Generation 2 list stay there until the end of the program execution.

ANKUR 14
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Writing first python program


 Sample Program to find sum of two numbers in C, Java and Python.
 By observing the below code of same program in different programming language we can
easily make a decision that Python code will be simple and concise.
 In C Language
#include<stdio.h>
void main()
{
int a=7,b=5,c;
printf("The Sum : %d",c);
}

 In JAVA Language
class Addition
{
public static void main(String args[ ])
{
int a,b;
a = 10;
b = 20;
System.out.println("The Sum : "+(a+b));
}
}

 In PYTHON Language
a =b= 10 = 20
print("The Sum : ",(a+b))

ANKUR 15
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Python variable
 In Python, we do not need to declare variables before using them or declare their type.
 A variable is created the moment we first assign a value to it.
 A variable is a name given to a memory location.
 It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.

 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 only contain alpha-numeric characters & 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.

Variable creation in Python:


# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "Daksh"

print(age) #output : 45
print(salary) #output : 1456.8
print(name) #output : Daksh

Variable Declaration in Python:


# declaring the var
Number = 100
# display
print(Number) #output : 100

Re-declare the Variable:


 We can re-declare the python variable once we have declared the variable already.
# declaring the var
Number = 100

ANKUR 16
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

# display
print("Before declare: ", Number) # Before declare: 100

# re-declare the var


Number = 120.3
print("After re-declare:", Number) # After re-declare: 120.3

Assigning a single value to multiple variables:


 Python allows assigning a single value to several variables simultaneously with “=”
operators.
a = b = c = 10
print(a) #output : 10
print(b) #output : 10
print(c) #output : 10

Assigning different values to multiple variables:


 Python allows adding different values in a single line with “,”operators.
a, b, c = 1, 20.2, "Daksh"
print(a) #output : 1
print(b) #output : 20.2
print(c) #output : Daksh

Can we use the same name for different types?


 If we use the same name, the variable starts referring to a new value and type.
a = 10
a = "Daksh"
print(a) #output : Daksh

How does + operator work with variables?


a = 10
b = 20
print(a+b) #output : 30

a = "Daksh"
b = "Parmar"
print(a+b) #output : Daksh Parmar

ANKUR 17
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Can we use + for different types also?


 No, It would produce error.
a = 10
b = "Daksh"
print(a+b) #TypeError: unsupported operand type(s) for +: 'int' and 'str'

Multi-line statement
 In Python, the end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\) which is called
an explicit line continuation.
 For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9

 In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }.


 For instance, we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)

 Here, the surrounding parentheses ( ) do the line continuation implicitly.


 Same is the case with [ ] and { }.
 For example:
colors = ['red',
'blue',
'green']

 We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3

ANKUR 18
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Python variable types


 There are two types of variables in Python - Local variable and Global variable.

1. Local Variable
 Local variables are the variables that declared inside the function and have scope within the
function.
 Let's understand the following example.
Example -
# Declaring a function
def add():

# Defining local variables. They has scope only within a function


a = 20
b = 30
c = a + b
print("The sum is:", c)

# Calling a function
add()

Output: The sum is: 50

2. Global Variables
 Global variables can be used throughout the program, and its scope is in the entire program.
 We can use global variables inside or outside the function.
 A variable declared outside the function is the global variable by default.
 Python provides the global keyword to use global variable inside the function.
 If we don't use the global keyword, the function treats it as a local variable.
 Let's understand the following example.
# Declare a variable and initialize it
x = 101

# Global variable in function


def mainFunction():

# printing a global variable


global x

ANKUR 19
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

print(x)

# modifying a global variable


x = 'Welcome Friend'
print(x)
mainFunction()
print(x)

Output: 101
Welcome Friend
Welcome Friend

Global keyword in Python


 Global keyword is a keyword that allows a user to modify a variable outside of the current
scope.
 It is used to create global variables from a non-global scope .
 Global keyword is used inside a function only when we want to do assignments or when we
want to change a variable.
 Rules of global keyword:
 If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a
local unless explicitly declared as global.
 Variables that are only referenced inside a function are global.
 We Use global keyword to use a global variable inside a function.
 There is no need to use global keyword outside a function.

# Python program to modify a global value inside a function


x = 15
def change():
# using a global keyword
global x
# increment value of a by 5
x = x + 5
print("Value of x inside a function :", x)

change()
print("Value of x outside a function :", x)

ANKUR 20
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Output:
Value of x inside a function : 20
Value of x outside a function : 20

Delete a variable
 We can delete the variable using the del keyword.
 The syntax is as : del <variable_name>

 In the following example, we create a variable x and assign value to it.


 We deleted variable x, and print it, we get the error "variable x is not defined".
 The variable x will no longer use in future.

# Assigning a value to x
x = 6
print(x)

# deleting a variable.
del x
print(x)

Output:
6

Traceback (most recent call last):


File "C:/Users/AP/PycharmProjects/Hello/test.py", line 111, in
print(x)
NameError: name 'x' is not defined

ANKUR 21
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Type conversion in Python


 The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion.
 Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion

1.Implicit Type Conversion


 In Implicit type conversion, Python automatically converts one data type to another data
type.
 This process doesn't need any user involvement.
 Let's see an example where Python promotes the conversion of the lower data type (integer)
to the higher data type (float) to avoid data loss.
Example : Converting integer to float
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

Output :
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>

Value of num_new: 124.23


datatype of num_new: <class 'float'>

 Now, let's try adding a string and an integer, and see how Python deals with it.
Example : Addition of string(higher) data type and integer(lower) datatype
num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))

ANKUR 22
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

print("Data type of num_str:",type(num_str))


print(num_int+num_str)

Output :
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>

Traceback (most recent call last):


File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

2. Explicit Type Conversion


 In Explicit Type Conversion, users convert the data type of an object to required data type.
 We use the predefined 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.
 Syntax : <required_datatype>(expression)
Example : Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))


print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str


print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

Output :
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>

ANKUR 23
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579


Data type of the sum: <class 'int'>

keywords in python
 Keywords are the reserved words in Python.
 We cannot use a keyword as a variable name, function name or any other identifier.
 They are used to define the syntax and structure of the Python language.
 In Python, keywords are case sensitive.
 There are 35 keywords in Python, this number can vary slightly over the course of time.
 All the keywords except True, False and None are in lowercase and they must be written as
they are.

Keyword in Python
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

ANKUR 24
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Datatypes in python
 In programming, data type is an important concept.
 Variables can store data of different types, and different types can do different things.
 Python has the following data types built-in by default.
Type Which type of Value stored?
Text str
Numeric int, float, complex
Sequence list, tuple, range
Mapping dict
Set set, frozenset
Boolean bool
Binary bytes, bytearray, memoryview

ANKUR 25
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Text type in python


 In Python, Text type stored string values.
 String defined as str in Python.
 String is sequence of characters.
 We can use single quotes or double quotes to represent strings.
 Multi-line strings can be denoted using triple quotes, ''' or """.

s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)

Output :
This is a string
A multiline
String

 Just like a list and tuple, the slicing operator [ ] can be used with strings.
 String index will be start with zero and all the white spaces will be count in a string while
slicing.
 Strings, however, are immutable(unchangeable) means once created it can’t be modified.

s = 'Hello world!'
print("s[4] = ", s[4])
print("s[6:11] = ", s[6:11])

Output :
s[4] = o
s[6:11] = 'world'

ANKUR 26
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Numeric type in python


 In Python, numeric datatype represent the data which has numeric value.
 Numeric value can be integer, floating number or complex numbers.
 These values are defined as int, float and complex class in Python.

1. Integer
 This value is represented by int class.
 It contains positive or negative whole numbers (without fraction or decimal).
 In Python there is no limit to how long an integer value can be.
a = 12345
print(“a = ”, a)

Output :
12345

2. Float
 This value is represented by float class.
 It is a real number with floating point representation.
 A floating-point number is accurate up to 15 decimal places.
 Integer and floating points are separated by decimal points.
 1 is an integer, 1.0 is a floating-point number.
b = 0.12345
print(“b = ”, b)

Output :
0.12345

3. Complex
 Complex number is represented by complex class.
 It is specified as (real part) + (imaginary part)j. For example – 2+3j
 Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.
c = 1+2j
print(“c = ”, c)

Output :
(1+2j)

ANKUR 27
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

sequence type in python


 In Python, list, tuple and range are stored in Sequence type.

1. Python List
 In Python, a list is created by placing elements inside square brackets [], separated by
commas.
 List is an ordered sequence of items.
 All the items in a list do not need to be of the same type and can have any number of items..
my_list = [1, "Hello", 3.4]

 A list can also have another list as an item. This is called a nested list.
my_list = ["mouse", [8, 4, 6], ['a']]

 Lists are mutable(changeable), means, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)

Output :
[1, 2, 4]

 We can also define empty list as my_list = [ ]

 We can use the slicing operator [ ] to extract an item or a range of items from a list.
a = [5,10,15,20,25,30,35,40]
print("a[2] = ", a[2])
print("a[0:3] = ", a[0:3])
print("a[5:] = ", a[5:])

Output :
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]

ANKUR 28
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

2. Python Tuple
 A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
 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.
 Tuple is also an ordered sequence of items same as a list.
 A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
my_tuple = (1, "Hello", 3.4)

 A tuple can also have another tuple as an item. This is called a nested tuple.
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

 We can also define empty tuple as my_tuple = ( )

 A tuple can also be created without using parentheses which is known as tuple packing and
tuple unpacking is also possible.
my_tuple = 3, 4.6, "dog"
print(my_tuple)

# tuple unpacking is also possible


a, b, c = my_tuple
print(a)
print(b)
print(c)

Output :
(3, 4.6, 'dog')
3
4.6
Dog

 Creating a tuple with one element is a bit tricky.


 Having one element within parentheses is not enough, we will need a trailing comma to
indicate that it is, in fact, a tuple.
my_tuple = ("hello")
print(type(my_tuple))

ANKUR 29
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

# Creating a tuple having one element


my_tuple = ("hello",)
print(type(my_tuple))

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple))

Output :
<class 'str'>
<class 'tuple'>
<class 'tuple'>

 We can use the slicing operator [ ] to extract items but we cannot change its value.
a = (5,'program', 1+3j)
print("a[1] = ", a[1])
print("a[0:3] = ", a[0:3])

Output will be as:


a[1] = program
a[0:3] = (5, 'program', (1+3j))

3. Python Range
 Range in python is mainly used with loops in python.
 It returns a sequence of numbers specified in the function arguments.
 Following are the range function parameters that we use in python:
 Start – This specifies the start of the sequence of numbers in a range function.

 Stop – It is the ending point of the sequence, the number will stop as soon as it reaches
the stop parameter.

 Step – The steps or the number of increments before each number in the sequence is
decided by step parameter.

 Syntax of range : range(start, stop, step)

ANKUR 30
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

 The range function in python only works with integers or whole numbers.
 Arguments passed in the range function cannot be any other data type other than an integer
data type.
 All three arguments passed can be either positive or negative integers.
 Step argument value cannot be zero otherwise it will throw a ValueError exception.
 You can access the elements in a range function using index values, just like a list data type.

Range With For Loop


 Below is an example of how we can use range function in a for loop.
 This program will print the even numbers starting from 2 until 20.
for i in range(2,20,2):
print(i)

Output : 2
4
6
8
10
12
14
16
18

How range works in Python?


# empty range
print(list(range(0)))

# using range(stop)
print(list(range(10)))

# using range(start, stop)


print(list(range(1, 10)))

Output :
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

ANKUR 31
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Reverse Range In Python


 The following program shows how we can reverse range in python.
 It will return the list of first 5 natural numbers in reverse.
for i in range(5, 0, -1):
print(i, end=", ")

Output :
5, 4, 3, 2, 1, 0

List of even number between the given numbers using range()


start = 2
stop = 14
step = 2
print(list(range(start, stop, step)))

Output :
[2, 4, 6, 8, 10, 12]

ANKUR 32
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

set type in python


 set type in python stored value of set and frozenset type.

1. set type
 A set is basically a data type consisting of a collection of unordered elements.
 Sets are mutable(changeable) and do not have repeated copies of elements.
 The values of a set are unindexed, so, indexing operations cannot be performed on sets.
 Sets in Python are used when
 The order of data does not matter
 You do not need any repetitions in the data elements
 You need to perform mathematical operations such as union, intersection, etc.
 Below is the program whose output shows all the elements present My_Set.
My_Set={1,'s',7.8}
print(My_Set)

Output: {‘s’, 1, 7.8}

 You can create an empty set using the same function.


Empty_Set=set( )
print(Empty_Set)

Output: set( )

 Sets in Python can be created in two ways


1.Using curly braces
 Sets in Python are created using curly braces({}).
My_Set={1,'s',7.8}
print(My_Set)

Output: {‘s’, 1, 7.8}

2. Using set() function


 Sets in Python can be created using the set() function.
My_Set =set({1,'b',6.9})
print(My_Set)

Output: {1, ‘b’, 6.9}

ANKUR 33
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Adding elements to a Set:


 Elements can be added to a set using two functions, the add() and the update() function.
 The add() function adds one element to the existing set as shown below:
My_Set={1,'s',7.8}
My_Set.add(3)
print(My_Set)

Output: {1, 3, 7.8, ‘s’}

 The update() function is used when you want to add more than one element to the
existing set.
 As you can see in the output, the update() function is taking a list of 4 values and all
values except 1 are added to My_Set. This is because 1 is already present in the set
and therefore, it cannot be added again.
My_Set={1,'s',7.8}
My_Set.update([2,4.6,1,'r'])
print(My_Set)

Output: {1, 2, 4.6, 7.8, ‘r’, ‘s’}

Removing Elements of a Set


 To remove elements from a set, you can use either the remove(), discard() and the pop()
functions.
1.remove( ) function
 The remove() function takes one parameter which is the item to be removed from the set.
 As you can see, 2 has been removed from the set using the remove() function.
 In case you specify some element as a parameter to remove() that does not exist in the
set, it will throw an error.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.remove(2)
print(My_Set)

Output: {1, 4.6, 7.8, ‘r’, ‘s’}

 2. discard( ) function
 If you want to remove some element from the set, and if you are not sure whether that
element is actually present in the set or not, you can use the discard() function.

ANKUR 34
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

 This function will take the element to be removed from the set as a parameter but in case
the element is not present, it does not throw an error.
 The output shows that 4.6 has been removed from My_Set but discard() has not thrown
an error when you used My_Set.discard(‘i’) even though ‘i’ is not present in my set.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.discard(4.6)
My_Set.discard('i')
print(My_Set)

Output: {1, 2, 7.8, ‘r’, ‘s’}

 3. pop( ) function
 The pop() function also removes set elements, but since a set is unordered, you will not
know which element has been removed.
 The output shows that, using pop() some random element has been removed, which in
this case is 1.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.pop()
print(My_Set)

Output: {2, 4.6, 7.8, ‘r’, ‘s’}

 Now, in case you want to delete all elements present in a set, you can use the clear() method.
 As you can see in the output, My_Set is an empty set.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.clear()
print(My_Set)

Output: set()

 In case you want to completely delete the set, you can use the del keyword.
 When you run the code, it will throw an error because My_Set is deleted.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
del My_Set
print(My_Set)

ANKUR 35
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

2. frozenset type
 Frozenset has the characteristics of a set, but its elements cannot be changed once assigned.
 Being immutable, it does not have methods that add or remove elements.
 The frozenset() function takes a single Parameters
 The syntax of frozenset() function is: frozenset([iterable])
 Iterable can be set, dictionary, tuple, etc.
# initialize A and B in Frozenset
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

Try these examples on Python shell.


>>> A.isdisjoint(B)
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})

Working of Python frozenset()


# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

# frozensets are immutable


fSet.add('v')

Output :
The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'})
The empty frozen set is: frozenset()
Traceback (most recent call last):
File "<string>, line 8, in <module>
fSet.add('v')
AttributeError: 'frozenset' object has no attribute 'add'

ANKUR 36
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Frozenset operations
 Like normal sets, frozenset can also perform different operations like copy, difference,
intersection, symmetric_difference, and union.
# initialize A and B in Frozenset
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

# copying a frozenset
C = A.copy() # Output: frozenset({1, 2, 3, 4})
print(C)

# union
print(A.union(B)) # Output: frozenset({1, 2, 3, 4, 5, 6})

# intersection
print(A.intersection(B)) # Output: frozenset({3, 4})

# difference
print(A.difference(B)) # Output: frozenset({1, 2})

# symmetric_difference
print(A.symmetric_difference(B)) # Output: frozenset({1, 2, 5, 6})

 Similarly, other set methods like isdisjoint, issubset, and issuperset are also available.
# initialize A, B and C in Frozenset
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
C = frozenset([5, 6])

# isdisjoint() method
print(A.isdisjoint(C)) # Output: True

# issubset() method
print(C.issubset(B)) # Output: True

# issuperset() method
print(B.issuperset(C)) # Output: True

ANKUR 37
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

mapping type in python


 In Python, Mapping type stored dictionary type values.
 Each item of a dictionary has a key/value pair.
 Dictionaries are optimized to retrieve values when the key is known.

Creating Python Dictionary


 Creating a dictionary is as simple as placing items inside curly braces {} separated by
commas.
 An item has a key and a corresponding value that is expressed as a pair (key : value).
 While the values can be of any data type and can repeat, keys must be unique.
# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])
 As you can see from above, we can also create a dictionary using the built-in dict() function.

Accessing Elements from Dictionary


 While indexing is used with other data types to access values, a dictionary uses keys.
 Keys can be used either inside square brackets [] or with the get() method.
 If we use the square brackets [], KeyError is raised in case a key is not found in the
dictionary.
 On the other hand, the get() method returns None if the key is not found.
my_dict = {'name': 'Jack', 'age': 26}
print(my_dict['name']) # Output: Jack
print(my_dict.get('age')) # Output: 26

ANKUR 38
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

print(my_dict.get('address')) # Output: None

print(my_dict['address']) # Output: KeyError:’address’

Changing and Adding Dictionary elements


 Dictionaries are mutable.
 We can add new items or change the value of existing items using an assignment operator.
 If the key is already present, then the existing value gets updated.
 In case the key is not present, a new (key: value) pair is added to the dictionary.
my_dict = {'name': 'Jack', 'age': 26}
my_dict['age'] = 27
print(my_dict) # Output: {'name': 'Jack', 'age': 27}

my_dict['add'] = 'Downtown'
print(my_dict) # Output: {'name': 'Jack', 'age': 27, 'add': 'Downtown'}

Removing Elements from Dictionary


 We can remove a particular item in a dictionary by using the pop() method.
 This method removes an item with the provided key and returns the value.
 The popitem() method can be used to remove and return an arbitrary (key, value) item pair
from the dictionary.
 All the items can be removed at once, using the clear() method.
 We can also use the del keyword to remove individual items or the entire dictionary itself.
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, and returns its value


# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove all items


squares.clear()

ANKUR 39
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
print(squares)

Output :
16

{1: 1, 2: 4, 3: 9, 5: 25}

{}

Traceback (most recent call last):


File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined

ANKUR 40
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

boolean type in python


 In Python, Boolean type stored bool type values.
 The bool data type is either True or False.
 The output in the below program <class 'bool'> indicates that the variable is a boolean data
type.
a = True
type(a)
Output : <class 'bool'>

b = False
type(b)
Output : <class 'bool'>

 Note the keywords True and False must have an Upper Case first letter. Using a lowercase
true returns an error.
c = true
Output : Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'true' is not defined

d = false
Output : Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'false' is not defined

Boolean Arithmetic
 Boolean arithmetic is the arithmetic of true and false logic.
 A boolean or logical value can either be True or False.
 Boolean values can be manipulated and combined with boolean operators.
 Boolean operators in Python include and, or, and not.
 The common boolean operators in Python are below:
 or
 and
 not
 == (equivalent)
 != (not equivalent)

ANKUR 41
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

 In the code section below, two variables are assigned the boolean values True and False.
 Then these boolean values are combined and manipulated with boolean operators.
A = True
B = False

A or B
Output : True

A and B
Output : False

not A
Output : False

not B
Output : True

A == B
Output : False

A != B
Output : True

ANKUR 42
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

binary type in python


 In Python, Binary Type stored bytes, bytearray, memoryview type data.
 bytes and bytearray are used for manipulating binary data.
 The memoryview uses the buffer protocol to access the memory of other binary objects
without needing to make a copy.
 Bytes objects are immutable sequences of single bytes. We should use them only when
working with ASCII compatible data.
 The syntax for bytes literals is same as string literals, except that a 'b' prefix is added.
 bytearray objects are always created by calling the constructor bytearray() and these
are mutable objects.

x = b'char_data'
x = b"char_data"

y = bytearray(5)

z = memoryview(bytes(5))

print(x) # b'char_data'
print(y) # bytearray(b'\x00\x00\x00\x00\x00')
print(z) # <memory at 0x014CE328>

ANKUR 43
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Determining datatype of variable in python


 The variable can be from any of the data types in Python as Number, String, Boolean, List,
Tuple, Set, and Dictionary.
 To find the data type of data in Python, you use the type() function.
testscore1= 95
type(testscore1)
Output : <class 'int'>

average= 92.5
type(average)
Output : <class 'float'>

student1= "Mark"
type(student1)
Output : <class 'str'>

students= ["Mark", "Ron", "Peter", "Greg"]


type(students)
Output : <class 'list'>

studentslist= ("Mark", "Ron", "Peter", "Greg")


type(studentslist)
Output : <class 'tuple'>

ANKUR 44
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Operators in python
 Operators are special symbols in Python that carry out arithmetic or logical computation.
 The value that the operator operates on is called the operand.
 For example: 2+3 will be provide output as 5
 Here, + is the operator that performs addition. 2 & 3 are the operands and 5 is the output.

1. Arithmetic operators
 Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Operator Meaning Example
+ Add two operands x+y
- Subtract right operand from the left x-y
* Multiply two operands x*y
Divide left operand by the right one
/ x/y
(always results into float)
Modulus - remainder of the division
% x % y (remainder of x/y)
of left operand by the right
Floor division - division that results
// into whole number adjusted to the x // y
left in the number line
Exponent - left operand raised to the
** x**y (x to the power y)
power of right

Example : Arithmetic operators in Python


x = y = 17 = 4

print('x + y =',x+y) # Output : x + y = 21


print('x - y =',x-y) # Output : x - y = 13
print('x * y =',x*y) # Output : x * y = 68
print('x / y =',x/y) # Output : x / y = 4.25
print('x % y =',x%y) # Output : x % y = 1
print('x // y =',x//y) # Output : x // y = 4
print('x ** y =',x**y) # Output : x ** y = 83521

ANKUR 45
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

2. Comparison operators
 Comparison operators are used to compare values. It returns either True or False according to
the condition.
Operator Meaning Example
Greater than - True if left operand is
> x>y
greater than the right
Less than - True if left operand is
< x<y
less than the right
Equal to - True if both operands are
== x == y
equal
Not equal to - True if operands are
!= x != y
not equal
Greater than or equal to - True if left
>= operand is greater than or equal to x >= y
the right
Less than or equal to - True if left
<= operand is less than or equal to the x <= y
right

Example : Comparison operators in Python


x = y = 10 = 12

print('x > y is',x>y) # Output : x > y is False


print('x < y is',x<y) # Output : x < y is True
print('x == y is',x==y) # Output : x == y is False
print('x != y is',x!=y) # Output : x != y is True
print('x >= y is',x>=y) # Output : x >= y is False
print('x <= y is',x<=y) # Output : x <= y is True

3. Logical operators
 Logical operators are the and, or, not operators.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
True if operand is false
not not x
(complements the operand)

ANKUR 46
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA

Example : Logical Operators in Python


x = True
y = False

print('x and y is',x and y) # Output : x and y is False


print('x or y is',x or y) # Output : x or y is True
print('not x is',not x) # Output : not x is False

Truth Table : and


 and will result into True only if both the operands are True.

A B A and B
True True True
True False False
False True False
False False False

Truth Table : or
 or will result into True if any of the operand is True.

A B A or B
True True True
True False True
False True True
False False False

Truth Table : not


 not operator is used to invert the truth value.

A not A
True False
False True

ANKUR 47

You might also like