I Unit
I Unit
UNIT – II
UNIT – III
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-
Return Statement. Function Arguments: Required Arguments, Keyword Arguments,
Default Arguments and Variable Length ArgumentsRecursion. Python Strings: String
operations- Immutable Strings - Built-in String Methods and Functions - String
Comparison. Modules: import statementThe Python module – dir() function –
Modules and Namespace – Defining our own modules.
UNIT – IV
Lists: Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic
list operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting
Elements in a tuple – Nested tuples– Difference between lists and tuples. Dictionaries:
Creating, Accessing, Updating and Deleting Elements in a Dictionary – Dictionary
Functions and Methods - Difference between Lists and Dictionaries.
UNIT – V
Python File Handling: Types of files in Python - Opening and Closing filesReading and
Writing files: write() and writelines() methods- append() method – read() and
readlines() methods – with keyword – Splitting words – File methods - File Positions-
Renaming and deleting files.
UNIT – I
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
For many uninitiated people, the word Python is related to a species of snake.
Rossum though attributes the choice of the name Python to a popular comedy
series Monty Python's Flying Circus on BBC.
Being the principal architect of Python, the developer community conferred upon
him the title of Benevolent Dictator for Life (BDFL). However, in 2018, Rossum
relinquished the title. Thereafter, the development and distribution of the reference
implementation of Python is handled by a nonprofit organization Python Software
Foundation.
Python was invented by a Dutch Programmer Guido Van Rossum in the late
1980s. And, Python's first version (0.9.0) was released in 1991.
Python 1.0
In January 1994, version 1.0 was released, armed with functional programming
tools, features like support for complex numbers etc.
Python 2.0
Next major version − Python 2.0 was launched in October 2000. Many new
features such as list comprehension, garbage collection and Unicode support were
included with it.
Python 3.0
Meanwhile, more and more features have been incorporated into Python's 3.x
branch. As of date, Python 3.11.2 is the current stable version, released in February
2023.
Features of Python
Let's highlight some of the important features of Python that make it widely
popular. Apart from these 10 features where are number of other interesting features
which make Python most of the developer's first choice.
The following are the features of Python programming language –
1. Easy to Learn
This is one of the most important reasons for the popularity of Python. Python
has a limited set of keywords. Its features such as simple syntax, usage of indentation
to avoid clutter of curly brackets and dynamic typing that doesn't necessitate prior
declaration of variable help a beginner to learn Python quickly and easily.
2. Interpreter Based
3. Interactive
Standard Python distribution comes with an interactive shell that works on the
principle of REPL (Read – Evaluate – Print – Loop). The shell presents a Python prompt
>>>. You can type any valid Python expression and press Enter. Python interpreter
immediately returns the response and the prompt comes back to read the next
expression.
>>> 2*3+1
7
>>> print ("Hello World")
Hello World
The interactive mode is especially useful to get familiar with a library and test out its
functionality. You can try out small code snippets in interactive mode before writing a
program.
4. MultiParadigm
5. Standard Library
Even though it has a very few keywords (only Thirty Five), Python software is
distributed with a standard library made of large number of modules and packages.
Thus Python has out of box support for programming needs such as serialization, data
compression, internet data handling, and many more. Python is known for its batteries
included approach.
7. GUI Applications
8. Database Connectivity
Almost any type of database can be used as a backend with the Python
application. DB-API is a set of specifications for database driver software to let Python
communicate with a relational database. With many third party libraries, Python can
also work with NoSQL databases such as MongoDB.
9. Extensible
The term extensibility implies the ability to add new features or modify existing
features. As stated earlier, CPython (which is Python's reference implementation) is
written in C. Hence one can easily write modules/libraries in C and incorporate them
in the standard library. There are other implementations of Python such as Jython
(written in Java) and IPython (written in C#). Hence, it is possible to write and merge
new functionality in these implementations with Java and C# respectively.
Apart from the above-mentioned features, Python has another big list of good features,
few are listed below −
Python Variables
• A Variable is a location that is named in order to store data while the program is
being run.
• In a programming language, Variables are words that are used to store values of
any data type.
In simple words, when you create a variable, it takes up some memory space based on the
value and the type you set to it. The Python interpreter allocates RAM to the variable
based on its data type. The variables’ values can be altered at any time during the
program.
An Identifier is a term used in programming language in order to denote unique name
given to these variables.
Syntax
variable_name = data values
where, variable_name = combination of letters, numbers and an underscore
Rules to be followed while declaring a Variable name
1. A Variable’s name cannot begin with a number. Either an alphabet or the
underscore character should be used as the first character.
2. Variable names are case-sensitive and can include alphanumeric letters as well
as the underscore character.
3. Variable names cannot contain reserved terms.
4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables
in Python.
Assigning values to Variables in Python
There are few different methods to assign data elements to a Variable. The most common
ones are described below –
1. Simple declaration and assignment of a value to the Variable
In this type, the data values are directly assigned to the Variables in the declaration
statement.
Example
num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'
print(num)
print(numlist)
print(str)
Output
10
[1, 3, 5, 7, 9]
Hello World
Here, we have created 3 variables named as ‘num’, ‘numlist’, and ‘str’. We have
assigned all the 3 variables an int value 10, a list of integers, and a string of characters
respectively.
Keywords in Python
Python 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, or variable name. All the keywords
in Python are written in lowercase except True and False. There are 35 keywords in
Python 3.11.
In Python, there is an inbuilt keyword module that provides an iskeyword()
function that can be used to check whether a given string is a valid keyword or not.
Furthermore, we can check the name of the keywords in Python by using the kwlist
attribute of the keyword module.
Rules for Keywords in Python
• Python keywords cannot be used as identifiers.
• All the keywords in Python should be in lowercase except True and False.
List of Python Keywords
Keywords Description
This is a logical operator which returns true if both the operands are
and
true else returns false.
Else is used with if and elif conditional statements. The else block is
else
executed if the given condition is not true.
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module,
etc. The identifier is a combination of character digits and an underscore. They are
case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python.
It is a good programming practice to give meaningful names to identifiers to make
the code understandable.
We can also use the Python string isidentifier() method to check whether a
string is a valid identifier or not.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
Built-in Data Types
• 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, in these categories:
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Output Statements
Example
x = "Python is awesome"
print(x)
OUTPUT
Python is awesome
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
OUTPUT
Python is awesome
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
OUTPUT
Python is awesome
x=5
y = 10
print(x + y)
OUTPUT
15
Input Statements
Example
Python input() function is used to get input from the user. It prompts for the user input
and reads a line. After reading data, it converts it into a string and returns that. It throws
an error EOFError if EOF is read.
print('Enter your name:')
x = input()
print('Hello, ' + x)
OUTPUT
Enter your name: computer
Hello computer
Definition and Usage
The input() function allows user input.
Syntax
input(prompt)
Parameter Values
Prompt → A String, representing a default message before the input.
Example
Use the prompt parameter to write a message before the input:
x = input('Enter your name:')
print('Hello, ' + x)
Comments
Creating a Comment
Comments starts with a #, and Python will ignore them:
#This is a comment
print("Hello, World!")
OUTPUT
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of the
line:
print("Hello, World!") #This is a comment
Multiline Comments
• Python does not really have a syntax for multiline comments.
• To add a multiline comment you could insert a # for each line:
Python Indentation
Example
if 5 > 2:
OUTPUT
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Python Operators
Python operators are special symbols (sometimes called keywords) that are
used to perform certain most commonly required operations on one or more
operands (value, variables, or expressions).
Types of Operators in Python
Python language supports the following types of operators −
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such
as addition, subtraction, multiplication, etc.
Assume variable a holds 10 and variable b holds 20, then
+ Addition a + b = 30
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0
= a = 10 a = 10
+= a += 30 a = a + 30
-= a -= 15 a = a - 15
*= a *= 10 a = a * 10
/= a /= 5 a=a/5
%= a %= 5 a=a%5
**= a **= 4 a = a ** 4
//= a //= 5 a = a // 5
|= a |= 5 a=a|5
^= a ^= 5 a=a^5
| OR a|b
^ XOR a^b
~ NOT ~a
or OR a or b
not NOT not(a)
Python 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 −
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last
two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming. This article is
aimed at providing information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Python Implicit Type Conversion
2. Python Explicit Type Conversion
Type Conversion in Python
The act of changing an object’s data type is known as type conversion. The
Python interpreter automatically performs Implicit Type Conversion. Python
prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit
type conversion, sometimes referred to as type casting. When type casting, data loss
could happen if the object is forced to conform to a particular data type.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
Example
As we can see the data type of ‘z’ got automatically changed to the “float” type
while one variable x is of integer type while the other variable y is of float type. The
reason for the float value not being converted into an integer instead is due to type
promotion that allows performing operations by converting data into a wider-sized
data type without any loss of information. This is a simple case of Implicit type
conversion in Python.
x = 10
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'>
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of data
loss since we are forcing an expression to be changed in some specific data
type. Various forms of explicit type conversion are explained below:
Converting integer to float
int(a, base): This function converts any data type to an integer. ‘Base’
specifies the base in which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-
point number.
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# initializing string
s = 'geeks'
# initializing integers
a=1
b=2
# initializing tuple
c = complex(1,2)
print (c)
c = str(a)
print (c)
c = dict(tup)
print (c)
Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
What Is an Array?
An array is a data structure that lets us hold multiple values of the same data type.
Think of it as a container that holds a fixed number of the same kind of object. Python
makes coding easier for programmers.
Why Use an Array in Python?
An array is used to store more than one value at a time. It can hold multiple values in a
single variable, and also helps you reduce the overall size of the code. Arrays save time.
Syntax to Create an Array in Python
You can declare an array in Python while initializing it using the following syntax.
arrayName = array.array(type code for data type, [array,items])
The following image explains the syntax.
Array Syntax
1. Identifier: specify a name like usually, you do for variables
2. Module: Python has a special module for creating array in Python, called “array”
– you must import it before using it
3. Method: the array module has a method for initializing the array. It takes two
arguments, type code, and elements.
4. Type Code: specify the data type using the type codes available (see list below)
5. Elements: specify the array elements within the square brackets, for example
[130,450,103]
How to create arrays in Python?
In Python, we use following syntax to create arrays:
Class array.array(type code[,initializer])
For Example
import array as myarray
abc = myarray.array('d', [2.5, 4.9, 6.7])
The above code creates an array having integer type. The letter ‘d’ is a type code.
Following tables show the type codes:
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
# Output: 2
The code above creates a list called fruits with four elements: 'apple', 'banana',
'cherry', and another 'banana'. The count() method is then used on the fruits list to
count the number of occurrences of the element 'banana'. It returns the count, which
in this case is 2, as 'banana' appears twice in the list.
Finally, the count value is printed to the console, resulting in the output: 2.
Here's another example of using the count() method:
# Return the number of times the value "Lexus" appears in the car list.
# Output: 1
This code above creates a list of fruits containing 'apple', 'banana', and 'cherry'. It then
finds the index position of 'banana' in the list and assigns it to the variable 'index'.
Finally, it prints the value of 'index', which in this case would be 1.
The insert() method
This array method adds an element at the specified position.
numbers = [1, 2, 3, 5, 6]
numbers.insert(3, 4)
print(numbers)
# Output: [1, 2, 3, 4, 5, 6]
From the code above, we have an array numbers with elements [1, 2, 3, 5, 6]. We want
to insert the number 4 at index 3 (which is the fourth position in the array, as Python
is 0-indexed). By calling insert(3, 4), we insert the element 4 at the specified index, and
the existing elements are shifted to the right to make room for the new element. The
resulting array is [1, 2, 3, 4, 5, 6].
The pop() method
This method removes the element at the specified position.
Example:
# To delete an item from an array/list, you can utilize the pop() method.
# Delete the second element of the car array:
cars = ["Lexus", "Toyota", "Mercedez"]
cars.pop(2)
print(cars)
And here's the output:
['Lexus', 'Toyota']
This code above deletes the second element from the 'cars' array using the 'pop()'
method and then prints the updated array.
Here's another example using the pop() method:
# To delete an item from an array/list, you can utilize the pop() method.
# Delete the second element of the car array:
cars = ["Lexus", "Toyota", "Mercedez"]
cars.pop(2)
print(cars)
Output:
['Lexus', 'Toyota']
The code deletes the second element from the `cars` array using the `pop()` method
and then prints the modified array. The resulting array will contain only the first and
third elements: ['Lexus', 'Toyota'].
The remove() method
This method removes the first item with the specified value.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
# Output Below:
["apple", "cherry"]
The code above creates a list called fruits with three elements: 'apple', 'banana', and
'cherry'. The remove() method is then used to remove the element 'banana' from the
list.
After removing 'banana', the updated list is printed using the print() function. The
output will be ['apple', 'cherry'], as 'banana' is no longer present in the list.
Here's another example using the remove() method:
cars = ["Lexus", "Toyota", "Mercedez"]
cars.remove("Toyota")
print(cars)
The remove() function may also be used to remove an element from an array, but it
should be noted that it only removes the first instance of the specified value from a list.
The reverse() method
This method reverses the order of the list.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)
# Output: [1, 2, 3, 4]
The code above creates a list called numbers with the elements [4, 2, 1, 3].
The sort() method is then called on the numbers list, which sorts the elements in
ascending order. After sorting, the numbers list becomes [1, 2, 3, 4]. Finally, the sorted
list is printed to the console using print(numbers), which outputs [1, 2, 3, 4].
the sort() method in Python sorts the elements of a list in ascending order by default.
If you want to sort the list in descending order, you can pass the
parameter reverse=True to the sort() method.
Here's an example of how to sort the numbers list in descending order:
numbers = [4, 2, 1, 3]
numbers.sort(reverse=True)
print(numbers)
# Output
[4, 3, 2, 1]
By passing reverse=True as an argument to the sort() method, the list is sorted in
descending order.