Python Programming Basics Guide
Python Programming Basics Guide
UNIT - 1
Basics of Python Programming: History of Python-Features of Python-Literal-
Constants-Variables – Identifiers–Keywords-Built-in Data Types-Output
Statements – Input Statements-Comments – Indentation- Operators-Expressions-
Type conversions. Python Arrays: Defining and Processing Arrays – Array
methods
UNIT - 2
Control Statements: Selection/Conditional Branching statements: if, if-else, nested
if and if-elif-else statements. Iterative Statements: while loop, for loop, else suite in
loop and nested loops. Jump Statements: break, continue and pass statements.
UNIT - 3
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-
Return Statement. Function Arguments: Required Arguments, Keyword
Arguments, Default Arguments and Variable Length Arguments- Recursion.
Python Strings: String operations- Immutable Strings – Built-in String Methods
and Functions – String [Link]: import statement- The Python
module – dir() function – Modules and Namespace – Defining our own modules.
UNIT - 4
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 - 5
Python File Handling: Types of files in Python – Opening and Closing files-
Reading 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.
BASICS OF PYTHON :
What is Python?
Python is a high-level, general-purpose
programming language that is:
• Beginner-friendly
🌐 Web Development
📊 Data Analysis & Visualization
🤖 Machine Learning & AI
🕹 Game Development
🖥 Desktop Applications
🤖 Automation (like bots or scripts)
📱 Internet of Things (IoT)
🔹 Example Code:
Print(“Welcome to Python”)
o/p: Welcome to Python
HISTORY OF PYTHON:
• Python’s history begins in the late 1980s with ‘Guido van
Rossum’, a Dutch programmer, who started developing it as a
hobby project during the Christmas holidays.
• The language was officially released in 1991, with the name
"Python” inspired by the British comedy group ‘Monty
Python’s Flying Circus’.
• Over the years, Python has evolved through several versions,
including 1.0 (1994), 2.0 (2000), and 3.0 (2008).
• 1980s: Guido van Rossum begins developing Python at CWI
(Centrum Wiskunde & Informatica) a research institute in
mathematics and computer science in the Netherlands, aiming to
create a successor to the ABC programming language.
• 1991: Python 0.9 is released, marking the first official public
release.
• 1994: Python 1.0 is released, introducing features like exception
handling and lambda expressions.
• 2000: Python 2.0 is released, adding list comprehensions and
other key features.
FEATURES OF PYTHON:
LITERALS:
EXAMPLE
float_literal = 3.14
boolean_literal = True
none_literal = None
list_literal = [1, 2, 3]
tuple_literal = (4, 5, 6)
set_literal = {7, 8, 9}
result = integer_literal + 5
#10+5
#OUTPUT: 15
name = "Bob"
pi = 3.14159
VARIABLES:
1) They can contain both letters and numbers but they cannot begin
with a number.
Variable_name = value
Explanation: The value on the right side is then associated with the
variable name on the left side.
EXAMPLE:
age = 30
user_name = "Alice"
_count = 10
total_score = 150
IDENTIFIERS:
CONSTANTS:
EXAMPLE:
# Define constants
PI = 3.14159
GRAVITY = 9.8
# Use constants
radius = 5
circumference = 2 * PI * radius
printf(“The circumference of the circle is: {circumference}")
KEYWORDS:
➢ import keyword
print(keyword. kwlist)
Keywords Description
False Represents the boolean value
false.
True Represents the boolean value true.
None Represents a null value or no
value at all.
as Used to create an alias while
importing a module.
assert Used for debugging by testing a
condition. If the condition is
False, it raises an exception.
async Used to define asynchronous
functions
await Used to wait for the result of an
asynchronous call
break Terminates the loop prematurely.
class Used to define a class.
continue Skips the rest of the code inside a
loop for the current iteration and
proceeds to the next iteration.
def Used to define a function.
del Deletes objects like variables,
lists, or dictionary elements.
elif Used for conditional branching
(else if). else specifies a block of
code to execute if the condition in
if or elif is false.
except Used to catch exceptions in a try
block.
finally A block of code that will be
executed regardless of an
exception occurring or not.
for Used for looping over an iterable.
from Specifies the module to import
specific parts from.
global Declares a variable as global,
allowing it to be modified outside
the current scope.
if Used for conditional branching.
in Check if an element is present in
a sequence.
is Tests for object identity.
not Logical operator to invert the
truth value of an expression.
or Logical operator to combine
conditional statements.
pass A null operation, is used as a
placeholder.
raise Used to raise an exception.
return Exits a function and optionally
passes back a value.
try Starts a block of code to test for
exceptions.
while Used to create loops that continue
while a condition is true.
with Used to simplify exception
handling and resource
management.
yield Pauses the function execution and
returns a value, allowing it to be
resumed later.
BUILT-IN DATATYPES:
DATATYPES:
➢ In Python, a data type defines the type of value a variable can
hold.
➢ It tells the interpreter what kind of data is being stored like
numbers, text, or more complex structures.
➢ Data types help in allocating memory and performing
operations on variables.
TYPES OF DATATYPES:
Python has two main categories of data types:
[Link] types:
set: Represents an unordered collection of unique elements.
Example:
my_set = {1, 2, 3}
v. Boolean types:
bool: Represents True or False
Example:
is_active = True
OUTPUT STATEMENT:
Output statements in Python are primarily handled by the print()
function, which displays data to the console.
i. Basic Usage
The simplest form of output is printing a string literal:
EXAMPLE:
print("Hello, world!")
# Output:
Hello, world!
INPUT STATEMENTS:
✓ Input statements in Python allow programs to receive data from
users during runtime.
✓ The input() function is used for this purpose.
i) Basic Input
The input() function takes an optional string argument, which serves
as a prompt to the user.
EXAMPLE:
name = input("Enter your name: ")
print("Hello, " + name + "!")
#OUTPUT
Enter your name: kaviya
Hello, kaviya!
i) Single-line comments
Begin with a hash symbol (#). Everything after the # on that line is
considered a comment.
EXAMPLE:
# This is a single-line comment
INDENTATIONS:
✓ Indentation in Python is the whitespace at the beginning of a
code line.
✓ It's crucial because it signifies code block structure.
✓ Unlike languages using curly braces, Python uses indentation to
group statements.
✓ Consistent indentation ensures the code runs as expected.
EXAMPLE:
# Correct indentation
if 5 > 2:
print("Five is greater than two!")
print("This is also inside the if block.")
Importance of Indentation
OPERATORS:
Arithmetic Operators
EXAMPLE:
a = 10
b=5
# Addition
result = a + b # result = 15
# Subtraction
result = a - b # result = 5
# Multiplication
result = a * b # result = 50
# Division
# Floor Division
# Modulus
EXAMPLE:
x=5
y=3
# Equal to
print(x == y) # False
# Not equal to
print(x != y) # True
# Greater than
# Less than
EXAMPLE:
# Assign value 10 to x
x = 10
x += 5
x -= 3
x *= 2
x /= 4
# Equivalent to x = x % 3 (x becomes 0)
x %= 3
Logical Operators
EXAMPLE:
x=5
y = 10
# AND
print(x > 0 and y < 15) # True (both conditions are True)
# OR
# NOT
Bitwise Operators:
a = 5 # 5 in binary: 101
b = 3 # 3 in binary: 011
# AND
# 1 (binary 001)
# OR
print(a | b)
# 7 (binary 111)
# XOR
# 7 (binary 111)
# NOT
print(~a)
# Left Shift
print(a << 1)
# 10 (binary 1010)
# Right Shift
print(a >> 1)
# 2 (binary 010)
Membership Operators:
EXAMPLE:
# In
# Not In
Identity Operators:
a = [1, 2, 3]
b=a
c = [1, 2, 3]
# is
# is not
Syntax:
x = 10 if condition else 5
x = 10
print(result)
# Output: Even
EXPRESSIONS:
EXAMPLE:
num_int = 123
num_float = 1.23
print("Value of num_new:",num_new)
OUTPUT:
EXAMPLE:
num_str = "12"
num_int = 34
num_sum = int(num_str) + num_int
print("The sum of num_str and num_int is:", num_sum)
print("Data type of num_sum:", type(num_sum))
string_int = "10"
string_float = "10.5"
num_int = int(string_int)
num_float = float(string_float)
print("Data type of num_int:", type(num_int))
print("Data type of num_float:", type(num_float))
OUTPUT:
The sum of num_str and num_int is: 46
Data type of num_sum: <class 'int'>
Data type of num_int: <class 'int'>
Data type of num_float: <class 'float'>
PYTHON ARRAYS
DEFINING AND PROCESSING ARRAYS
ARRAYS IN PYTHON:
Defining Arrays:
✓ To use arrays in Python, you first need to import
the array module.
✓ Arrays are defined using the array() constructor, which takes
two arguments: the type code and a list or iterable of initial
values.
EXAMPLE:
arr = [1, 2, 3, 4, 5]
You can access elements in a list using indices, where indexing starts
from 0.
EXAMPLE:
arr = [10, 20, 30, 40, 50]
print(arr[0]) # Output: 10
print(arr[-1]) # Output: 50
EXAMPLE:
[Link](60)
[Link](2, 25)
[Link](40)
popped_value = [Link](1)
print(popped_value) # Output: 20
sliced_arr = arr[1:4]
ARRAY METHODS
arr = [1, 2, 3]
[Link](4)
print(arr)
# Output: [1, 2, 3, 4]
o extend()
arr = [1, 2, 3]
[Link]([4, 5, 6])
print(arr)
# Output: [1, 2, 3, 4, 5, 6]
o insert()
arr = [1, 2, 4]
[Link](2, 3) # Insert 3 at index 2
print(arr)
# Output: [1, 2, 3, 4]
o remove()
arr = [1, 2, 3, 4]
popped_value = [Link](1) # Removes and returns the element
at index 1
print(popped_value) # Output: 2
print(arr)
# Output: [1, 3, 4]
o clear()
arr = [1, 2, 3]
[Link]()
print(arr)
# Output: []
o index()
• Example:
arr = [1, 2, 3, 4]
index_of_3 = [Link](3)
print(index_of_3)
# Output: 2
o count()
arr = [1, 2, 2, 3, 4, 2]
count_of_2 = [Link](2)
print(count_of_2)
# Output: 3
o copy()
arr = [1, 2, 3]
arr_copy = [Link]()
print(arr_copy)
# Output: [1, 2, 3]
3. Sorting and Reversing
o sort()
arr = [3, 1, 4, 5, 2]
[Link]()
print(arr)
# Output: [1, 2, 3, 4, 5]
o sorted()
arr = [3, 1, 4, 5, 2]
sorted_arr = sorted(arr)
print(sorted_arr)
# Output: [1, 2, 3, 4, 5]
print(arr)
# Original list remains unchanged: [3, 1, 4, 5, 2]
o reverse()
arr = [1, 2, 3, 4, 5]
[Link]()
print(arr)
# Output: [5, 4, 3, 2, 1]
o reversed()
arr = [1, 2, 3, 4, 5]
reversed_arr = list(reversed(arr)) # Convert iterator to list
print(reversed_arr)
# Output: [5, 4, 3, 2, 1]
o join()
string = "hello"
list_from_string = list(string)
print(list_from_string)
# Output: ['h', 'e', 'l', 'l', 'o']
o sum()
arr = [1, 2, 3, 4, 5]
print(sum(arr))
# Output: 15
5. List Slicing and Indexing
Python lists also support slicing and indexing for extracting parts of
lists or accessing specific elements.
Slicing
Example:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
slice_arr = arr[Link]
print(slice_arr)
# Output: [3, 5, 7]
Indexing
Example:
arr = [1, 2, 3, 4, 5]
print(arr[0])
# Output: 1
print(arr[-1])
# Output: 5 (last element)
PART A
PART B
PART C
Conditional Statement
• Conditional statements are used to execute
specific blocks of code based on whether
certain conditions evaluate to True or False .
• They are fundamental for controlling the flow
of a Python program and implementing logic.
1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement
Python If statements
The if statement allows you to execute a block of code only if a
specified condition is True .
Syntax:
if condition:
# block of code
Syntax Explanation:
• The condition can be any expression that evaluates to a boolean value
( True or False ).
• If the condition is True , the indented block of code following the if
statement is executed.
• If the condition is False , the block of code is skipped.
Flowchart
Flow Chart: it is a graphical
representation of steps an
algorithm to solve a problem.
Example:
x = 10
if x > 5:
print("x is greater than 5")
Explanation:
• Here, x > 5 is the condition being evaluated.
• Since x is 10 , which is indeed greater than 5 , the print statement "x is
greater than 5" is executed.
2. if - else statements
This construct of python program consist of one if condition with two
blocks. When condition becomes true then executes the block given below
it. If condition evaluates result as false, it will executes the block given
below else.
Syntax:
if condition:
# block of code
else:
# block of code
Syntax Explanation:
• After an if statement, you can optionally add an else statement.
• The else block is executed only if the preceding if condition evaluates to
False .
• You cannot have an else statement without an if statement.
• Flowchart
Example:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Explanation:
Here, x > 5 evaluates to False because x is 3 .
Therefore, the else block "x is not greater than 5" is executed
Example-1:
Age=int(input(“Enter Age: “))
if ( age>=18):
print(“You are eligible for vote”)
else:
print(“You are not eligible for vote”)
Example-2:
N=int(input(“Enter Number: “))
if(n%2==0):
print(N,“ is Even Number”)
else:
print(N,“ is Odd Number”)
Python Ladder if else statements (if-elif-else)
This construct of python program consist of more than one if condition.
When first condition evaluates result as true then executes the block given
below it. If condition evaluates result as false, it transfer the control at else
part to test another condition. So, it is multi-decision making construct.
Syntax:
if ( condition-1):
# block of code
…………………..
elif (condition-2):
# block of code
…………………..
elif (condition-3):
# block of code
…………………..
else:
…………………..
…………………..
Syntax Explanation:
• You can have multiple elif statements to check additional conditions.
• The elif statements are evaluated sequentially from top to bottom.
• Once a condition evaluates to True , the corresponding block of code is
executed, and subsequent conditions are not checked.
Flowchart:
Example:
x=7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
Explanation:
Here, x > 10 is False , so it moves to the next elif condition.
x > 5 is True , so "x is greater than 5 but less than or equal to 10" is printed.
Nested if statements
It is the construct where one if condition take part inside of other if
condition. This construct consist of more than one if condition. Block
executes when condition becomes false and next condition evaluates
when first condition became true.
So, it is also multi-decision making construct.
Syntax:
if ( condition-1):
if (condition-2):
……………
……………
else:
……………
……………
else:
…………………..
…………………..
FlowChart
Example:
x = 15
if x > 10:
print("x is greater than 10")
if x > 20:
print("x is also greater than 20")
else:
print("x is not greater than 20")
Explanation:
• In this example, the outer if statement checks if x > 10 .
• If x is indeed greater than 10 , it enters the inner if statement to check
if x >20 .
• Depending on the value of x , different blocks of code are executed
sequentially.
Example:
num=int(input(“Enter Number: “))
if ( num<=0):
if ( num<0):
Print(“You entered Negative number”)
else:
Print(“You entered Zero ”)
else:
Print(“You entered Positive number”)
Output:
Enter Number:4
You entered Positive number
Program:
while loop
The while loop is conditional construct that executes a block of statements
again and again till given condition remains true. Whenever condition
meets result false then loop will terminate.
Syntax:
Initialization of control variable
while (condition):
…………………..
Updation in control variable
..…………………
Flowchart
Example: print 1 to 10
numbers num=1
# initialization
while(num<=10): # condition testing
print(num, end=” “) #Body of loop
num + = 1 # Increment
Example
Example:
L=list(range(1,20,2)
Print(L) Output: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
For loop
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a string etc.) With for loop we can execute a set of
statements, and for loop can also execute once for each element
in a list, tuple, set etc.
Example: print 1-10 numbers Example: print 10-1
numbers for num in range(1,11,1): for num in range(10,0,-1):
print(num, end=” “) print(num, end=” “)
Output: 1 2 3 4 5 6 7 8 9 10 Output: 10 9 8 7 6 5 4 3 2 1
output:
mango Membership Operators:
apple
grapes The “in” and “not in” are membership
cherry operators. These operators check either
[Link] x in "TIGER": given value is available in sequence or
print(x)
not. The “in” operator returns Boolean
output: True result if value exist in sequence
T otherwise returns Boolean False.
I
G The “not in” operator also returns
E
R
Boolean True / False result but it works
opposite to “in” operator.
else in for Loop
The else keyword in for loop specifies a block of code to be executed when the
loop is finished:
for x in range(4):
print(x, end=” “)
else:
print("\nFinally finished!")
output: 0 1 2 3
Finally finished!
Nested Loops
A nested loop is a loop inside another loop.
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
output:
apple
cherry
UNIT-3
FUNCTIONS AND MODULES
FUNCTIONS:
Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the same
code again and again for different inputs, we can do the function calls to reuse code contained in it
over and over again.
Some Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability
Need for Functions
• Once defined, Python functions can be called multiple times and from any location in a
program.
• Our Python program can be broken up into numerous, easy-to-follow functions if it is
significant.
• The ability to return as many outputs as we want using a variety of arguments is one of
Python's most significant achievements.
However, Python programs have always incurred overhead when calling functions
Calling a Function To call a function, use the function name followed by parenthesis:
>>> MyMsg1()
OUTPUT:
Learning to create function
Calling a Function To call a function, use the function name followed by parenthesis:
>>> MyMsg2(‘john’)
OUTPUT:
John is learning to define Python Function
2. Parameter (argument) Passing
III. Anonymous functions, which are also called lambda functions because they are not
declared with the standard def keyword
x= lambda a,b:a*b
print(x(5, 6)
OUTPUT:
30
FUNCTION DEFINITION
Syntax of function is:
Global Variables are those which are defined outside any function and which are accessible
throughout the program, i.e., inside and outside of every function. Let’s see how to create a Python
global variable.
EXAMPLE:
# This function uses global variable s
def f():
print("Inside Function", s)
# Global scope
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)
OUTPUT
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks
THE return STATEMENT
When a defined function is called, a return statement is written to exit the function and return
the calculated value.
Syntax:
return < expression to be returned as output >
The return statement can be an argument, a statement, or a value, and it is provided as output
when a particular job or function is finished. A declared function will return an empty string if no
return statement is written.
Example1:
def square( num ): Example 2:
return num**2 # Defining a function without return
# Calling function and passing statement
arguments. def square( num ):
print( "With return statement" ) num**2
print( square( 8 ) ) # Calling function and passing
arguments.
OUTPUT: print( "Without return statement" )
With return statement print( square( 8 ) )
64 OUTPUT:
Without return statement
None
FUNCTION ARGUMENTS:
The following are the types of arguments that we can use to call a function:
• Default arguments
• Keyword arguments
• Required arguments
• Variable-length arguments
1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no
worth is provided for the contention when the capability is called. The following example
demonstrates default arguments.
Example:
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
print( "Passing only one argument" )
function(30)
print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a
capability with watchword contentions, the client might tell whose boundary esteem it is by looking at
the boundary name.
We can eliminate or orchestrate specific contentions in an alternate request since the Python
translator will interface the furnished watchwords to connect the qualities with its boundaries. One
more method for utilizing watchwords to summon the capability() strategy is as per the following:
Example:
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
print( "Without using keyword" )
function( 50, 30)
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50
3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined
positional sequence. The number of arguments required in the method call must be the same as those
provided in the function's definition.
We should send two contentions to the capability() all put together; it will return a language
structure blunder, as seen beneath.
Example:
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
print( "Passing out of order arguments" )
function( 30, 20 )
PYTHON STRINGS:
String is a data structure in Python Programming that represents a sequence of characters. It
is an immutable data type, meaning that once you have created a string, you cannot change it. Python
String are used widely in many different applications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be represented as text.
String Operations:
String Concatenation:
The + operator adds the multiple strings together. Strings must be assigned to the different
variables because strings are immutable. Let's understand the following example.
Example:
str1 = "Hello "
str2 = "Coders"
str3 = str1 + str2
print("The new combined string is:",str3)
Output:
The new combined string is: Hello Coders
String Appending:
Append means to add something at the [Link] python you can add one string at the end of
another string using the += operator.
Example:
Str=”Hello,”
name=input(“\n Enter your name:”)
str+=name
str+=”.Welcome to Python Programming.”
Print(str)
Output:
Enter your name:Mani
Hello,Mani. Welcome to Python Programming.
String Repeating:
The * operator used to repeat the string n number of times
Example:
Str=”Hello”
Print(str*3)
Output:
Hello Hello Hello
STRINGS ARE IMMUTABLE:
Since strings in Python are immutable data structures, we cannot add or edit any data. We
encountered warnings stating that strings are not changeable when modifying any section of the
[Link] is an illustration of that:
Example: 3 string = 'hello world'
string = 'hello world' 4
string[0] = 'X' ----> 5 string[0] = 'X'
print(string) 6
7 print(string)
Output: TypeError: 'str' object does not support item
TypeError Traceback (most recent call last) assignment
<ipython-input-3-4e0fff91061f>in <module>
Output:
4.0
720
The dir() Built-in Function
We may use the dir() method to identify names declared within a module.
For instance, we have the following names in the standard module str. To print the names, we
will use the dir() method in the following way:
Example:
# Here, we are creating a simple Python program to print the directory of a module
print( "List of functions:\n ", dir( str ), end=", " )
Output:
List of functions:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
MODULES AND NAMESPACES:
In Python, everything is an object like variable, function, etc. A name is nothing but something that we
use to refer to an object. It is also called an identifier.
For example, in the code below, ‘text’ is an identifier to the variable that stores ‘PythonGeeks’.
• local and global namespace variables can be accessed by a Python statement. When two
variables with the same name are local and global, the local variable takes the role of the
global variable. There is a separate local namespace for every function.
• The scoping rule for class methods is the same as for regular functions. Python
determines if parameters are local or global based on reasonable predictions.
• Any variable that is allocated a value in a method is regarded as being local.
• Therefore, we must use the global statement before we may provide a value to a global
variable inside of a function.
• Python is informed that Var_Name is a global variable by the line global Var_Name.
Python stops looking for the variable inside the local namespace.
• We declare the variable Number, for instance, within the global namespace. Since we
provide a Number a value inside the function, Python considers a Number to be a local
variable.
• UnboundLocalError will be the outcome if we try to access the value of the local variable
without or before declaring it global.
Example:
Number = 204
def AddNumber():
Number = Number + 200
print("The number is:", Number)
AddNumber()
print("The number is:", Number)
Output:
The number is: 204
The number is: 40
a. Built-in Namespace in Python
This namespace gets created when the interpreter starts. It stores all the keywords or the built-
in names. This is the superset of all the Namespaces. This is the reason we can use print, True, etc.
from any part of the code.
Output:
Python
PythonGeeks
When we print ‘var’ inside the function we could see the changed value but couldn’t observe the
same outside the function. This is because the local namespace is isolated and creates its own variable
‘var’.
To avoid this we can use the keyword ‘global’ inside the function for the ‘var’.
Look at the below results.
Output:
Python
Python
The use of global keywords tells the interpreter to use the global variable, rather than creating
its own. This makes us observe the changes globally.
The same concept applies to nested functions, a local namespace exists separately for that
function. And it exists only during the function’s execution.
import mymodule
a = mymodule.person1["age"]
print(a)
OUTPUT:36
UNIT IV
List
Definition:
✓ A list is a built-in dynamic sized array (automatically grows and shrinks).
✓ We can store all types of items (including another list) in a list.
✓ A list may contain mixed type of items, this is possible because a list
mainly stores references at contiguous locations and actual items maybe
stored at different locations.
✓ List can contain duplicate items.
✓ List in Python are Mutable. Hence, we can modify, replace or delete the
items.
✓ List are ordered. It maintain the order of elements based on how they are
added.
✓ Accessing items in List can be done directly using their position (index),
starting from 0.
Example:
# Creating a Python list with different data types
a = [10, 20, "GfG", 40, True]
print(a)
Creating a List
print(a)
print(b)
print(c)
Using list() Constructor
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)
Output:
[1, 2, 3, 'apple', 4.5]
Example:
a = [10, 20, 30, 40, 50]
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
Output: 5
[Link]
Iteration involves looping through the elements of a list.
Code:
# Example of iteration
my_list = ['apple', 'banana', 'cherry']
for item in my_list:
print(item)
Output:
apple
banana
cherry
[Link]
Membership checks if an element is present in the list.
# Example of membership
my_list = [10, 20, 30, 40]
is_present = 20 in my_list
print(is_present)
Output: True
is_present = 50 in my_list
print(is_present)
Output: False
List methods:
The list data type has some more methods. Here are all of the methods of list
objects:
• Del()
• Append()
• Extend()
• Insert()
• Remove()
• Reverse()
• Sort()
Delete:
Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x [5, 8, 6] ------------
>>> del(x)
>>> x # complete list gets deleted
Append:
Append an item to a list
>>> x=[1,5,8,4]
>>>[Link](10)
>>> x [1, 5, 8, 4, 10]
Extend:
Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>>[Link](y)
>>> x [1, 2, 3, 4, 3, 6, 9, 1]
Insert:
To add an item at the specified index, use the insert () method
>>> x=[1,2,4,6,7]
>>>[Link](2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
Remove:
The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>>[Link](33)
>>> x
[1, 2, 10, 4, 6]
>>>[Link](4)
>>> x
[1, 2, 10, 6]
Reverse:
Reverse the order of a given list.
>>> x=[1,2,3,4,5,6,7]
>>>[Link]()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort:
Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>>[Link]()
>>> x
[1, 2, 3, 4, 5, 6, 7]
Tuple:
✓ A comma-separated group of items is called a Tuple .Tuples are used to store
multiple items in a single variable.
✓ Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities and
usage.
✓ A tuple is a collection which is ordered and unchangeable.
✓ Tuples are written with round brackets ( ) .
✓ The main difference between the two is that we cannot alter the components
of a tuple once they have been assigned. On the other hand, we can edit the
contents of a list.
Create a List of Tuples
• Use parentheses () to create a tuple and separate elements with commas.
• Tuples can also be created without parentheses.
Example:
# This is a tuple with parentheses
my_tuple = (1, 2, 3)
# This is also a triple, which is just a tuple with exactly three items
my_triple = (1, 2, 3)
# This is a tuple without parentheses (Python allows this)
another_tuple = 4, 5, 6
print(type(my_tuple)) # <class 'tuple'>
print(type(my_triple)) # <class 'tuple'>
print(type(another_tuple)) # <class 'tuple'>
EXAMPLE:
Creating tuples
tuple1 = (1, 2, 3, 4)
tuple2 = (1,3.14)
tuple3 = (1,) # A tuple with one element (note the comma)
# Tuple without parentheses
tuple4 = 1, 2, 3, 4
# Accessing elements
print(tuple1[0]) # Output: 1
print(tuple2[1]) # Output: hello
# Slicing
print(tuple1[1:3]) # Output: (2, 3)
output:
('apple', 'banana', 'cherry')
Access Tuple Items
You can access tuple items by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
Thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
output:
banana
Updating Tuples:
Tuples are immutable which means you cannot update or change the values
of tuple elements. You are able to take portions of existing tuples to create new
tuples as the following example demonstrates
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# tup1[0] = 100; # This action is not valid for tuples
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print (tup3)
When the above code is executed, it produces the following
result − (12, 34.56, 'abc', 'xyz')
1. tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
This last element, which consists of three items enclosed in parenthesis, is
known as a nested tuple since it is contained inside another tuple. The name of the
main tuple with the index value, tuple[index], can be used to obtain the nested tuple,
and we can access each item of the nested tuple by using tuple[index-1][index-2].
Example of a Nested Tuple
# Python program to create a nested tuple
Dictionary
Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a
given key.
Updating Dictionary:
You can update a dictionary by adding a new entry or item(i.e., a key-value pair),
modifying an existing entry, or deleting an existing entry as shown below in the
simple example:
dict = {'Name': 'abi', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print (dict['Age']: ", dict['Age'])
print (dict['School']: ", dict['School'])
When the above code is executed, it produces the following result:
dict['Age']: 8
dict['School']: DPS School
dic[5]="Hello"
dic[6]="Wonder"
print(len (dic))
print(dic)
OUTPUT:
4
3
5
{1: 'This', 3: 'The', 4: 'World', 5: 'Hello', 6: 'Wonder'}
clear()
(ii)
This method is used to remove the elements of the dictionary. It produces
an empty dictionary. It will only delete elements not a dictionary. It does not
take any parameter and does not return any value.
Syntax
dictionary_name.clear()
For example,
>>>dic1 ={“Project” : “All In One”, “Days” : 15, “Level” : “High”}
>>>[Link]()
>>>dic1
{}
If you want to delete the dictionary with its elements, then del keyword is
used.
>>>dic1 {“Project” : “All in One”, “Days” : 15, “Level” : “High”}
>>>del dic1
>>>dic1
Trackback (most recent call last) :
File “<pyshell#5>”, line1, in <module> dic1
NameError : name ‘dic1’ is not defined
(iii)get()
This method returns the value for the given key, if present in the dictionary. It
takes maximum of two parameters.
Syntax
dictionary_name.get (Key[, value])
Here, Key to be searched in the dictionary value (optional) value to be returned if
the key not found. The default value is None.
For example,
>>>Student {‘Name’: ‘Siva’, ‘Roll No’: 21, ‘Marks’: 459, ‘Class’: 12}
>>>Student {‘Class’ : 12, ‘Roll No’ : 21, ‘Marks’ : 459, ‘Name’ : ‘Siva’}
>>>[Link] (‘Name’) ‘Siva’
>>>[Link] (‘Age’, ‘Not Found’) ‘Not Found’
>>>[Link] (‘Marks’, ‘Not Found’) 459
(iv)values ( )
This method returns a view object that displays a list of all the values in the
dictionary. It does not take any parameters.
Syntax
dictionary_name.values ()
For example,
>>>Teacher {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, ‘Salary’ : 28000,
‘Experience’ : 4}
>>>[Link]()
dict_values([28000, ‘Science’, ‘4’, ‘Akshat’])
(v) update ( )
This method updates the dictionary with the elements from the another
dictionary object or from an iterable of key/value pairs.
Syntax
dictionary_name1.update (dictionary_name2)
For example,
>>>Teacher {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, ‘Salary’ : 28000}
>>>[Link](Teacher1)
>>>Teacher
(‘Salary’ : 25000, ‘Subject’, ‘Science’, ‘Experience’ : 5, ‘Name’ :
Akansha}
(vi) sorted ()
This method returns a sorted sequence of the keys in the dictionary.
Syntax
sorted (dictionary_name)
For example,
>>>Teacher {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, ‘Salary’ : 28000,
‘Experience’ : 4}
>>>sorted(Teacher)
[‘Experience’, ‘Name’, ‘Salary’, ‘Subject’]
(vii)copy()
This method returns a shallow copy of the dictionary.
Syntax
[Link]( )
Here, copy( ) method does not take any parameters.
For example,
dic = {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’} dic1 = dic. copy ( )
print (‘Original dictionary : ’, dic) print (‘Copied
dictionary : ’, dic1)
Output
Original dictionary : {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’}
Copied dictionary : {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’}
(viii)pop item ()
This method in dictionary helps to achieve similar purpose. It removes the
arbitrary key value pair from the dictionary and returns it as a tuple. There is an
update for this method from Python version 3.7 onwards.
Syntax
[Link]( )
For example,
dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} print (‘Before
deletion : ’, dic)
dic1 = [Link] ( )
print (‘Deleted element’, dic1) print (‘After deletion :’,
dic)
Output
Before deletion : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} Deleted element :
(‘Shrey’, : 27)
After deletion : {‘Akshat’ : 26, ‘Riya’ : 24}
(ix) max ()
This method is used to return the maximum key from the dictionary.
Syntax
max(dict)
For example,
dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} dic1 = max(dic)
print (‘Dictionary : ’, dic) print (‘Maximum key : ’,
dic1)
Output
Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
Maximum key : Shrey
(x) min ()
This method is used to return the minimum key from the dictionary.
Syntax
min(dict)
For example,
dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} dic1 = min(dic)
print (‘Dictionary :’, dic) print (‘Minimum key :’,
dic1)
Output
Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
Minimum key : Akshat
1. Introduction to Files:
When a program is being executed, its data is stored in RAM. Though
RAM can be accessed faster by the CPU,it is also volatile, which means
when the program ends, or the computer shuts down, all the data is lost. If
you want to use the data in future,then you need to store this data on a
permanent or non- volatile storage media such as hard disk, USB drive
and DVD etc,
A file is a collection of data stored on a secondary storage device like hard
disk.
A file is basically used because real-life applications involve large
amounts of data and in such situations the console oriented I/O
operations pose two major problems:
First, it becomes cumbersome and time consuming to handle huge
amount of data through terminals.
Second, when doing I/O using terminal, the entire data is lost when
either the program is terminated or computer is turned off. Therefore, it
becomes necessary to store data on a permanent storage (the disks) and
read whenever necessary, without destroying the data.
2. File Types
Like C and C++,Python also supports two types of files
1. ASCII Text Files
2. Binary Files
[Link] Text Files
A text file is a stream of characters that can be sequentially
processed by a computer in forward direction. For this reason a
text file is usually opened for only one kind of operation (reading,
writing, or appending) at any given time.
Because text files can process characters, they can only read or
write data one character at a time. In Python, a text stream is
treated as a special kind of file.
Depending on the requirements of the operating system and on the
operation that has to be performed (read/write operation) on the file,
the newline characters may be converted to or from carriage-
return/linefeed combinations.
Besides this, other character conversions may also be done to
satisfy the storage requirements of the operating system.
However, these conversions occur transparently to process a text
file. In a text file, each line contains zero or more characters and
ends with one or more characters.
Another important thing is that when a text file is used, there are
actually two representations of data- internal or external.
For example, an integer value will be represented as a number that
occupies 2 or 4 bytes of memory internally but externally the
integer value will be represented as a string of characters
representing its decimal or hexadecimal value.
Note: In a text file, each line of data ends with a newline character. Each file
ends with a special character called end-of-file (EOF) Marker.
2.2 Binary Files
A binary file is a file which may contain any type of data, encoded in
binary form for computer storage and processing purposes. It includes
files such as word processing documents, PDFs, images, spreadsheets,
videos, zip files and other executable programs.
Like a text file, a binary file is a collection of bytes. A binary file is
also referred to as a character stream with following two essential
differences.
A binary file does not require any special processing of the data and
each byte of data is transferred to or from the disk unprocessed.
Python places no constructs on the file, and it may be read from, or
written to, in any manner the programmer wants.
While text files can be processed sequentially, binary files, on the
other hand, can be either processed sequentially or randomly
depending on the needs of the application.
While an absolute path always contains the root and the complete
directory list to specify the exact location the file.
Example:To access BTech_CS.docx,The absolute path
is C:\Students\Under Graduate\BTech_CS.docx
Relative path needs to be combined with another path in order to
access a file. It starts with respect to the current working directory and
therefore lacks the leading slashes.
Example: Suppose you are working on current directory Under Graduate in
order to access BTech_CS.docx,The Relative path is
Under Graduate\BTech_CS.docx
4. File Operations
Where file_name is a string value that specifies name of the file that you
want to access. access_mode indicates the mode in which the file has to be
opened, i.e., read, write, append, etc.
Example:Write a Program to print the details of file object
Writing A File
The write() method is used to write a string to an already opened file.
Of course this string may include numbers, special characters or other
symbols.
While writing data to a file, you must remember that the write()
method does not add a newline character ('\n') to the end of the string.
writeline() method:
The writelines() method is used to write a list of strings.
Example:Program to write to afile using the writelines()
method
file=open('[Link]','w')
lines=['hello','cse','hope to enjoy','learning','python programming']
[Link](line)
[Link]()
print('file writing
successful') [Link]
append() method:
Once you have stored some data in a file,you can always open that file
again to write more data or append data to it.
To append a file, you must open it using „a‟ or „ab‟ mode depending on
whether it is text file or binary file.
Note that if you open a file with „w‟ or „wb‟ mode and then start writing
data into it, then the existing contents would be overwritten.
Example:Program to append data to an already existing file
file=open('[Link]','a')
[Link]('\nHave a nice day')
[Link]()
print('Data appended successful')
Output:
Data appended successful
[Link]
readlines() Method
readlines() Method is used to read all the lines in the file.
Example:Program to demonstrate readlines() function
file=open('[Link]','r')
print([Link]()) [Link]
[Link]() hellocsehope to enjoylearningpython
Output:
programming
['hellocsehope to enjoylearningpython Have a nice day'Have a nice day']
programming\n',
list() Method
list() method is also used to display entire contents of the [Link] need
to pass the file object as an argument to the list() method.
Example: Program to display the contents of the file [Link] using the
list() method
[Link]
file=open('[Link]','r')
print(list(file)) hellocsehope to enjoylearningpython
[Link]()
programmingHave a nice day
Output:
['hellocsehope to enjoylearningpython programming\n', 'Have a nice day']
Splitting Words:
Python allows you to read line(s) from a file and splits the line
(treated as a string) based on a character. By default, this character
is space but you can even specify any other character to split words
in the string.
Example: Program to split the line into series of words and use space to
perform the split operation
with open('[Link]','r') as [Link]
file: line=[Link]()
words=[Link]() hellocsehope to enjoylearningpython programming
print(words)
Output:
5. Typesof Arguments
5.1 Command line Arguments:
The Python sys module provides access to any command-line
arguments via the [Link]. This serves two purposes −
[Link] is the list of command-line arguments.
len([Link]) is the number of command-line arguments.
Here [Link][0] is the program ie. script name.
Example1:Write a Python program to demonstrate the usage of Command
Line Arguments
[Link]
#!/usr/bin/python
import sys
print ('Number of arguments:', len([Link]),
'arguments.') print ('Argument List:', str([Link]))
Output:
Output:
The no of lines in a given file is
2
The no of words in a given file is
8
The no of chars in a given file is
63
[Link]
Python handles absolute paths by specifying the complete directory list from the root to the target file, ensuring consistent file access regardless of the working directory. Relative paths start from the current directory, allowing for more flexible and environment-specific file location referencing. Absolute paths provide stability and predictability, crucial for cross-platform applications, while relative paths aid in portability and ease of adjustments across different environments. Choosing between them depends on the specific requirements for program deployment and usage scenarios.
Data types in Python are critical for defining the type of value a variable holds, influencing both how much memory is allocated and what operations can be performed on it. Effective data type usage allows the Python interpreter to manage memory efficiently, making programs faster and more efficient. Python supports both built-in data types like 'int', 'float', and 'str', and user-defined types, providing flexibility and robustness in handling varied data types and structures. Proper understanding and usage of data types help in preventing data errors and improving algorithm efficiency.
The 'pass' statement acts as a placeholder, allowing developers to define syntactically required code blocks, like empty loops or function bodies, without executing any operations. This facilitates iterative development by enabling code scaffolding, allowing developers to outline code structures for future development without causing syntax errors. It helps in maintaining code integrity when a particular block logic is yet to be implemented.
The 'read' method reads the entire file or a specified number of bytes, 'readline' reads a single line, and 'readlines' reads all lines and returns them as a list. 'Read' is suitable for handling small files, 'readline' is useful for processing files line-by-line without loading the entire content into memory, and 'readlines' is effective for obtaining all lines at once when dealing with manageable text sizes. Each method is chosen based on the file size, parsing requirement, and memory considerations.
The 'assert' keyword in Python is used for debugging purposes by testing a condition. If the condition evaluates to False, an AssertionError is raised, which helps identify logical errors in the code during development. This can otherwise be difficult to spot through normal operation and ensures that the expected program state is maintained as per assumptions.
Python's file handling uses the 'with' keyword to ensure that files are properly closed after operations, even if errors occur. This context manager handles the closing of open files automatically after their block of code is executed, maintaining resource integrity. While the 'open' function initiates file access, 'close' frees up system resources once operations are completed. This practice prevents data corruption and unintentional file lock states, contributing to stability and reliability of programs.
The 'break' statement terminates the loop entirely, skipping any remaining iterations, whereas the 'continue' statement skips the current iteration and proceeds to the next one. 'Break' can be used to exit a loop early if a certain condition is met, whereas 'continue' is used when specific conditions need to bypass certain part of the loop's code to proceed with the next iteration.
Slice operations in Python allow for extracting a subsequence from a list, using a specified start, stop, and step index. This provides a powerful tool for accessing and manipulating portions of the data efficiently. For example, given a list 'arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]', the operation 'arr[2:7:2]' will output '[3, 5, 7]', demonstrating selective extraction based on the defined step.
Functions in Python provide several advantages such as increasing code readability, promoting reusability, and enhancing maintainability. They allow grouping commonly performed operations, which reduces redundancy and minimizes errors. Functions support better organization of code, making it easier to debug and update. By allowing abstraction, functions enable breakdown of complex problems into simpler sub-problems, facilitating comprehensive testing and modular development.
Python's reserved keywords, such as 'def', 'class', 'if', and 'else', have predefined meanings and cannot be used as ordinary identifiers, ensuring a clear distinction between standard language constructs and user-defined names. This design minimizes ambiguity, enforcing consistent structure and behavior, which reduces errors related to accidental keyword conflicts. It also enhances code readability by ensuring universal understanding of these operations within the Python community.