PYTHON Full Notes
PYTHON Full Notes
PYTHON Full Notes
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.
HISTORY of PYTHON:
PYTHON FEATURES:
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential features.
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) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java or
C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc.
So, we can say that Python is a portable language. It enables programmers to develop the software
for several competing platforms by writing a program only once.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official website www.python.org.
It has a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source means,
"Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.
7) 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.
8) Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning, web developer,
and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas,
Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web
development.
9) GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are
the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line
like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use Python
source code in another programming language as well. It can embed other language into our code.
12. 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 15 to x, then we don't need to write int x = 15. Just write x = 15.
Usage of Python
Python is a general purpose, open source, high-level programming language and also provides
number of libraries and frameworks. Python has gained popularity because of its simplicity, easy
syntax and user-friendly environment. The usage of Python as follows.
Desktop Applications
Web Applications
Data Science
Artificial Intelligence
Machine Learning
Scientific Computing
Robotics
Internet of Things (IoT)
Gaming
Mobile Apps
Data Analysis and Preprocessing
PYTHON LITERAL:
A literal in Python is a way to represent a fixed value or raw data in the source code. It directly
appears in the program and does not change during the execution of a program.
Literals can be either numbers, text, boolean, or any other form of data.
In Python program, we use literals to create fixed values that are assigned to variables, constants,
used in expressions, or passed to functions.
For example, suppose we want to setting a variable with a specific value in a Python program. We
will write the code for it as:
x = 10
This statement creates an integer object containing a literal value 10. Literal means simply a value.
Some other examples of literal in Python are 100, x, 2.25, “Hello”, ‘World’, True, False, and so on.
Literals can be any of the primitive data types in Python language. The way of using literals depends
on its type. The various types of literals used in the Python program are as follows:
String literals
Numeric literals
Boolean literals
Literal Collections
Special Literals
Let’s look at the following diagrammatic representation of the classification of Python literals.
String Literals
A string literal in Python is a consecutive sequence of characters used to store and represent
messages, heading, and other text-based information.
It is enclosed within a pair of double quotation marks and single quotation marks. Both are
applicable to define the string literals.
“Hello”, ‘World’, “123”, ‘The area of rectangle is: ‘, etc are some examples of string literals. We use
quotation marks to start and end the string.
Strings in Python are immutable, meaning that when we perform an operation on strings, the Python
interpreter always creates a new string object in the memory, rather than mutating an existing string
object.
String object provides several methods in Python that we will gain knowledge in the further tutorial.
Types of Strings
Python language supports two types of string objects.
1) Single-line String: A string created in a single line is called single-line string. An example of a
single-line string object is as below:
single_line_string = ‘Scientech Easy’ # Here, literal is Scientech Easy.
2) Multi-line String: A piece of statement written in multiple lines is called multiple lines string. In
Python, there are two ways to create multi-line string objects.
a) Adding a black slash (\) at the end of each line. An example of it is:
multi_line_string = 'Welcome \
to \
Scientech Easy'
print(multi_line_string)
Output:
Welcome to Scientech Easy
b) We can also create a multi-line string literal using triple quotation marks. An example of it is as
below:
multi_line_string = '''Welcome \
to \
Scientech Easy, \
Dhanbad'''
print(multi_line_string)
Output:
Welcome to Scientech Easy, Dhanbad
Numeric literals
Numeric literals in Python consists of numbers or digits from 0 to 9. They may be preceded by a
positive (+) or negative (-) sign.
All numeric literals in Python are immutable (unchangeable) objects, meaning that when we perform
an operation on a number object, the Python interpreter always creates a new number object.
Operation performed on numbers are called arithmetic operations.We can classify numeric literals in
Python into three types that are as follows:
Integer literals
Floating point literals
Complex literals
Integer literals in Python
We know an integer is a whole number without any decimal point. It comprises a consecutive
sequence of digits, from (0 to 9). An integer can be positive or negative. An integer literal comes into
a different number system:
Decimal literal (base 10)
Octal literal (base 8)
Hexadecimal literal (base 16)
a) Decimal literal: A decimal literal is a consecutive sequence of digits, from (0 to 9) in which the
first digit is nonzero. It is the most commonly used number system in any programming language.
If a decimal literal consists of two or more digits, the first digit must be some other digit than zero
because the Python interpreter will consider it as an octal number. Some examples of decimal literals
are 10, 30, 33, 676, 20,000, etc.
b) Octal literal: An octal literal consists of 0, followed by the sequence of any of the digits from 0 to
7. The first digit must be 0 in order to identify as an octal literal. For example: 01, 025, 02799, etc.
c) Hexadecimal literal: This literal comprises any of the digits from 0 to 9 and letters from A to F,
representing decimal values from 10 to 15. A hexadecimal integer literal starts with either 0x or 0X.
For example: 0x124, 0X12345, 0x10,000.
Rules for creating integer literals
The following are the rules for creating integer literals:
a) Python does not allow to use commas, or blank spaces in an integer literal. Some examples of
valid integer literals are 20, 40, 140, 1990, etc. Invalid integer literals are 20,5; 30 50, etc.
b) Integer literals may be positive or negative. If no sign precedes an integer literal, Python considers
it as positive. Some example of valid integer literals are +20; -40; 130; -1999. Invalid integer literals
are 20-5; 0x-120.
c) Python does not allow to have a decimal point in integer literals. Some of invalid integer literals
having decimal point are 30.5; 40.50; 0x4.25.
d) Integer literals must contain at least one digit, for example, 0.
e) The value of an integer literal should lie within the range of integers.
Note that the print() function always outputs integer using decimal representation, even if they
are specified as octal or hexadecimal. The following example code shows the output 50 in three
forms:
x = 50 # Decimal integer
y = 0o62 # Octal integer
z = 0x32 # Hexadecimal integer
print("Decimal literal representation: ", x)
print("Octal literal representation: ", y)
print("Hexadecimal representation: ", z)
Output:
Decimal literal representation: 50
Octal literal representation: 50
Hexadecimal representation: 50
Floating-point literals in Python
A floating-point literal is a real number that contains a decimal point (.) or exponent sign or both,
differentiating them from integer literals. We can express them in either standard or scientific
notation, which is explained in the below:
a) Standard notation: In this notation, the floating point numbers contain an integer part or fractional
part with a decimal point in between two parts.
For example: 15.5, -10.50, 333.999, 9.0, -1234.567, and so on. The following are the general rules
for creating floating point literals in standard notation:
1. A decimal point must be present. Valid examples are 20.30, -150, 0.9999, etc.
2. We cannot use commas, or blanks with real literals.
3. A floating-point literal can be positive or negative. If any sign does not precede a literal, then the
interpreter will consider it as a positive number. For example: +2734.365, 234.55, -1234.55, and so
on.
b) Scientific notation: In scientific notation, a number contains two parts such as mantissa and
exponent. The mantissa part represents the floating point number and the exponent part specifies a
power of 10 by which the number is to be multiplied.
The letter E or e separates the mantissa and exponential portion of a number. For instance, we can
represent a number 24.55 in the exponential form as 2.455e2 (i.e. 2.455*10^2).
Here, the number 2.455 specifies the mantissa part and the part after the letter e specifies the
exponent part which has a base value 10.
In general, we use exponential form to represent the large numbers in order to writing large number
of 0s in a number. For instance, 5,000,000 can be written as 5.0e6.
Rules for creating floating point literals in scientific notation
There are the following rules for creating floating point literals in scientific notation. They are:
1. The mantissa part can be in integer or decimal form. A positive or negative sign can precede it.
The default sign is positive. For example, we can write 25.5 as 2.55e1 or 255e-1, or 0.255e2.
2. The exponent part must contain at least one digit, which should be a positive or negative integer.
The default sign is +ve. Valid examples are 2.32e+1; 234e-1. Invalid examples are 2.0e; -121e;
+1260e.
3. Spaces are not allowed in the mantissa part and in the exponent part. For instance, 5 5.44e-5, 525,
6e-6 are invalid.
4. We can write the letter e in both uppercase or lowercase. For example, 5.2e7, 1.3E7.
5. We can leave out the decimal point if we include the exponent part. For example, we can represent
0.95 as 95e-2.
Note that the print() function always outputs integer floating-point numbers. Even if they are
specified in the exponential form. Look at the following example code of Python floating point
literals.
x = 75e-2
y = 0.75
print(x)
print(y)
Output:
0.75
0.75
Complex literal
A complex number comprises two floating-point values, one each for the real and imaginary. A
complex literal is represented by (a + bj).
Here, a is a real part and the b with j is the imaginary or complex part. The letter j represents the
square root of -1. In mathematics, we use the letter i. An example code of it is below.
# complex literal
a = 5 + 10j
b = 2j
print(a)
print(b)
Output:
(5+10j)
2j
Boolean literals:
A boolean literal is a logical value that can have any of the two values: True or False. True represents
the value 1 whereas False represents the value 0.
We use boolean literal in certain operations in which need a boolean value. We use boolean value to
test whether a condition is true or false. Let’s take an example based on it.
# boolean literals
a = (9 == 9)
b = (5 == False)
c = True + 5
d = False + 5
print("a is ", a)
print("b is ", b)
print("c is ", c)
print("d is ", d)
Output:
a is True
b is False
c is 6
d is 5
You can observe in the above example, we have used boolean literals for numerical comparison.
Based on the conditions, we received the outputs True and False, respectively.
Special literals in Python:
Python language contains only one special literal, i.e., None. It is a special constant in Python that
specifies the null value or the absence of a value. We use None to specify a field that is not
constructed. We also use None at the end of lists in Python. Let’s take an example on it.
# Special literals
a = None
print(a)
Output:
None
You must make a note that None does not imply False, 0, or an empty list, dictionary, string, and so
on.
Collection literals in Python:
A collection literal is a syntactic representation that is used to work with more than one value.
Python language provides the four types of collection literal tokens, such as List, Tuple, Dictionary,
and Set. Let’s understand each one by one.
List literals
A list is a collection of mutable data or values of different types. To create a list in Python, place data
or values in within square brackets ([ ]) and separating them by commas (,).
You can consider the Python lists similar to arrays in C, C++, or Java. To declare a list in Python, the
syntax is as:
<name of list> = [ <value1>, <value2>, <value3>, . . . . ]
Let’s take an example based on it.
# List literals
address = ['Scientech Easy', 'Joraphatak Road', 'Dhanbad']
print(address)
Output:
['Scientech Easy', 'Joraphatak Road', 'Dhanbad']
Let’s take another example in which we will assign the first 10 natural numbers and print the
numbers in a list called num.
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(num)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Dictionary Literals
Python dictionary is a collection of data that stores value in a key-value pairs. They are enclosed in
curly braces ({ }) and separated by the commas (,).
Dictionary literals in Python are mutable (changeable) and can also contain different types of data or
values. Let’s take an example based on it.
# Dictionary literals
fruits_dict = {'a': 'apple',
'o': 'orange',
'b': 'banana'}
print(fruits_dict)
Output:
{'a': 'apple', 'o': 'orange', 'b': 'banana'}
Tuple Literals
Tuple in Python is a collection of different data-type, similar to a list. It is immutable, which means
we cannot change it after creation. It performs the same operation as a list does.
The parentheses ( ( ) ) enclose it and the comma separates each element of tuples. Below is an
example code of tuple literals.
# tuple literals
even_numbers = (2, 4, 6, 8, 10, 12)
vowels = ('a','e','i','o','u')
direction = ('North', 'South', 'East', 'West')
print(even_numbers)
print(vowels)
print(direction)
Output:
(2, 4, 6, 8, 10, 12)
('a', 'e', 'i', 'o', 'u')
('North', 'South', 'East', 'West')
Set Literals
Set literals in Python are a well-defined collection of unordered data that cannot be changed. The
elements of a set are enclosed within curly brackets separated by commas (,). Let’s see an example
code for it.
# Set literals
fruits = {'Apple', 'Mango', 'Banana', 'Orange', 'Grape'}
print(fruits)
Output:
{'Orange', 'Apple', 'Grape', 'Banana', 'Mango'}
CONSTANT:
a constant term is used in Mathematics, a value or quantity that never changes.
In programming, a constant refers to the name associated with a value that never changes during
the programming execution.
Programming constant is different from other constants, and it consists of two things - a name
and an associated value.
A real-life example is - The speed of light, the number of minutes in an hour, and the name of a
project's root folder.
Some advantages of constant:
o Improved Readability - It helps to improve the readability of the code. For example, it is
easier to read and understand a constant named MAX_SPEED than the substantial speed
value itself.
o Clear communication of intent - Most developers consider the 3.14 as the pi constant.
However, the Pi, pi, or PI name will communicate intent more clearly. This practice will
allow another developer to understand our code.
o Better Maintainability - Constants allow us to use the same value throughout your code.
Suppose we want to update the constant's value; we don't need to change every instance.
o Low risk of errors - A constant representing a given value throughout a program is less
error-prone. If we want to change the precision in the calculations, replacing the value can be
risky. Instead of replacing it, we can create different constants for different precision levels
and change the code where we needed.
o Thread-safe data storage - A constants are thread-safe objects, meaning several threads can
simultaneously use a constant without risking losing data.
Built-in Constants:
In the official documentation, the True and False are listed as the first constant. These are Python
Boolean values and are the instance of the int. A True has a value of 1, and False has a value 0.
Example -
>>> True
True
>>> False
False
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> int(True)
1
>>> int(False)
0
>>> True = 42
...
SyntaxError: cannot assign to True
>>> True is True
True
>>> False is False
True
PYTHON VARIABLES:
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
x=5
y = "John"
print(x)
print(y)
Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and smart
enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.
Identifier Naming:
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
o The first character of the variable must be an alphabet or underscore ( _ ).
o All the characters except the first character may be an alphabet of lower-case(a-z), upper-case
(A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are
used to denote objects by that name.
Let's understand the following example
a = 50
In the above image, the variable a refers to an integer object.
Suppose we assign the integer value 50 to a new variable b.
a = 50
b=a
The variable b refers to the same object that a points to because Python does not create another
object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Python manages memory efficiently if we assign the same variable to two different values.
Object Identity
In Python, every created object identifies uniquely in Python. Python provides the guaranteed that no
two objects will have the same identifier. The built-in id() function, is used to identify the object
identifier.
Consider the following example.
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
Output:
140734982691168
140734982691168
2822056960944
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
Explanation:
In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside the
function. If we try to use them outside the function, we get a following error.
add()
# Accessing local variable outside the function
print(a)
Output:
The sum is: 50
print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw the NameError.
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.
Example -
Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we defined a function
and accessed the declared variable using the global keyword inside the function. Now we can modify
its value. Then, we assigned a new string value to the variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.
Delete a variable:
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
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.
Example -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Output:
6
BASIC FUNDAMENTALS:
i)Tokens and their types.
ii) Comments
a)Tokens:
The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
The token is the smallest unit inside the given program.
There are following tokens in Python:
Keywords.
Identifiers.
Literals.
Operators.
KEYWORDS:
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions.
You'll never need to import any keyword into your program because they're permanently
present.
Python's built-in methods and classes are not the same as the keywords.
Built-in methods and classes are constantly present; however, they are not as limited in their
application as keywords.
# Pyt
False await else import pass
h on pr
o gram
None break except in raise
t o de
m onstr
True class finally is return
a te th
e appli
and continue for lambda try
c ation
o as def from nonlocal while f iske
y word
( assert del global not with )
# imp
o async elif if or yield rting
k eywo
rd library which has lists
import keyword
# displaying the complete list using "kwlist()."
print("The set of keywords in this version is: ")
print( keyword.kwlist )
Output:
Code
help("keywords")
The following sections categorize Python keywords under the headings based on their frequency
of use.
The first category, for instance, includes all keywords utilized as values, whereas the next group
includes keywords employed as operators.
These classifications will aid in understanding how keywords are employed and will assist you
in arranging the huge collection of Python keywords.
A few terms mentioned in the segment following may be unfamiliar to you. They're explained
here, and you must understand what they mean before moving on:
The Boolean assessment of a variable is referred to as truthfulness. A value's truthfulness reveals
if the value of the variable is true or false.
Value Keywords: True, False, None
Three Python keywords are employed as values in this example. These are singular values,
which we can reuse indefinitely and every time correspond to the same entity. These values will
most probably be seen and used frequently.
The Keywords True and False
These keywords are typed in lowercase in conventional computer languages (true and false);
however, they are typed in uppercase in Python every time. In Python script, the True Python
keyword represents the Boolean true state. False is a keyword equivalent to True, except it has the
negative Boolean state of false.
True and False are those keywords that can be allocated to variables or parameters and are compared
directly.
Code
print( 4 == 4 )
print( 6 > 9 )
print( True or False )
print( 9 <= 28 )
print( 6 > 9 )
print( True and False )
Output:
True
False
True
True
False
False
Because the first, third, and fourth statements are true, the interpreter gives True for those and False
for other statements. True and False are the equivalent in Python as 1 & 0. We can use the
accompanying illustration to support this claim:
Code
print( True == 3 )
print( False == 0 )
print( True + True + True)
Output:
False
True
3
The None Keyword
None is a Python keyword that means "nothing." None is known as nil, null, or undefined in different
computer languages.
If a function does not have a return clause, it will give None as the default output:
Code
print( None == 0 )
print( None == " " )
print( None == False )
A = None
B = None
print( A == B )
Output:
False
False
False
True
If a no_return_function returns nothing, it will simply return a None value. None is delivered by
functions that do not meet a return expression in the program flow. Consider the following scenario:
Code
def no_return_function():
num1 = 10
num2 = 20
addition = num1 + num2
number = no_return_function()
print( number )
Output:
None
This program has a function with_return that performs multiple operations and contains a return
expression. As a result, if we display a number, we get None, which is given by default when there is
no return statement. Here's an example showing this:
Code
def with_return( num ):
if num % 4 == 0:
return False
number = with_return( 67 )
print( number )
Output:
None
Operator Keywords: and, or, not, in, is
Several Python keywords are employed as operators to perform mathematical operations. In many
other computer languages, these operators are represented by characters such as &, |, and!. All of
these are keyword operations in Python:
Mathematical Operations Operations in Other Languages Python Keyword
X Y X and Y
True True True
False True False
True False False
False False False
X Y X or Y
X not X
True False
False True
Code
Code
def the_outer_function():
var = 10
def the_inner_function():
var = 14
print("Value inside the inner function: ", var)
the_inner_function()
print("Value inside the outer function: ", var)
the_outer_function()
Output:
# looping from 1 to 15
i = 0 # initial condition
while i < 15:
# When i has value 9, loop will jump to next iteration using continue. It will not print
if i == 9:
i += 3
continue
else:
# when i is not equal to 9, adding 2 and printing the value
print( i + 2, end = " ")
i += 1
Output:
4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 14 15 16
Exception Handling Keywords - try, except, raise, finally, and assert
try: This keyword is designed to handle exceptions and is used in conjunction with the keyword
except to handle problems in the program. When there is some kind of error, the program inside
the "try" block is verified, but the code in that block is not executed.
except: As previously stated, this operates in conjunction with "try" to handle exceptions.
finally: Whatever the outcome of the "try" section, the "finally" box is implemented every time.
raise: The raise keyword could be used to specifically raise an exception.
assert: This method is used to help in troubleshooting. Often used to ensure that code is correct.
Nothing occurs if an expression is interpreted as true; however, if it is false, "AssertionError" is
raised. An output with the error, followed by a comma, can also be printed.
Code
# initializing the numbers
var1 = 4
var2 = 0
['A', 'B']
Python has various built-in data types which we will discuss with in this tutorial:
Python numeric data types store numeric values. Number objects are created when you assign a
value to them. For example −
var1 = 1
var2 = 10
var3 = 10.023
Python supports four different numerical types −
Python allows you to use a lowercase l with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
Example
Following is an example to show the usage of Integer, Float and Complex numbers:
# integer variable.
# float variable.
# complex variable.
c=10+3jprint("The type of variable having value", c, " is ", type(c))
Python Strings are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the
slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in
Python. For example −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python List Data Type
Python Lists are the most versatile compound data types. A Python list contains items separated by
commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays
in C. One difference between them is that all the items belonging to a Python list can be of different
data type where as C array can store elements related to a particular data type.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator. For example −
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
print (list) # Prints complete listprint (list[0]) # Prints first element of the listprint
(list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting
from 3rd elementprint (tinylist * 2) # Prints list two timesprint (list + tinylist) # Prints concatenated
lists
Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists. For example −
The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tuple[2] = 1000 #
Invalid syntax with tuplelist[2] = 1000 # Valid syntax with list
Python Ranges
Python range() is an in-built function in Python which returns a sequence of numbers starting from 0
and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers. Following is the
syntax of the function:
Examples
Following is a program which uses for loop to print number from 0 to 4 −
for i in range(5):
print(i)
This produce the following result −
0
1
2
3
4
Now let's modify above program to print the number starting from 1 instead of 0:
for i in range(1, 5):
print(i)
This produce the following result −
1
2
3
4
Again, let's modify the program to print the number starting from 1 but with an increment of 2
instead of 1:
for i in range(1, 5, 2):
print(i)
This produce the following result −
1
3
Python Dictionary
Python dictionaries are kind of hash table type. They work like associative arrays or hashes found in
Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually
numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]).
For example −
dict = {}dict['one'] = "This is one"dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' keyprint (dict[2]) # Prints value for 2 keyprint
(tinydict) # Prints complete dictionaryprint (tinydict.keys()) # Prints all the keysprint
(tinydict.values()) # Prints all the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Python dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order"; they are simply unordered.
Python Boolean Data Types
Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows you to evaluate the value of any expression and
returns either True or False based on the expression.
OUTPUT STATEMENTS:
In Python, Using the input() function, we take input from a user, and using the print() function, we
display output on the screen. Using the input() function, users can give any information to the
application in the strings or numbers format.
In Python 3, we have the following two built-in functions to handle input from a user and system.
1. input([prompt])
2. raw_input([prompt])
The input() function reads a line entered on a console or screen by an input device such as a
keyboard, converts it into a string. As a new developer, It is essential to understand what is input in
Python.
The input is a value provided by the system or user. For example, suppose you want to calculate
the addition of two numbers on the calculator, you need to provide two numbers to the calculator. In
that case, those two number is nothing but an input provided by the user to a calculator program.
There are different types of input devices we can use to provide data to application. For example: –
Stems from the keyboard: User entered some value using a keyboard.
Using mouse click or movement: The user clicked on the radio button or some drop-down list
and chosen an option from it using mouse.
In Python, there are various ways for reading input from the user from the command line
environment or through the user interface. In both cases, the user is sending information using the
keyboard or mouse.
First, ask employee name, salary, and company name from the user
Next, we will assign the input provided by the user to the variables
Finally, we will use the print() function to display those variables on the screen.
PYTHON COMMENTS:
learn about single-line comments, multi-line comments, documentation strings, and other Python
comments.
Introduction to Python Comments
We may wish to describe the code we develop. We might wish to take notes of why a section of
script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures, and
sophisticated business logic are typically explained with comments. The Python interpreter overlooks
the remarks and solely interprets the script when running a program. Single-line comments, multi-
line comments, and documentation strings are the 3 types of comments in Python.
Advantages of Using Comments
Our code is more comprehensible when we use comments in it. It assists us in recalling why specific
sections of code were created by making the program more understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating other code
sections. This simple technique stops some lines from running or creates a fast pseudo-code for the
program.
Below are some of the most common uses for comments:
o Readability of the Code
o Restrict code execution
o Provide an overview of the program or project metadata
o To add resources to the code
The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain what
they perform. The docstring is then readily accessible in Python using the __doc__ attribute.
Code
# Code to show how we use docstrings in Python
def add(x, y):
"""This function adds the values of x and y"""
return x + y
# Displaying the docstring of the add function
print( add.__doc__ )
Output:
indentation is the leading whitespace (spaces or/and tabs) before any statement. The importance
of indentation in Python stems from the fact that it serves a purpose other than code readability.
Python treats statements with the same indentation level (statements preceded by the same
number of whitespaces) as a single code block.
So, whereas in languages such as C, C++, and others, a block of code is represented by curly
braces, a block in Python is a group of statements with the same Indentation level, i.e. the same
number of leading whitespaces.
Advantages of Indentation in Python:
o Indentation is used in python to represent a certain block of code, but in other programming
languages, they refer to various brackets. Due to indentation, the code looks more efficient
and beautifully structured.
o Indentation rules used in a python programming language are very simple; even a
programmer wants their code to be readable.
o Also, indentation increases the efficiency and readability of the code by structuring it
beautifully.
EXPRESSIONS:
+ : add (plus).
- : subtract (minus).
x : multiply.
/ : divide.
** : power.
% : modulo.
<< : left shift.
>> : right shift.
& : bit-wise AND.
| : bit-wise OR.
^ : bit-wise XOR.
~ : bit-wise invert.
< : less than.
> : greater than.
<= : less than or equal to.
>= : greater than or equal to.
== : equal to.
!= : not equal to.
and : boolean AND.
or : boolean OR.
not : boolean NOT.
The expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on their
precedence. We have various types of expression in Python, refer to the next section for a more
detailed explanation of the types of expression in Python.
Types of Expression in Python:
We have various types of expression in Python, let us discuss them along with their respective
examples.
1. Constant Expressions:
A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a value
that cannot be changed after its initialization.
Example :
x = 10 + 15# Here both 10 and 15 are constants but x is a variable.print("The value of x is: ", x)
Output :
The value of x is: 25
2. Arithmetic Expressions:
An expression in Python that contains a combination of operators, operands, and sometimes
parenthesis is known as an arithmetic expression. The result of an arithmetic expression is also a
numeric value just like the constant expression discussed above. Before getting into the example of
an arithmetic expression in Python, let us first know about the various operators used in the
arithmetic expressions.
Operator Syntax Working
+ x+y Addition or summation of x and y.
- x-y Subtraction of y from x.
x xxy Multiplication or product of x and y.
/ x/y Division of x and y.
// x // y Quotient when x is divided by y.
% x%y Remainder when x is divided by y.
Operator Syntax Working
** x ** y Exponent (x to the power of y).
Example :
x = 10y = 5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
print("The sum of x and y is: ", addition)print("The difference between x and y is: ",
subtraction)print("The product of x and y is: ", product)print("The division of x and y is: ",
division)print("x to the power y is: ", power)
Output :
The sum of x and y is: 15The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000
3. Integral Expressions:
An integral expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). An integral expression always produces an integer value as a resultant.
Example :
x = 10 # an integer numbery = 5.0 # a floating point number# we need to convert the floating-
point number into an integer or vice versa for summation.result = x + int(y)print("The sum of x and y
is: ", result)
Output :
The sum of x and y is: 15
4. Floating Expressions:
A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example :
x = 10 # an integer numbery = 5.0 # a floating point number# we need to convert the integer
number into a floating-point number or vice versa for summation.result = float(x) + yprint("The sum
of x and y is: ", result)
Output :
The sum of x and y is: 15.0
5. Relational Expressions:
A relational expression in Python can be considered as a combination of two or more arithmetic
expressions joined using relational operators. The overall expression results in
either True or False (boolean result). We have four types of relational operators in
Python (�.�.>,<,>=,<=)(i.e.>,<,>=,<=).
A relational operator produces a boolean result so they are also known as Boolean Expressions.
For example :
10+15>2010+15>20
In this example, first, the arithmetic expressions (i.e. 10+1510+15 and 2020) are evaluated, and then
the results are used for further comparison.
Example :
a = 25b = 14c = 48d = 45# The expression checks if the sum of (a and b) is the same as the
difference of (c and d).result = (a + b) == (c - d)print("Type:", type(result))print("The result of the
expression is: ", result)
Output :
Type: <class 'bool'>The result of the expression is: False
6. Logical Expressions:
As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical expressions
in Python, let us discuss them briefly.
Operator Syntax Working
and �x and �y The expression return True if both �x and �y are true, else it returns False.
or �x or �y The expression return True if at least one of �x or �y is True.
not not �x The expression returns True if the condition of �x is False.
Note :
In the table specified above, �x and �y can be values or another expression as well.
Example :
from operator import and_
x = (10 == 9)y = (7 > 5)
and_result = x and yor_result = x or ynot_x = not xprint("The result of x and y is: ",
and_result)print("The result of x or y is: ", or_result)print("The not of x is: ", not_x)
Output :
The result of x and y is: FalseThe result of x or y is: True
The not of x is: True
7. Bitwise Expressions:
The expression in which the operation or computation is performed at the bit level is known as
a bitwise expression in Python. The bitwise expression contains the bitwise operators.
Example :
x = 25left_shift = x << 1right_shift = x >> 1print("One right shift of x results: ",
right_shift)print("One left shift of x results: ", left_shift)
Output :
One right shift of x results: 12One left shift of x results: 50
8. Combinational Expressions:
As the name suggests, a combination expression can contain a single or multiple expressions which
result in an integer or boolean value depending upon the expressions involved.
Example :
x = 25y = 35result = x + (y << 1)print("Result obtained : ", result)
Output :
Result obtained: 95
Whenever there are multiple expressions involved then the expressions are resolved based on their
precedence or priority. Let us learn about the precedence of various operators in the following
section.
Multiple Operators in Expression (Operator Precedence) ?
The operator precedence is used to define the operator's priority i.e. which operator will be executed
first. The operator precedence is similar to the BODMAS rule that we learned in mathematics. Refer
to the list specified below for operator precedence.
Precedence Operator Name
1. ()[]{} Parenthesis
2. ** Exponentiation
Precedence Operator Name
3. -value , +value , ~value Unary plus or minus, complement
4. / * // % Multiply, Divide, Modulo
5. +– Addition & Subtraction
6. >> << Shift Operators
7. & Bitwise AND
8. ^ Bitwise XOR
9. pipe symbol Bitwise OR
10. >= <= > < Comparison Operators
11. == != Equality Operators
12. = += -= /= *= Assignment Operators
13. is, is not, in, not in Identity and membership operators
14. and, or, not Logical Operators
Let us take an example to understand the precedence better :
x = 12y = 14z = 16
result_1 = x + y * zprint("Result of 'x + y + z' is: ", result_1)
result_2 = (x + y) * zprint("Result of '(x + y) * z' is: ", result_2)
result_3 = x + (y * z)print("Result of 'x + (y * z)' is: ", result_3)
Output :
Result of 'x + y + z' is: 236Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236
Let us say we want to change a number from a higher data type to a lower data type.
Implicit type conversion is ineffective in this situation, as we observed in the previous section.
Explicit type conversion, commonly referred to as type casting, now steps in to save the day.
Using built-in Language functions like str() to convert to string form and int() to convert to
integer type, a programmer can explicitly change the data form of an object by changing it
manually.
The user can explicitly alter the data type in Python's Explicit Type Conversion according to
their needs. Since we are compelled to change an expression into a certain data type when doing
express type conversion, there is chance of data loss. Here are several examples of explicit type
conversion.
o The function int(a, base) transforms any data type to an integer. If the type of data is a string,
"Base" defines the base wherein string is.
o float(): You can turn any data type into a floating-point number with this function.
After converting the string the to list : ['j', 'a', 'v', 'a']
PYTHON ARRAYS
The Array is a process of memory allocation. It is performed as a dynamic memory allocation. We
can declare an array like x[100], storing 100 data in x. It is a container that can hold a fixed number
of items, and these items should be the same type.
Array operations
Some of the basic operations supported by an array are as follows:
o Traverse - It prints all the elements one by one.
o Insertion - It adds an element at the given index.
o Deletion - It deletes an element at the given index.
o Search - It searches an element using the given index or by the value.
o Update - It updates an element at the given index.
The Array can be created in Python by importing the array module to the python program.
x = len(cars)
ARRAY METHODS:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value PART -
A
insert() Adds an element at the specified position
1. Is Python
case pop() Removes the element at the specified position sensitive
when
remove( Removes the first item with the specified value dealing
with )
Explanation: This is a built-in function which rounds a number to give precision in decimal digits.
In the above case, since the number of decimal places has not been specified, the decimal number
is rounded off to a whole number. Hence the output will be 5.
11. Which of these in not a core data type?
a) Lists
b) Dictionary
c) Tuples
d) Class
Explanation: Class is a user defined data type.
12. Given a function that does not return any value, What value is thrown by default when
executed in shell.
a) int
b) bool
c) void
d) None
Explanation: Python shell throws a NoneType object back.
17. Operators with the same precedence are evaluated in which manner?
a) Left to Right
b) Right to Left
c) Can’t say
d) None of the mentioned
Explanation: None.
19. Which one of the following has the same precedence level?
a) Addition and Subtraction
b) Multiplication, Division and Addition
c) Multiplication, Division, Addition and Subtraction
d) Addition and Multiplication
Explanation: “Addition and Subtraction” are at the same precedence level. Similarly,
“Multiplication and Division” are at the same precedence level. However, Multiplication and
Division operators are at a higher precedence level than Addition and Subtraction operators.
a) wo
b) world
c) sn
d) rl
Explanation: Execute in the shell and verify.
22. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}
Explanation: The argument given for the set must be an iterable
….……………………………………..UNIT 1 COMPLETED………….…………………………..
In Python, the selection statements are also known as decision making statements or branching
statements.
The selection statements are used to select a part of the program to be executed based on a condition.
Python provides the following selection statements.
if statement
if-else statement
if-elif statement
if statement in Python
In Python, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then decides
the execution of a block of statements. If it is True, then the block of statements is executed and if it
is False, then the block of statements is ignored. The execution flow of if statement is as follows.
Syntax
if condition:
Statement_1
Statement_2
Statement_3
...
The general syntax of if statement in Python is as follows.
When we define an if statement, the block of statements must be specified using indentation only.
The indentation is a series of white-spaces. Here, the number of white-spaces is variable, but all
statements must use the identical number of white-spaces. Let's look at the following example
Python code.
if (num % 5 == 0):
In Python, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the given
condition then decides which block of statements to be executed based on the condition result. If the
condition is True, then the true block of statements is executed and if it is False, then the false block
of statements is executed.
Syntax
if condition:
Statement_1
Statement_2
Statement_3
...
else:
Statement_4
Statement_5
...
In the above syntax, whenever the condition is True, the statements 1 2 and 3 are gets executed. And
if the condition is False then the statements 4 and 5 are gets executed. Let's look at the following
example of Python code.
if num % 2 == 0:
else:
print(f'The number {num} is a Odd number')
Syntax
if condition_1:
Statement_1
Statement_2
Statement_3
...
elif condition_2:
Statement_4
Statement_5
Statement_6
...
else:
Statement_7
Statement_8
...
In the above syntax, whenever the condition_1 is True, the statements 1 2 and 3 are gets executed. If
the condition_1 is False and condition_2 is True then the statements 4, 5, and 6 are gets executed.
And if condition_1 nad Condition_2 both are False then the statements 7 and 8 are executed. Let's
look at the following example of Python code.
Python code to illustrate if-else statement
# Python code to illustrate elif statement
if choice == 'C':
else:
print('You are not interested in Sports')
#!/usr/bin/python
Example
#!/usr/bin/python
var = 100if var == 200:
print "1 - Got a true expression value"
print varelif var == 150:
print "2 - Got a true expression value"
print varelif var == 100:
print "3 - Got a true expression value"
print varelse:
print "4 - Got a false expression value"
print var
print "Good bye!"
When the above code is executed, it produces the following result −
3 - Got a true expression value
100
Good bye!
ITERATIVE STATEMENTS:
In programming, loops are used to repeat a block of code. For example, if we want to show a
message 100 times, then we can use a loop. It's just a simple example, we can achieve much more
with loops.
In the previous tutorial, we learned about Python for loop. Now we will learn about the while loop.
Python while Loop
Python while loop is used to run a block code until a certain condition is met.
The syntax of while loop is:
while condition:
# body of while loop
Here,
A while loop evaluates the condition
If the condition evaluates to True, the code inside the while loop is executed.
condition is evaluated again.
This process continues until the condition is False.
When condition evaluates to False, the loop stops.
10
20
30
40
50
60
Example - 2
str = "JavaTpoint"
for i in str:
print(i)
Output:
o
i
t
Using the range() function
The range function() generates the sequence of the numbers. For example, if we execute
the range(5) and it will generate the 0 to 4. The syntax of the range() function is given below.
Syntax:
range(start, stop, step-size)
It accepts the three arguments.
The start represents the beginning of the iteration.
The stop indicates the end of for loop. It will iterate till stop-1.
The step size skips the specific number of iteration. By default, the step size is 1.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Example - 2 Traverse the List element using range() function
list = ['Peter', 'Joseph', 'Ricky', 'Devansh', 'Kevin']
for i in range(len(list)):
print("Hii",list[i])
Output:
Hii Peter
Hii Joseph
Hii Ricky
Hii Devansh
Hii Kevin
Explanation:
The len() function returns the length of the list. The range() got the number of elements in the list
and printed its elements.
PYTHON ELSE SUITE:
In Python, it is possible to use 'else' statement along with for loop or while loop in the form shown in
Table:
for with else syntax
for( var in sequence)
statementselse:
statements
while with else syntax
while( condition ):
statementselse:
statements
he else suite will be always executed irrespective of the statements in the loop are executed or not.
for i in range(5):
print("Yes") else: print("No")
Output:
Yes
Yes
Yes
Yes
Yes
No
It means, the for loop statement is executed and also the else suite is executed.
A Python program to search for an element in the list of elements.
group1 = [1,2,3,4,5]
search = int(input('Enter element to search:')) for element in group1:
if search == element: print('Element found in group')
break #come out of for loop else: print('Element not found in group1') #this is else suite
Write a python program to check whether given number is Prime number or not?
num = int(input("Enter a number: ")) if num > 1:
for i in range(2,num):
if (num % i) == 0: print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else: print(num,"is a prime number") else: print(num,"is not a prime number")
Write a python program to list of Prime numbers
lower = int(input("Enter starting number : "))
upper = int(input("Enter ending number: ")) for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,end='\t')
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
JUMP STATEMENTS:
Break, Pass, and Continue statements are loop controls used in python. The break statement, as the
name suggests, breaks the loop and moves the program control to the block of code after the loop (if
any). The pass statement is used to do nothing.
Python break statement:
The break is a keyword in python which is used to bring the program control out of the loop. The
break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop
first and then proceeds to outer loops. In other words, we can say that break is used to abort the
current execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition. The
syntax of the break statement in Python is given below.
Syntax:
#loop statements
break;
Example 1 : break statement with for loop
Code
# break statement example
my_list = [1, 2, 3, 4]
count = 1
for item in my_list:
if item == 4:
print("Item matched")
count += 1
break
print("Found at location", count)
Output:
Item matched
Found at location 2
In the above example, a list is iterated using a for loop. When the item is matched with value 4, the
break statement is executed, and the loop terminates. Then the count is printed by locating the item.
Example 2 : Breaking out of a loop early
Code
# break statement example
my_str = "python"
for char in my_str:
if char == 'o':
break
print(char)
Output:
p
y
h
When the character is found in the list of characters, break starts executing, and iterating stops
immediately. Then the next line of the print statement is printed.
Example 3: break statement with while loop
Code
# break statement example
i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");
Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
It is the same as the above programs. The while loop is initialised to True, which is an infinite loop.
When the value is 10 and the condition becomes true, the break statement will be executed and jump
to the later print statement by terminating the while loop.
Example 4 : break statement with nested loops
Code
# break statement example
n=2
while True:
i=1
while i <= 10:
print("%d X %d = %d\n" % (n, i, n * i))
i += 1
choice = int(input("Do you want to continue printing the table? Press 0 for no: "))
if choice == 0:
print("Exiting the program...")
break
n += 1
print("Program finished successfully.")
Output:
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program...
Program finished successfully.
There are two nested loops in the above program. Inner loop and outer loop The inner loop is
responsible for printing the multiplication table, whereas the outer loop is responsible for
incrementing the n value. When the inner loop completes execution, the user will have to continue
printing. When 0 is entered, the break statement finally executes, and the nested loop is terminated.
Definition The continue statement is utilized to skip the The pass keyword is used when a
current loop's remaining statements, go to phrase is necessary syntactically to
the following iteration, and return control to be placed but not to be executed.
the beginning.
Action It takes the control back to the start of the Nothing happens if the Python
loop. interpreter encounters the pass
statement.
Applicatio It works with both the Python while and It performs nothing; hence it is a
n Python for loops. null operation.
Syntax It has the following syntax: -: continue Its syntax is as follows:- pass
Interpretati It's mostly utilized within a loop's condition. During the byte-compile stage, the
on pass keyword is removed.
Keyword:
pass
Ordinarily, we use it as a perspective for what's to come.
Let's say we have an if-else statement or loop that we want to fill in the future but cannot. An empty
body for the pass keyword would be grammatically incorrect. A mistake would be shown by the
Python translator proposing to occupy the space. As a result, we use the pass statement to create a
code block that does nothing.
An Illustration of the Pass Statement
Code
# Python program to show how to use a pass statement in a for loop
'''''pass acts as a placeholder. We can fill this place later on'''
sequence = {"Python", "Pass", "Statement", "Placeholder"}
for value in sequence:
if value == "Pass":
pass # leaving an empty if block using the pass keyword
else:
print("Not reached pass keyword: ", value)
Output:
Not reached pass keyword: Python
Not reached pass keyword: Placeholder
Not reached pass keyword: Statement
The same thing is also possible to create an empty function or a class.
Code
# Python program to show how to create an empty function and an empty class
# Empty function:
def empty():
pass
# Empty class
class Empty:
pass
x = ['ab', 'cd']for i in x:
i.upper()print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
Explanation: The function upper() does not modify a string in place, it returns a new string which
isn’t being stored anywhere.
8. What will be the output of the following Python code?
i = 1while True:
if i%3 == 0:
break
print(i)
i+=1
a) 1 2
b) 1 2 3
c) error
d) none of the mentioned
Explanation: SyntaxError, there shouldn’t be a space between + and = in +=.
i = 1while True:
if i%0O7 == 0:
break
print(i)
i += 1
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) error
d) none of the mentioned
Explanation: Control exits the loop when i becomes 7.
i = 5while True:
if i%0O11 == 0:
break
print(i)
i += 1
a) 5 6 7 8 9 10
b) 5 6 7 8
c) 5 6
d) error
Explanation: 0O11 is an octal number.
11. What will be the output of the following Python code?
i = 5while True:
if i%0O9 == 0:
break
print(i)
i += 1
a) 5 6 7 8
b) 5 6 7 8 9
c) 5 6 7 8 9 10 11 12 13 14 15 ….
d) error
Explanation: 9 isn’t allowed in an octal number.
12. What will be the output of the following Python code?
i = 1while True:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 2
c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
Explanation: The loop does not terminate since i is never an even number.
13. What will be the output of the following Python code?
i = 2while True:
if i%3 == 0:
break
print(i)
i += 2
a) 2 4 6 8 10 …
b) 2 4
c) 2 3
d) error
Explanation: The numbers 2 and 4 are printed. The next value of i is 6 which is divisible by 3 and
hence control exits the loop.
14. What will be the output of the following Python code?
i = 1while False:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 3 5 7 …
c) 1 2 3 4 …
d) none of the mentioned
Explanation: Control does not enter the loop because of False.
15. What will be the output of the following Python code?
True = Falsewhile True:
print(True)
break
a) True
b) False
c) None
d) none of the mentioned
Explanation: SyntaxError, True is a keyword and it’s value cannot be changed.
16. Can we write if/else into one line in python?
a) Yes
b) No
c) if/else not used in python
d) None of the above
Explanation: We can write if/else in one line. For eg i = 2 if a > 5 else 0.
17. else if Statement in Python
a) if a>=2 :
b) if (a >= 2)
c) if (a => 22)
d) if a >= 22
Explanation:- If statement always end with colon (:)
18. What keyword would you use to add an alternative condition to an if statement?
a) else if
b) elseif
c) elif
d) None of the above
19. What is the output of the given below program?
if 1 + 3 == 7:
print("Hello")else:
print("Know Program")
a) Hello
b) Know Program
c) Compiled Successfully, No Output.
d) Error
The 1+3 = 4 which is not equal to 7 therefore else block will be executed.
20. What is the output of the given below program?
if 3 + 4 == 7:
print("Hi")else:
print("Know Program")print("Hello")
a) Hi
b) Know Program
c)
Hi
Hello
d)
Know Program
Hello
The 3+4 = 7 is equal to 7 therefore if block will be executed. The remaining statement after if-else
block also will be executed.
….…………………………UNIT - 2 COMPLETED………………………
UNIT - III
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
Arguments Recursion. Python Strings: String operations- Immutable Strings - Built-in String
Methods and Functions - String Comparison. Modules: import statement- The Python module – dir()
function – Modules and Namespace – Defining our own modules.
FUNCTIONS
Python Functions
This tutorial will go over the fundamentals of Python functions, including what they are, their syntax,
their primary parts, return keywords, and significant types. We'll also look at some examples of
Python function definitions.
What are Python Functions?
A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is
known as a function. An assortment of proclamations called Python Capabilities returns the specific
errand. Python functions are necessary for intermediate-level programming and are easy to define.
Function names meet the same standards as variable names do. The objective is to define a function
and group-specific frequently performed actions. Instead of repeatedly creating the same code block
for various input variables, we can call the function and reuse the code it contains with different
variables.
Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python.
It aids in maintaining the program's uniqueness, conciseness, and structure.
Advantages of Python Functions
Pause We can stop a program from repeatedly using the same code block by including functions.
o Once defined, Python functions can be called multiple times and from any location in a
program.
o Our Python program can be broken up into numerous, easy-to-follow functions if it is
significant.
o The ability to return as many outputs as we want using a variety of arguments is one of
Python's most significant achievements.
o However, Python programs have always incurred overhead when calling functions.
However, calling functions has always been overhead in a Python program.
Syntax
# An example Python Function
def function_name( parameters ):
# code block
The accompanying components make up to characterize a capability, as seen previously.
o The start of a capability header is shown by a catchphrase called def.
o function_name is the function's name, which we can use to distinguish it from other
functions. We will utilize this name to call the capability later in the program. Name
functions in Python must adhere to the same guidelines as naming variables.
o Using parameters, we provide the defined function with arguments. Notwithstanding, they are
discretionary.
o A colon (:) marks the function header's end.
o We can utilize a documentation string called docstring in the short structure to make sense of
the reason for the capability.
o Several valid Python statements make up the function's body. The entire code block's
indentation depth-typically four spaces-must be the same.
o A return expression can get a value from a defined function.
Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify the arguments
it must receive, and organize the code block.
When the fundamental framework for a function is finished, we can call it from anywhere in the
program. An illustration of how to use the a_function function can be found below.
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. 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.
Code
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
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:
Code
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )
function( 50, 30)
# Calling function and passing arguments using keyword
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
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.
Code
# Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to be 3
0
print( "Passing out of order arguments" )
function( 30, 20 )
number 1 is: 30
number 2 is: 20
4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions. However, we
need a capability. This can be accomplished with one of two types of characters:
"args" and "kwargs" refer to arguments not based on keywords.
To help you understand arguments of variable length, here's an example.
Code
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']
RETURN STATEMENT:
When a defined function is called, a return statement is written to exit the function and return the
calculated value.
Syntax:
2704
None
Code
Here, we can see that the initial value of num is 10. Even though the function number() changed the
value of num to 50, the value of num outside of the function remained unchanged.
This is because the capability's interior variable num is not quite the same as the outer variable
(nearby to the capability). Despite having a similar variable name, they are separate factors with
discrete extensions.
Factors past the capability are available inside the capability. The impact of these variables is global.
We can retrieve their values within the function, but we cannot alter or change them. The value of a
variable can be changed outside of the function if it is declared global with the keyword global.
Python Capability inside Another Capability
Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same
everywhere they are used in a programming language. They can be stored in built-in data structures,
used as arguments, and in conditional expressions. If a programming language treats functions like
first-class objects, it is considered to implement first-class functions. Python lends its support to the
concept of First-Class functions.
A function defined within another is called an "inner" or "nested" function. The parameters of the
outer scope are accessible to inner functions. Internal capabilities are developed to cover them from
the progressions outside the capability. Numerous designers see this interaction as an embodiment.
Code
A return statement
A return statement ends the execution of a function, and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return
statement can return a value to the calling function.
Function Arguments
Arguments and Parameters in Python
Be it any programming language, Arguments and Parameters are the two words that cause a lot of
confusion to programmers. Sometimes, these two words are used interchangeably, but actually, they
have two different yet similar meanings. This tutorial explains the differences between these two
words and dives deep into the concepts with examples.
Both arguments and parameters are variables/ constants passed into a function. The difference is that:
1. Arguments are the variables passed to the function in the function call.
2. Parameters are the variables used in the function definition.
3. The number of arguments and parameters should always be equal except for the variable
length argument list.
Example:
def add_func(a,b):
sum = a + b
return sum
num1 = int(input("Enter the value of the first number: "))
num2 = int(input("Enter the value of the second number: "))
print("Sum of two numbers: ",add_func(num1, num2))
Output:
Enter the value of the first number: 5
Enter the value of the second number: 2
Sum of two numbers: 7
Points to grasp from the Example:
1. (num1, num2) are in the function call, and (a, b) are in the function definition.
2. (num1, num2) are arguments and (a, b) are parameters.
Mechanism:
Observe that in the above example, num1 and num2 are the values in the function call with which we
called the function. When the function is invoked, a and b are replaced with num1 and num2, the
operation is performed on the arguments, and the result is returned.
Functions are written to avoid writing frequently used logic again and again. To write a general
logic, we use some variables, which are parameters. They belong to the function definition. When
we need the function while writing our program, we need to apply the function logic on the variables
we used in our program, called the arguments. We then call the function with the arguments.
Types of Arguments:
Based on how we pass arguments to parameters, arguments are of two types:
1. Positional arguments
2. Keyword arguments
o Given some parameters, if the respective arguments are passed in order one after the other,
those arguments are called the "Positional arguments."
o If the arguments are passed by assigning them to their respective parameters in the function
call with no significance to the passing order, they are called "Keyword arguments".
Example:
def details(name, age, grade):
print("Details of student:", name)
print("age: ", age)
print("grade: ", grade)
details("Raghav", 12, 6)
details("Santhosh", grade = 6, age = 12)
Output:
Details of student: Raghav
age: 12
grade: 6
Details of student: Santhosh
age: 12
grade: 6
Points to grasp from the Example:
First Function Call:
o The function has three parameters-name, age and grade. So, it accepts three arguments.
o In the first function call:
details("Raghav", 12, 6)
The arguments are passed position-wise to the parameters, which mean according to the passed
order:
o name is replaced with "Raghav."
o age is replaced with 12 and
o grade is replaced with 6
o In the first function call, the order of passing the arguments matter. The parameters accept the
arguments in the given order only.
o In the Second Function Call:
When the addresses of the arguments are passed into parameters instead of values, this method of
invoking a function is called "Call by Reference".
o Both the arguments and parameters refer to the same memory location.
o Changes to the parameters (pointers) will affect the values of the arguments in the program.
o By default, C language follows Call by value, but using the indirection operator and pointers;
we can simulate Call by reference.
000000000062FE1C
000000000062FE1C
In Python:
a = 20
print(id(a))
a = 21
print(id(a))
Output:
140714950863232
140714950863264
o As you can observe: In C, after reassigning the value, the variable is still in the same memory
location, while in Python, it refers to a different memory location. (id -> address in Python).
o But that's not all. There are other types of objects too.
2253724439168
2253724439168
Understanding:
A list is immutable, which means we can alter or modify it after creating it. As you can observe,
when created with the name a, it is saved in the address "2253724439168". Using append(), we
altered it by appending another value. It is still in the same memory location, meaning the same
object is modified.
Immutable Objects:
a = 20
print(id(a))
a += 23
print(id(a))
Output:
140714950863232
140714950863968
Understanding:
This is the case we discussed before in the tutorial. An int object is immutable, meaning we can't
modify it once created. You might wonder we still added 23 in the above code. Observe that the
object when created is not the same object after adding. Both are in different memory locations
which means they are different objects.
So, how are arguments passed to the parameters when a function is invoked?
With all the knowledge about assignment operation in Python:
1. The passing is like a "Call by Reference" if the arguments are mutable.
2. The passing is like "Call by Value" if the arguments are immutable.
Example:
def details(name, age, grade, marks):
marks.append(26)
name += " Styles"
print("Details of the student: ")
print("name: ",name)
print("age: ",age)
print("grade: ", grade)
print("marks: ", marks)
name = "Harry"
age = 15
grade = 10
marks = [25, 29, 21, 30]
details (name, age, grade, marks)
print(grade)
print(marks)
Output:
age: 15
grade: 10
10
Let
us
study
Data Science
and
Blockchain
Explanation-
Let's understand what we have done in the above program,
1. In the first step, we have created a function that will take variable arguments as its
parameters.
2. After this, we have used a for loop that will take each element or parameter in this case and
print it.
3. Finally, we have passed six strings as the parameters in our function.
4. On executing the program, the desired output is displayed.
study
Data Science
and
Blockchain
Explanation-
It's time to have a glance at the explanation of this program.
1. In the first step, we have created a function that will take two parameters and then rest as
variable arguments as its parameters.
2. In the next step, we have defined the function in which we have displayed the values of the
first two parameters.
3. After this, we have used a for loop that will take each element or parameter in this case and
print it.
4. Finally, we have passed six strings as the parameters in our function.
5. On executing the program, the desired output is displayed.
a_key=Let
b_key=us
c_key=study
d_key=Data Science
e_key=and
f_key=Blockchain
Explanation-
Let us see what we have done in the above program.
1. In the first step, we have created a function that takes keyworded arguments as its parameters.
2. After this, in the function definition we have specified that a for loop will be used to fetch the
key-value pair.
3. Finally, we have passed six key value pairs inside the function.
4. On executing this program, the desired output is displayed.
b_key=us
c_key=study
d_key=Data Science
e_key=and
f_key=Blockchain
Explanation-
Check out the explanation of this program,
1. In the first step, we have created a function that takes one parameter and rest as keyworded
arguments as its parameters.
2. After this, in the function definition, we have specified that a for loop will be used to fetch
the key-value pair.
3. Finally, we have passed five key-value pairs inside the function and so it displays only those
pairs in the output and doesn't consider the first string.
4. On executing this program, the desired output is displayed.
We will conclude this article with a program that illustrates how *args and **kwargs can be used in a
single program.
#program to demonstrate **kwargs in python
def my_func(*args,**kwargs):
#displaying the value of args
print("The value of args is:",args)
#displaying the value of kwargs
print("The value of kwargs is:",kwargs)
#passing the values in function
my_func("Let","us","study",a_key="Data Science",b_key="and",c_key="Blockchain")
Output:
The value of kwargs is: {'a_key': 'Data Science', 'b_key': 'and', 'c_key': 'Blockchain'}
Explanation-
1. In the first step, we have created a function that takes *args and **kwargs (non-keyworded
and keyworded arguments) as its parameters.
2. After this, we have the function definition where we have displayed the values of both
parameters.
3. Finally, we have passed six parameters in the function, from which three are strings and the
other three are key-value pairs.
Escape Sequences:
To insert characters that are illegal in a string, use an escape character.An escape character is
a backslash \ followed by the character you want to insert.
Example:
txt = "We are the so-called \"Vikings\" from the north."
Output:
Raw Strings:
Raw strings are particularly useful when working with regular expressions, as they allow
you to specify patterns that may contain backslashes without having to escape them. They are also
useful when working with file paths, as they allow you to specify paths that contain backslashes
without having to escape them. Raw strings can also be useful when working with strings that
contain characters that are difficult to type or read, such as newline characters or tabs. In general,
raw strings are useful anytime you need to specify a string that contains characters that have
special meaning in Python, such as backslashes, and you want to specify those characters literally
without having to escape them.
Example:
str = r'Python\nis\easy\to\learn'
Output: Python\nis\easy\to\learn
Explanation: As we can see that the string is printed as raw,
and it neglected all newline sign(\n) or tab space (\t).
String Formatting:
String formatting in Python allows you to create dynamic strings by combining variables
and values. String formatting in Python allows you to create dynamic strings by combining
variables and values.
Example:
print("The mangy, scrawny stray dog %s gobbled down" %'hurriedly' +
"the grain-free, organic dog food.")
Output:
The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog
food.
Python Operators:
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y Tr
- Subtraction x-y Tr
* Multiplication x*y Tr
/ Division x/y Tr
% Modulus x%y Tr
** Exponentiation x ** y Tr
// Floor division x // y Tr
== Equal x == y Tr
!= Not equal x != y Tr
and Returns True if both statements are true x < 5 and x < 10 T
not Reverse the result, returns False if the result not(x < 5 and x < 10) T
is true
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
is not Returns True if both variables are not the same x is not y T
object
<< Zero fill left Shift left by pushing zeros in from the right and let the x << 2
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from x >> 2
shift the left, and let the rightmost bits fall off
Operator Precedence:
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:
print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest precedence at
the top:
Operator Description T
() Parentheses T
** Exponentiation T
^ Bitwise XOR T
| Bitwise OR T
and AND T
or OR T
If two operators have the same precedence, the expression is evaluated from left to right.
Example
Addition + and subtraction - has the same precedence, and therefor we evaluate the
expression from left to right:
print(5 + 4 - 7 + 3)
Formatting using format() Method
Format() method was introduced with Python3 for handling complex string formatting more
efficiently. Formatters work by putting in one or more replacement fields and placeholders defined
by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put
into the placeholders and concatenate with the string passed as parameters into the format
function.
Output:
We all are equal
Understanding Python f-string
PEP 498 introduced a new string formatting mechanism known as Literal String
Interpolation or more commonly as F-strings (because of the leading f character preceding the
string literal). The idea behind f-String in Python is to make string interpolation simpler.
To create an f-string in Python, prefix the string with the letter “f”. The string itself can be
formatted in much the same way that you would with str. format(). F-strings provide a concise
and convenient way to embed Python expressions inside string literals for formatting.
String Formatting with F-Strings:In this code, the f-string f”My name is {name}.” is
used to interpolate the value of the name variable into the string.
Example:
name = 'Ele'
print(f"My name is {name}.")
Output:
My name is Ele
Python String Template Class
In the String module, Template Class allows us to create simplified syntax for output
specification. The format uses placeholder names formed by $ with valid
Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $
$ creates a single escaped $:
This code imports the Template class from the string module. The Template class allows us
to create a template string with placeholders that can be substituted with actual values. Here we are
substituting the values n1 and n2 in-place of n3 and n4 in the string n.
Example:
# Python program to demonstrate
# string interpolation
from string import Template
n1 = 'Hello'
n2 = 'GeeksforGeeks'
Output:
Hello ! This is GeeksforGeeks.
Formatting string using center() method:This code returns a new string padded
with spaces on the left and right sides.
Example:
string = "GeeksForGeeks!"
width = 30
centered_string = string.center(width)
print(centered_string)
Output:
GeeksForGeeks!
String Operations:
In python, String operators represent the different types of operations that can be employed
on the program's string type of variables. Python allows several string operators that can be applied
on the python string are as below: Assignment operator: “=.” Concatenate operator: “+.” String
repetition operator: “*.”
String operators with examples:
In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be applied on
can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’]. var_name =
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:
hello
hello
hello
Example #2 – Concatenate Operator “+”
Two strings can be concatenated or join using the “+” operator in python, as explained in
Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
Output:
helloworld
below example.
Code:
Output:
helloworld helloworld
operator. The index is interpreted as a positive index starting from 0 from the left side and a negative
string[a]: Returns a character from a positive index a of the string from the left side as
string[-a]: Returns a character from a negative index a of the string from the right side as
string[a:b]: Returns characters from positive index a to positive index b of the as displayed
string[a:-b]: Returns characters from positive index a to the negative index b of the string as
string[a:]: Returns characters from positive index a to the end of the string.
string[:b] Returns characters from the start of the string to the positive index b.
string[-a:]: Returns characters from negative index a to the end of the string.
string[:-b]: Returns characters from the start of the string to the negative index b.
Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Output:
ello
ellowo
lloworld
hello
hellowor
ld
dlrowolleh
“!=” operator returns Boolean True if two strings are not the same and return Boolean False if
These operators are mainly used along with if condition to compare two strings where the
Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
Output:
False
True
True
False
the string.
“a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a”
is in the string.
A membership operator is also useful to find whether a specific substring is part of a given
string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)
Output:
True
False
False
True
True
False
False
of a non-allowed character in python string is inserting double quotes in the string surrounded by
double-quotes.
Code:
Output:
SyntaxError:invalid syntax
variable along with string, the “%” operator is used along with python string. “%” is prefixed to
another character indicating the type of value we want to insert along with the python string.
Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:
Hey india
my age is 19
In Python, the terms “mutable” and “immutable” refer to the ability of an object to be
changed after it is created.An object is considered mutable if its state or value can be modified after
it is created. This means that you can alter its internal data or attributes without creating a new
object. Examples of mutable objects in Python include lists, dictionaries, and sets. If you modify a
mutable object, any references to that object will reflect the changes.Both of these states are integral
to Python data structure.
What is Mutable?
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’
is the ability of objects to change their values. These are often the objects that store a collection of
data.
What is Immutable?
Immutable is the when no change is possible over time. In Python, if the value of an object
cannot be changed over time, then it is known as immutable. Once created, the value of these objects
is permanent.
Lists
Sets
Dictionaries
User-Defined Classes (It purely depends upon the user to define the characteristics)
Objects of built-in type that are immutable are:
# Printing the elements from the list cities, separated by a comma & space
print(city, end=’, ’)
print(weekdays)
Python has a set of built-in methods that you can use on strings.All string methods returns new
values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
index() Searches the string for a specified value and returns the position of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was fou
rindex() Searches the string for a specified value and returns the last position of where it was fou
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Function Description
delattr() Deletes the specified attribute (property or method) from the specified object
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
hasattr() Returns True if the specified object has the specified attribute
(property/method)
map() Returns the specified iterator with the specified function applied to each item
(by default)
The relational operators compare the Unicode values of the characters of the strings from
the zeroth index till the end of the string. It then returns a boolean value according to the operator
used.
Example:
print("Geek" == "Geek")
print("Geek" != "Geek")
Output:
True
True
False
False
The == operator compares the values of both the operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same is
the case for != and is not.
Example:
str1 = "Geek"
str2 = "Geek"
str3 = str1
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)
str1 += "s"
str4 = "Geeks"
print(str1 is str4)
Output:
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
ID of str4 = 0x7f60356137a0
False
The object ID of the strings may vary on different machines. The object IDs of str1, str2
and str3 were the same therefore they the result is True in all the cases. After the object id of str1 is
changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as
in the new str1, the answer will be false as their object IDs are different.
Vice-versa will happen with is not.
String Comparison in Python Creating a user-defined function.
By using relational operators we can only compare the strings by their unicodes. In order
to compare two strings according to some other parameters, we can make user-defined functions.
In the following code, our user-defined function will compare the strings based upon the
number of digits.
Python3
count1 = 0
count2 = 0
for i in range(len(str1)):
count1 += 1
for i in range(len(str2)):
if str2[i] >= "0" and str2[i] <= "9":
count2 += 1
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))
Output:
False
False
True
Python Modules:
What is a Module?
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module:
The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):
Example
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
import platform
x = platform.system()
print(x)
Example
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
print (person1["age"])
Pythontutor
It is advisable to use online pythontutor to visualize execution of Python code
See how pythontutor visualizes object reference
Shared object reference
See that two (or even more names, a and c in this example) may reference the same
object (integer '1'). This is typically called "shared object reference"
(b) Namespaces
What is a namespace?
In [7]:
x=1
x='spam'
print(x)
del x
print(x)
spam
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-2bb509689422> in <module>()
4
5 del x
----> 6 print(x)
x=1 introduces 'x' in the namespace but name 'x' is not recognized after executing
the 'del x' command. 'x' is deleted from the namespace.
Please note that when working interactively in a Python shell (like, for example,
jupyter notebook) you may either use the print() function to present values
onscreen or simply write the name or expression whose value you want in the
output.
In the latter case only the last expression in the cell will be presented in the output
unless you define otherwise by adjusting the notebook settings
In [1]:
x=1
y = 2.5
x+y
# Just writing the expression will present the outcome
Out[1]:
3.5
In [5]:
x=1
y = 2.5
print(x, y, 2*x**y)
# Better use print() when you want to present more than one values
1 2.5 2.0
(c) Modules
What is a module?
A module is practically any .py file containing useful code (for example:
statements, functions, and classes) that can be used for code development.
As the name implies, modules promote the idea of modular development in
practice. Python offers a simple yet powerful way to link modules and use/reuse
code in many different situations
import module_name
The 'import' command imports the namespace of the module to the namespace of
the code you are writing in your main program. For example:
In [ ]:
import random
print(random.randint(1,10))
The 'random' module offers functions for generating and managing random
numbers. The 'import random' command imports the namespace of 'random' in your
program code. We shall see more of that later.
Note the use of 'dot notation' to refer to the imported
names: 'module_name.imported_name'. This is a practical way to visualize
namespaces and import them safely in your code.
There are two other common ways to write the 'import' command. One you should
avoid; the other you should follow.
Avoid this:
In [4]:
from random import *
print(randint(1,10))
The benefit here is that you import the entire module namespace and you can use it
without writing the module name as a prefix.
However: this technique provides no visual cues as to the origin of the names and it
may confuse you - so avoid it unless you are completely confident about your code!
Follow this:
In [6]:
import random as rn
print(rn.randint(1,10))
Python is a multi-purpose, high level, and dynamic programming language. It provides many
built-in modules and functions to perform various types of tasks. Aside from that, we can also
create our own modules using Python. A module is like a library in Java, C, C++, and C#. A
module is usually a file that contains functions and statements. The functions and statements
of modules provide specific functionality. A Python module is saved with the .py extension.
In this article, we will learn to create our own Python modules.
A module is typically used to divide the large functionality into small manageable files. We
can implement our most used functions in a separate module, and later on, we can call and
use it everywhere. The module’s creation promotes reusability and saves a lot of time.
Create Python modules
To create a Python module, open a Python script, write some statements and functions, and
save it with .py extension. Later on, we can call and use these modules anywhere in our
program.
Let’s create a new module named “MathOperations”. This module contains functions to
perform addition, subtraction, multiplication, and division.
def addition(num1,num2):
return num1+num2
#creating subtraction function
def subtraction(num1,num2):
return num1-num2
def multiplication(num1,num2):
return num1*num2
def division(num1,num2):
return num1/num2
Part- A
Choose the best answer:
str1="6/4"
print("str1")
a). 1
b). 6/4
c). 1.5
d). str1
a). class
b). function
c). method
d). module
4. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity
str1="poWer"
str1.upper()
print(str1)
a). POWER
b). Power
c). power
d). poWer
str1="Stack of books"
print(len(str1))
a). 13
b). 14
c). 15
d). 16
str1="Information"
print(str1[2:8])
a). format
b). formatio
c). orma
d). ormat
a). define
b). fun
c). def
d). function
10. Which of the following items are present in the function header?
11. Which of the following will print the pi value defined in math module?
a). print(pi)
b). print(math.pi)
c). from math import pi
print(pi)
d). from math import pi
print(math.pi)
a). .
b). *
c). ->
d). &
print(z(6))
a). 6
b). 36
c). 0
d). error
a). a
b). A
c). 97
d). error
Part – B
1. Explain about Python strings?
2. Explain about Python strings operators?
3. Explain about example of a string in Python?
4. How to do length of a string in Python?
5. Why strings are immutable with an example in Python?
6. What are immutable strings in Python?
7. What are immutable strings write a short note?
8. What are string function and method in Python?
9. What are the 5 string methods?
10. What are the 2 string method in Python?
Part-C
1. What is the method string?
2. What is string function and method in Python?
3. What are the built-in types in Python?
4. What are 4 built-in data types in Python?
5. How strings are immutable in Python with example?
6. Explain about string immutable data types in Python?
7. What are examples of immutable in Python?
8. Explain about string Comparison ?
9. What are the modules and namespace in Python?
10. How to defining our own modules?
Python Lists:
mylist = ["apple", "banana", "cherry"]
List:
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
Example
Create a List:
List Items:
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the items will
not change.
Changeable:
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
Allow Duplicates:
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
List Length:
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
Example
A list with strings, integers and boolean values:
type():
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
It is also possible to use the list() constructor when creating a new list.
Example:
Using the list() constructor to make a List:
There are four collection data types in the Python programming language:
*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.
List items are indexed and you can access them by referring to the index number:
Example
Negative Indexing:
-1 refers to the last item, -2 refers to the second last item etc.
Example
Range of Indexes:
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new list with the specified items.
Example
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
Specify negative indexes if you want to start the search from the end of the list:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second
last item etc.
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
Introduction:
Do you know what a list is? Have you ever performed any operations on a list in Python? If
not, then don't worry; we got your back.
In Python, a list is a type of data structure that enables users to store information in sequence
to constitute a record. Its indexing starts from 0; a list can keep any data (integer, character, boolean,
string). Before we jump to Python list operations, it is recommended you go through the python
data types. Let us discuss the characteristics of a list.
Operations on Lists
A list in Python is built using square brackets. We write the values inside the square brackets
separated by commas.
1. Append()
As we know, a list is mutable. We can add an element at the back of the list using an inbuilt
function of Python list operation append(). Let us see implementations of it.
my_list=[1,2,3]
my_list.append(9)
my_list.append(8)
print("The list after append() operation is: ",my_list)
Here, we created a list called my_list and added elements to the list. The output of the above
code is:
Output:
2. extend()
Extend () method can be used to add more than one element at the end of a list. Let us
understand the function by its implementation.
my_list.extend([20,21])
3. Insert()
Now we can insert an element in between the list using the inbuilt function of Python list
operation insert()
my_list.insert(5,30)
print("The list after insert() operator is: \n",my_list)
In this function, the first input is the position at which the element is to be added, and the second
input is the element's value. Here after using the insert() we have added 30 at 5th position in my_list.
Hence the updated list will be:
4. remove()
The way we added an element between the list, similarly, we can remove from in between a
list using an inbuilt Python list operation function remove().
my_list.remove(10)
print("The list after remove() operator is: \n",my_list)
As we have removed 10 from my_list, the output of the above code will be:
6. Slice()
This method is used to print a section of the list. Which means we can display elements of a
specific index.
print("The elements of list in the range of 3 to 12 are:\n",my_list[3:12])
Using the slicing operator, we have sliced elements from range of 3 to 12 in the my_list.
Hence the above code would print elements whose index lies between the range 3 to 12.
Note that the slice method only prints the elements; it does not change the list.
7. reverse()
To reverse the indexing of elements in a list, the simple built-in function reverse() can be
used. This function allows the user to reverse the order of elements very quickly and without large
code lines. To reverse a list, it needs to be parsed with the function itself.
Example:
coding_list = ["coding", "ninjas”, "data", "science"]
coding_list.reverse() #Reverse Function implemented
print(coding_list)
Output:
['science', 'data', 'ninjas', 'coding']
9. count()
As we can store duplicates in a list, a Python list operation is used to count the number of
copies, known as count().
my_list.extend([10,20,22])
print("The list is: \n",my_list)
print("Number of times 21 is in the list are: ",my_list.count(20))
After using the extend() and count() operator on my_list, the the number of repetitions of 21
are:
Concatenate is a very simple process, with the literal meaning of combining or joining two
objects. Similarly, concatenation in Python can be used to combine two lists or strings.
Concatenation in Python can be simply performed by using “+” between variable names that hold a
string or list.
Example:
list_one = [100, 150, 200]
list_two = [900, 950, 800]
new_list = list_one + list_two #new_list variable holds the concatenated list
print(new_list)
Output:
[100, 150, 200, 900, 950, 800]
Similarly, following is an example to perform concatenation on a string:
string_one = ["Coding"]
string_two = ["Ninjas"]
new_string = string_one + string_two
print(new_string)
Output:
['Coding', 'Ninjas']
11. Multiply
Did you know that you can increase the number of elements in a list by
simply multiplying it by a number? For example, by multiplying a list with the
number ‘n’, you get that list element being repeated ‘n’ times. List
multiplication can be performed by just
List Methods
Python has a set of built-in methods that you can use on lists.
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
Now you have learned a lot about lists, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
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.
Example
Create a Tuple:
Tuple Items:
Ordered:
When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not
recognize it as a tuple.
Example
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Example
String, int and boolean data types:
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
There are four collection data types in the Python programming language:
*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.
You can access tuple items by referring to the index number, inside square brackets:
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is
created.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as
it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.
print(x)
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways
to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add
your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or
many), create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
print(thistuple)
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.
Dictionary Length
To determine how many items a dictionary has, use the len() function:
type()
The dict() Constructor
a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method
a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
a) Error, invalid syntax
b) A
c) 5
d) 4
a={1:"A",2:"B",3:"C"}
print(a.setdefault(3))
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) C
c) {1: 3, 2: 3, 3: 3}
d) No method called setdefault() exists for dictionary
a={1:"A",2:"B",3:"C"}
a.setdefault(4,"D")
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’}
b) None
c) Error
d) [1,3,6,10]
a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a.update(b)
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) Method update() doesn’t exist for dictionaries
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
d) {4: ‘D’, 5: ‘E’}
a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
a) Error, copy() method doesn’t exist for dictionaries
b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
d) “None” is printed
a={1:"A",2:"B",3:"C"}
a.clear()
print(a)
a) None
b) { None:None, None:None, None:None}
c) {1:None, 2:None, 3:None}
d) { }
a={1:5,2:3,3:4}
a.pop(3)
print(a)
a) {1: 5}
b) {1: 5, 2: 3}
c) Error, syntax error for pop() method
d) {1: 5, 3: 4}
a={1:5,2:3,3:4}
print(a.pop(4,9))
a) 9
b) 3
c) Too many arguments for pop() method
d) 4
a={1:"A",2:"B",3:"C"}
for i in a:
print(i,end=" ")
a) 1 2 3
b) ‘A’ ‘B’ ‘C’
c) 1 ‘A’ 2 ‘B’ 3 ‘C’
d) Error, it should be: for i in a.items():
>>> a={1:"A",2:"B",3:"C"}
>>> a.items()
a) Syntax error
b) dict_items([(‘A’), (‘B’), (‘C’)])
c) dict_items([(1,2,3)])
d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])
5 MARKS
10 MARKS
1. What 4 methods can be used with a list?
2. What are the operations performed in the list?
3. What is list and methods of list in Python?
4. How many lists function in Python?
5. What are the types of list?
6.What are dictionaries for Python?
7.What is dictionary in Python with example?
8.What is dictionary and its types in Python?
9.How to get top 10 values in dictionary Python?
10.What are nested list in Python?
11.How do you make a list of 10 elements in Python?
12.What are nested lists?
13.How do you create a nested list in Python?
14.How do you update and delete a list in Python?
15.What is the delete method for list in Python?
16.How do you update a list of lists in Python?
17.How do I remove the first 10 elements from a list in Python?
18.What is the difference between list and tuple in Python?
19.What are the three main differences between tuples and lists in Python?
20.What's the main difference between Python lists and tuples?
File handling in Python is a powerful and versatile tool that can be used to perform a
wide range of operations. However, it is important to carefully consider the advantages and
disadvantages of file handling when writing Python programs, to ensure that the code is
secure, reliable, and performs well.
Output:
This is the write commandIt allows us to write in a particular file
Example 2: We can also use the written statement along with the with() function.
Opening a file refers to getting the file ready either for reading or for writing.
This can be done using the open() function. This function returns a file object and
takes two arguments, one that accepts the file name and another that accepts the
mode(Access Mode). Now, the question arises what is the access mode? Access
modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File
Handle in the file. The file handle is like a cursor, which defines where the data has
to be read or written in the file. There are 6 access modes in Python.
Mode Description
‘r’ Open text file for reading. Raises an I/O error if the file does not exist.
‘r+’ Open the file for reading and writing. Raises an I/O error if the file does not exist.
Open the file for writing. Truncates the file if it already exists. Creates a new file if it does
‘w’
not exist.
Open the file for reading and writing. Truncates the file if it already exists. Creates a new
‘w+’
file if it does not exist.
Open the file for writing. The data being written will be inserted at the end of the file.
‘a’
Creates a new file if it does not exist.
Open the file for reading and writing. The data being written will be inserted at the end of
‘a+’
the file. Creates a new file if it does not exist.
‘rb’ Open the file for reading in binary format. Raises an I/O error if the file does not exist.
Open the file for reading and writing in binary format. Raises an I/O error if the file does
‘rb+’
not exist.
Open the file for writing in binary format. Truncates the file if it already exists. Creates a
‘wb’
new file if it does not exist.
Open the file for reading and writing in binary format. Truncates the file if it already
‘wb+’
exists. Creates a new file if it does not exist.
Open the file for appending in binary format. Inserts data at the end of the file. Creates a
‘ab’
new file if it does not exist.
Open the file for reading and appending in binary format. Inserts data at the end of the file.
‘ab+’
Creates a new file if it does not exist.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
Note: The file should exist in the same directory as the Python script, otherwise full address
of the file should be written. If the file is not exist, then an error is generated, that the file
does not exist.
Output:
Welcome to GeeksForGeeks!!
Note: In the above example, we haven’t provided the access mode. By default, the open()
function will open the file in read mode, if no parameter is provided.
If you want to add more data to an already created file, then the access mode should be
‘a’ which is append mode, if we select ‘w’ mode then the existing text will be overwritten by
the new data.
# Python program to demonstrate
# opening a file
# Writing to file
file1.write("\nWriting to file:)" )
# Closing file
file1.close()
Sample Run:
writelines() function
file1.writelines(lst)
file1.close()
print("Data is written into the file.")
Output:
Data is written into the file.
Sample Run:
Enter the name of the employee: Rhea
Enter the name of the employee: Rohan
Enter the name of the employee: Rahul
The only difference between the write() and writelines() is that write() is used to write
a string to an already opened file while writelines() method is used to write a list of strings in
an opened file.
# my_list
my_list = ['geeks', 'for']
print(my_list)
Output:
['geeks', 'for', 'geeks']
Adding List to the List
In this example, we will append a complete list at the end of the given list.
Python3
# my_list
my_list = ['geeks', 'for', 'geeks']
# another list
another_list = [6, 0, 4, 1]
print(my_list)
Output:
['geeks', 'for', 'geeks', [6, 0, 4, 1]]
Note: A list is an object. If you append another list onto a list, the parameter list will be a
single object at the end of the list. If you want to append the elements of a list to another list
you can use Python’s List extend() method.
Time complexity: O(1) or constant time. This is because lists can be accessed randomly
using indexing, so the last element can be accessed easily in O(1) time.
Elements Add to a List in Python Using Concatenation Operator
Another way to add elements to a list is using the concatenation operator( ‘+’ ), in this
we create a new list by combining the existing list with another list that contains the new
element.
Python3
Output:
[9, 5, 7, 3]
Elements Add to a List in Python Using List Slicing
Another way to add elements to a list is using list slicing, this allows you to modify a
portion of a list by assigning new values to it. To add elements to specific positions within a
list, we can use list slicing with the insert() method.
Python3
Output:
[3, 4, 5, 6]
Python programming language is a pinnacle in the IT industry. With brilliant library support and
out of the box features, Python programming has made file handling looking like a piece of cake. It
provides easy implementations for File handling related tasks. One such method is the Python
readline method. In this article, we will learn about the Python readline() method with examples. The
following concepts are covered in this article:
Python readline() method will return a line from the file when called.
readlines() method will return all the lines in a file in the format of a list where each element is a
line in the file.
After opening the file using the open() method, we can simply use these methods.
Explore Curriculum
1file = open("filename.txt","r")
2file.readlines()
The readlines method takes one parameter i.e hint, the default value for the hint parameter is -
1. It means that the method will return all the lines. If we specify the hint parameter, the lines
exceeding the number of bytes from the hint parameter will not be returned by the readlines method.
Let us go ahead and take a look at a few examples to understand how these methods work in Python.
Let us suppose we have a text file with the name examples.txt with the following content.
Now, to use the readline, we will have to open the example.txt file.
readlines() Examples
We can use the readlines() method just like we used readline() in the above example.
This brings us to the end of this article where we have learned how we use the Python
readline() method with examples. I hope you are clear with all that has been shared with you in this
tutorial.
If you found this article on “Python readline()” relevant, check out Edureka’s Python Course a
trusted online learning company with a network of more than 250,000 satisfied learners spread
across the globe.
Python allows you to read the contents of a file using methods such as:
read()
readline()
readline()
Python read()
The read method reads the entire contents of a file and returns it as a string.
Python readline()
The readline method reads a single line from a file and returns it as a string. This means that
if you use readline, you can read the contents of a file line by line, which can be useful
for processing large files that do not fit in memory.
In the above example, the while loop continues to read lines from the file until
readline returns an empty string, indicating the end of the file. The strip method is used to remove
the line terminator from each line.
Python readlines()
The readline method reads a single line from a file and returns it as a string, while the
readlines method reads the entire contents of a file and returns it as a list of strings, where each
element of the list is a single line of the file.
You can see the difference of readline() and readlines() methods from the following example:
with open("file.txt") as f:
line = f.readline()
print(line)# Prints the first line of the file
lines = f.readlines()
print(lines) # Prints a list of all the lines in the file after the first line
Python readlines reads the whole file into memory, which can be problematic if the file is
very large. In such cases, it's usually better to use readline and process the file one line at a time. If
you want to remove the line terminator characters (\n or \r\n) from each line, you can use the strip
method:
Pros:
Cons:
Pros:
Cons:
Python readlines():
Pros:
Good for reading small files.
Returns the contents of the file as a list of strings, which makes it easy to work with the file's
contents.
Cons:
Opening a File
It is done using the open() function. No module is required to be imported for this
function.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file
should be written on place of filename. Note: The r is placed before filename to prevent the
characters in filename string to be treated as special character. For example, if there is \temp in the
file address, then \t is treated as the tab character and error is raised of invalid address. The r makes
the string raw, that is, it tells that the string is without any special characters. The r can be ignored if
the file is in same directory and address is not being placed.
Python3
# Open function to open the file "MyFile1.txt"
# (same directory) in read mode and
file1 = open("MyFile.txt", "r")
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at
the time when the file is no longer needed or if it is to be opened in a different file mode.
Syntax:
File_object.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Python3
# Program to show various ways to
# read data from a file.
# Creating a file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes
Output:
Hello
This is Delhi
This is Paris
This is London
Python provides inbuilt functions for creating, writing and reading files. There are two
types of files that can be handled in python, normal text files and binary files (written in
binary language, 0s and 1s).
Text files: In this type of file, Each line of text is terminated with a special
character called EOL (End of Line), which is the new line character (‘\n’) in
python by default.
Binary files: In this type of file, there is no terminator for a line and the data is
stored after converting it into machine-understandable binary language.
Note: To know more about file handling click here.
Table of content
Access mode
Opening a file
Closing a file
Writing to file
Appending to a file
With statement
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File Handle in
the file. File handle is like a cursor, which defines from where the data has to be read or
written in the file. Different access modes for reading a file are –
1. Write Only (‘w’) : Open the file for writing. For an existing file, the data is
truncated and over-written. The handle is positioned at the beginning of the file.
Creates the file if the file does not exist.
2. Write and Read (‘w+’) : Open the file for reading and writing. For an existing
file, data is truncated and over-written. The handle is positioned at the beginning
of the file.
3. Append Only (‘a’) : Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written will be
inserted at the end, after the existing data.
Note: To know more about access mode
Opening a File
It is done using the open() function. No module is required to be imported for this
function. Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of
the file should be written on place of filename. Note: The r is placed before filename to
prevent the characters in filename string to be treated as special character. For example, if
there is \temp in the file address, then \t is treated as the tab character and error is raised of
invalid address. The r makes the string raw, that is, it tells that the string is without any
special characters. The r can be ignored if the file is in same directory and address is not
being placed.
Python3
# Open function to open the file "MyFile1.txt"
# (same directory) in read mode and
file1 = open("MyFile.txt", "w")
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is
used at the time when the file is no longer needed or if it is to be opened in a different file
mode. Syntax:
File_object.close()
Python3
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt", "w")
file1.close()
Writing to file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
1. writelines() : For a list of string elements, each string is inserted in the text file.
Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Note: ‘\n’ is treated as a special character of two bytes. Example:
Python3
# Python program to demonstrate
# writing to file
# Opening a file
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"
# Closing file
file1.close()
Output:
Hello
This is Delhi
This is Paris
This is London
Appending to a file
When the file is opened in append mode, the handle is positioned at the end of the file.
The data being written will be inserted at the end, after the existing data. Let’s see the below
example to clarify the difference between write mode and append mode.
Python3
# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today
Python3
# Program to show various ways to
# write data to a file using with statement
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# Writing to file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
Output:
Hello
This is Delhi
This is Paris
This is London
Note: To know more about with statement click here.
using for statement:
steps:
To write to a file in Python using a for statement, you can follow these steps:
Open the file using the open() function with the appropriate mode (‘w’ for writing).
Use the for statement to loop over the data you want to write to the file.
Use the file object’s write() method to write the data to the file.
Close the file using the file object’s close() method.
In this example, the file is opened for writing using the with open(‘file.txt’, ‘w’) as f
statement. The data to be written is stored in a list called data. The for statement is used to
loop over each line of data in the list. The f.write(line + ‘\n’) statement writes each line of
data to the file with a newline character (\n) at the end. Finally, the file is automatically
closed when the with block ends.
Python3
# Open the file for writing
with open('file.txt', 'w') as f:
# Define the data to be written
data = ['This is the first line', 'This is the second line', 'This is the third line']
# Use a for loop to write each line of data to the file
for line in data:
f.write(line + '\n')
# Optionally, print the data as it is written to the file
print(line)
# The file is automatically closed when the 'with' block ends
Output
This is the first line
This is the second line
This is the third line
Keywor Description
d
as To create an alias
finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not
or A logical operator
Approach:
The code opens a file called file.txt in write mode using a with block to ensure the file
is properly closed when the block ends. It defines a list of strings called data that
represents the lines to be written to the file. The code then uses a for loop to iterate
through each string in data, and writes each string to the file using the write() method.
The code appends a newline character to each string to ensure that each string is
written on a new line in the file. The code optionally prints each string as it is written
to the file.
Time Complexity:
Both the original code and the alternative code have a time complexity of O(n), where n is
the number of lines to be written to the file. This is because both codes need to iterate
through each line in the data list to write it to the file.
Space Complexity:
The original code and the alternative code have the same space complexity of O(n), where n
is the number of lines to be written to the file. This is because both codes need to create a list
of strings that represent the lines to be written to the file.
Python Keywords
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:
as
as is used to create an alias while importing a module. It means giving a different name (user-
defined) to a module while importing it.
As for example, Python has a standard module called math. Suppose we want to calculate what
cosine pi is using an alias. We can do it as follows using as:
>>> a = 4
>>> assert a < 5
>>> assert a > 5
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError
For our better understanding, we can also provide a message to be printed with the AssertionError.
>>> a = 4
>>> assert a > 5, "The value of a is too small"
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError: The value of a is too small
is equivalent to,
if not condition:
raise AssertionError(message)
async, await
The async and await keywords are provided by the asyncio library in Python. They are used to write
concurrent code in Python. For example,
import asyncio
asyncio.run(main())
In the above program, the async keyword specifies that the function will be executed
asynchronously.
Here, first Hello is printed. The await keyword makes the program wait for 1 second. And then
the world is printed.
break, continue
break and continue are used inside for and while loops to alter their normal behavior.
break will end the smallest loop it is in and control flows to the statement immediately below
the loop. continue causes to end the current iteration of the loop, but not the whole loop.
This can be illustrated with the following two examples:
for i in range(1,11):
if i == 5:
break
print(i)
Output
1
2
3
4
Here, the for loop intends to print numbers from 1 to 10. But the if condition is met when i is
equal to 5 and we break from the loop. Thus, only the range 1 to 4 is printed.
for i in range(1,11):
if i == 5:
continue
print(i)
Output
1
2
3
4
6
7
8
9
10
Here we use continue for the same program. So, when the condition is met, that iteration is
skipped. But we do not exit the loop. Hence, all the values except 5 are printed out.
Learn more about Python break and continue statement.
class
Classes can be defined anywhere in a program. But it is a good practice to define a single
class in a module. Following is a sample usage:
class ExampleClass:
def function1(parameters):
…
def function2(parameters):
…
def function_name(parameters):
…
del is used to delete the reference to an object. Everything is object in Python. We can delete
a variable reference using del
>>> a = b = 5
>>> del a
>>> a
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
5
Here we can see that the reference of the variable a was deleted. So, it is no longer defined.
But b still exists.
del is also used to delete items from a list or a dictionary:
>>> a = ['x','y','z']
>>> del a[1]
>>> a
['x', 'z']
if, else, elif are used for conditional branching or decision making.
When we want to test some condition and execute a block only if the condition is true, then
we use if and elif. elif is short for else if. else is the block which is executed if the condition is false.
This will be clear with the following example:
def if_example(a):
if a == 1:
print('One')
elif a == 2:
print('Two')
else:
print('Something else')
if_example(2)
if_example(4)
if_example(1)
Output
Two
Something else
One
Here, the function checks the input number and prints the result if it is 1 or 2. Any input other
than this will cause the else part of the code to execute.
Learn more about Python if and if...else Statement.
except, raise, try
def reciprocal(num):
try:
r = 1/num
except:
print('Exception caught')
return
return r
print(reciprocal(10))
print(reciprocal(0))
Output
0.1
Exception caught
None
Here, the function reciprocal() returns the reciprocal of the input number.
When we enter 10, we get the normal output of 0.1. But when we input 0, a ZeroDivisionError is
raised automatically.
This is caught by our try…except block and we return None. We could have also raised
the ZeroDivisionError explicitly by checking the input and handled it elsewhere as follows:
if num == 0:
raise ZeroDivisionError('cannot divide')
finally
try:
Try-block
except exception1:
Exception1-block
except exception2:
Exception2-block
else:
Else-block
finally:
Finally-block
Here if there is an exception in the Try-block, it is handled in the except or else block. But
no matter in what order the execution flows, we can rest assured that the Finally-block is
executed even if there is an error. This is useful in cleaning up the resources.
Learn more about exception handling in Python programming.
for
for is used for looping. Generally we use for when we know the number of times we want to
loop.
In Python we can use it with any type of sequences like a list or a string. Here is an example in
which for is used to traverse through a list of names:
names = ['John','Monica','Steven','Robin']
for i in names:
print('Hello '+i)
Output
Hello John
Hello Monica
Hello Steven
Hello Robin
import keyword is used to import modules into the current namespace. from…import is used
to import specific attributes or functions into the current namespace. For example:
import math
will import the math module. Now we can use the cos() function inside it as math.cos(). But
if we wanted to import just the cos() function, this can done using from as
now we can use the function simply as cos(), no need to write math.cos().
Learn more on Python modules and import statement.
global
global is used to declare that a variable inside the function is global (outside the function).
If we need to read the value of a global variable, it is not necessary to define it as global. This is
understood.
If we need to modify the value of a global variable inside a function, then we must declare it
with global. Otherwise, a local variable with that name is created.
Following example will help us clarify this.
globvar = 10
def read1():
print(globvar)
def write1():
global globvar
globvar = 5
def write2():
globvar = 15
read1()
write1()
read1()
write2()
read1()
Output
10
5
5
Here, the read1() function is just reading the value of globvar. So, we do not need to declare
it as global. But the write1() function is modifying the value, so we need to declare the variable
as global.
We can see in our output that the modification did take place (10 is changed to 5). The write2() also
tries to modify this value. But we have not declared it as global.
Hence, a new local variable globvar is created which is not visible outside this function.
Although we modify this local variable to 15, the global variable remains unchanged. This is clearly
visible in our output.
in
in is used to test if a sequence (list, tuple, string etc.) contains a value. It returns True if the value is
present, else it returns False. For example:
>>> a = [1, 2, 3, 4, 5]
>>> 5 in a
True
>>> 10 in a
False
for i in 'hello':
print(i)
Output
h
e
l
l
o
is
is is used in Python for testing object identity. While the == operator is used to test if two
variables are equal or not, is is used to test if the two variables refer to the same object.
It returns True if the objects are identical and False if not.
We know that there is only one instance of True, False and None in Python, so they are
identical.
>>> [] == []
True
>>> [] is []
False
>>> {} == {}
True
>>> {} is {}
False
An empty list or dictionary is equal to another empty one. But they are not identical objects
as they are located separately in memory. This is because list and dictionary are mutable (value can
be changed).
Unlike list and dictionary, string and tuple are immutable (value cannot be altered once
defined). Hence, two equal string or tuple are identical as well. They refer to the same memory
location.
lambda
a = lambda x: x*2
for i in range(1,6):
print(a(i))
Output
2
4
6
8
10
Here, we have created an inline function that doubles the value, using the lambda statement.
We used this to double the values in a list containing 1 to 5.
Learn more about Python lamda function.
nonlocal
The use of nonlocal keyword is very much similar to the global keyword. nonlocal is used to
declare that a variable inside afunction (function inside a function) is not local to it, meaning
it lies in the outer inclosing function. If we need to
modify the value of a non-local variable inside a nested function, then we must declare it
with nonlocal. Otherwise a local variable with that name is created inside the nested function.
Following example will help us clarify this.
def outer_function():
a=5
def inner_function():
nonlocal a
a = 10
print("Inner function: ",a)
inner_function()
print("Outer function: ",a)
outer_function()
Output
Inner function: 10
Outer function: 10
def outer_function():
a=5
def inner_function():
a = 10
print("Inner function: ",a)
inner_function()
print("Outer function: ",a)
outer_function()
Output
Inner function: 10
Outer function: 5
Here, we do not declare that the variable a inside the nested function is nonlocal. Hence, a
new local variable with the same name is created, but the non-local a is not modified as seen in our
output.
pass
def function(args):
in the middle of a program will give us IndentationError. Instead of this, we construct a blank body
with the pass statement.
def function(args):
pass
class example:
pass
return
def func_return():
a = 10
return a
def no_return():
a = 10
print(func_return())
print(no_return())
Output
10
None
while
i=5
while(i):
print(i)
i=i–1
Output
5
4
3
2
1
with statement is used to wrap the execution of a block of code within methods defined by
the context manager.
Context manager is a class that implements __enter__ and __exit__ methods. Use of with statement
ensures that the __exit__ method is called at the end of the nested block. This concept is similar to
the use of try…finally block. Here, is an example.
This example writes the text Hello world! to the file example.txt. File objects
have __enter__ and __exit__ method defined within them, so they act as their own context manager.
First the __enter__ method is called, then the code within with statement is executed and
finally the __exit__ method is called. __exit__ method is called even if there is an error. It basically
closes the file stream.
yield
yield is used inside a function like a return statement. But yield returns a generator.
Generator is an iterator that generates one item at a time. A large list of values will take up a lot of
memory. Generators are useful in this situation as it generates only one value at a time instead of
storing all the values in memory. For example,
will create a generator g which generates powers of 2 up to the number two raised to the
power 99. We can generate the numbers using the next() function as shown below.
>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8
>>> next(g)
16
And so on… This type of generator is returned by the yield statement from a function. Here is an
example.
def generator():
for i in range(6):
yield i*i
g = generator()
for i in g:
print(i)
Output
0
1
4
9
16
25
Here, the function generator() returns a generator that generates square of numbers from 0 to
5. This is printed in the for loop.
Split in Python
The split() method in Python returns a list of the words in the string/line , separated by
the delimiter string. This method will return one or more new strings. All substrings are returned in
the list datatype.
Syntax
string.split(separator, max)
Parameter Description
The is a delimiter. The string splits at this specified separator. If is not
separator
provided then any white space is a separator.
It is a number, which tells us to split the string into maximum of provided
maxsplit
number of times. If it is not provided then there is no limit.
return The split() breaks the string at the separator and returns a list of strings.
If no separator is defined when you call upon the function, whitespace will be used by default. In
simpler terms, the separator is a defined character that will be placed between each variable. The
behavior of split on an empty string depends on the value of sep. If sep is not specified, or specified
as None, the result will be an empty list. If sep is specified as any string, the result will be a list
containing one element which is an empty string .
Splitting String by space
example
example
The following Python program reading a text file and splitting it into single words in python
example
This
is
a
test
After Split
['This', 'is', 'a', 'test']
This is a test
After Split
['This', 'is', 'a', 'test']
str = "This,is,a,test"
print(str.split(","))
output
example
import re
str = "This,isa;test"
print(re.split(",;",str))
output
['This', 'is', 'a', 'test']
example
This
is
a
test
maxsplit parameter
In the above program maxsplit is 2, the first two string are split and rest of them are in a same
string.
characters = "abcdef"
result = list(characters)
print (result)
output
['a', 'b', 'c', 'd', 'e', 'f']
In the above example, you can see the split() function return next part of a string using a specific
substring.
Here, you can see the split() function return the previous part of the string using a specific
substring.
Method Description
seekable() Returns whether the file allows us to change the file position
Learn more about the file object in our Python File Handling Tutorial.
This chapter covers all the basic I/O functions available in Python. For more functions, please
refer to standard Python documentation.
Printing to the Screen
The simplest way to produce output is using the print statement where you can pass zero or
more expressions separated by commas. This function converts the expressions you pass into a string
and writes the result to standard output as follows −
#!/usr/bin/python
raw_input
input
1
r
Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.
2
rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
3
r+
Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.
4
rb+
Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.
5
w
Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
6
wb
Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
7
w+
Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
8
wb+
Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.
9
a
Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.
10
ab
Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
11
a+
Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.
12
ab+
Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.
1
file.closed
Returns true if file is closed, false otherwise.
2
file.mode
Returns access mode with which file was opened.
3
file.name
Returns name of the file.
4
file.softspace
Returns false if space explicitly required with print, true otherwise.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another
file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close()
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is
File Positions
The tell() method tells you the current position within the file; in other words, the next read or
write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the
number of bytes to be moved. The from argument specifies the reference position from where the
bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the
current position as the reference position and if it is set to 2 then the end of the file would be taken as
the reference position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str
File Positions
o tell():
o seek():
File Positions
There are two more methods of file objects used to determine or get files positions.
tell()
seek()
tell():
This method is used to tell us the current position within the file which means the next read or write
operation will be performed that many bytes away from the start of the file.
Syntax :
obj.tell()
Example :
"""
"""
object=open("itvoyagers.txt",'w')
object=open("itvoyagers.txt",'r')
s=11
c=object.read(s)
g=object.read()
seek():
This method is used to change the current position of file.This method has two main parameters
offset and from.
Syntax :
obj.seek(offset,from)
if from is set to 1 ,it means use the current position of the file as reference position
if from is set to 2 ,it means use the end of the file as reference position
Example :
"""
"""
with open("itvoyagers.txt","r") as f:
s=10
c=f.read(s)
print(c)
c=f.read(s)
print(c)
c=f.read(s)
print(c)
Python Delete File
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
Example
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.
While working on projects, many times there are so many demo files or directories which you
have to remove because they are not required anymore while cleaning your code base. So, every
programmer needs to know how to delete a file in python. We will explain different ways to delete
files in directories.
The main difference between the OS module and the Shutil module is that in the OS module, it is
necessary that the directory you want to delete should be empty, but this is not the case in shutil
module, it can delete the whole directory with its contents.
It is a best practice to first check for the existence of a file or folder before deleting it. After that
perform the action to avoid errors. You can check for the file's existence using the following
commands:
os.path.isfile("/path/to/file")
Use exception handling (Try - Except block)
os.path.exists
Note: The file might be deleted or altered between the two lines, that's why exception handling is
advised rather than checking.
Method 1) os.remove(file_path)
The os.remove(path) function is used to delete a file from the file system whose path is
passed. The path argument is a string that specifies the path of the file that you want to delete. If the
file exists, it will permanently remove it. If it doesn't, it throws a FileNotFoundError exception.
Hence, to avoid the error we always prefer to check for file existence.
Example:
import os
from pathlib import Path
import touch
myfile = "favtutor.txt"
Path(myfile).touch() #creating a new empty file
print("Files in a directory -->",os.listdir())
print("We can see a file created succesfully")
print("-----------------------------------------------------")
# If file exists, delete it.
if os.path.isfile(myfile):
os.remove(myfile)
print("Favtutor file deleted using remove() function")
print("Current files in directory -->",os.listdir())
print("-----------------------------------------------------")
else:
# If it fails, inform the user.
print("Error: %s file not found" % myfile)
Output:
Files in a directory --> ['demo.txt', 'favtutor.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv']
We can see a file created succesfully
-----------------------------------------------------
Favtutor file deleted using remove() function
Current files in directory --> ['demo.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv']
-----------------------------------------------------
Note that If any files are once deleted using python, They will be deleted permanently. So, be
cautious!
Method 2) os.rmdir(directory_path)
The os.rmdir(directory_path) function is used to remove an empty directory from the file
system. The "rmdir" means to remove the directory. If the directory specified by directory_path
exists and is empty, this function will delete it. If it is not empty, the function will raise an OSError
exception with the message "Directory not empty".
Keep in mind that if the directory is the same as your python program you can pass the
relative path to it otherwise you have to pass the full path of the directory you want to delete inside
the function.
Example:
import pathlib
path="Text_files" # specifiing new folder name
os.rmdir(dir_path)
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:
Output:
Subdirectory f:\projects\Favtutor\Text_files
We can see a folder created succesfully with name Text_files
-----------------------------------------------------
Files in a directory --> ['demo.txt', 'favtutor.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv',
'Text_files']
Error: f:\projects\Favtutor\Text_files - The directory is not empty.
-----------------------------------------------------
As we have created a new file named “Favtutor” inside our newly created subdirectory,
rmdir() function fails to delete the directory, giving us the error stating that the folder is not empty.
Now let's try deleting the folder after first deleting the file so that our directory is empty.
try:
os.remove(new)
print(new,"Favtutor file deleted using remove() function")
os.rmdir()
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:
Output:
As in the above example we faced the issue of the directory not being empty, we can use
shutil() method in place of rmdir() to delete the directory completely without any error. The code
will have just a few slight changes as below:
Example:
import pathlib
import shutil
path="Text_files" # specifiing new folder name
Subdirectory f:\projects\Favtutor\Text_files
We can see a folder created succesfully with name Text_files
-----------------------------------------------------
favtutor.txt file created inside Text_files directory
-----------------------------------------------------
No subdiretectory
We can see a folder deleted succesfully
-----------------------------------------------------
Method 4) pathlib.Path.unlink(missing_ok=False)
The pathlib.Path.unlink() method operates on a Path object that represents the path of the file
that you want to delete. If the file specified by the Path object exists, the unlink() method will delete
it. If missing_ok parameter is false (default value), FileNotFoundError is raised if the path does not
exist. If it is true, FileNotFoundError exceptions will be ignored.
Example:
import pathlib
import os
path_object = Path(".")
print(type(path_object))
#creating a new empty file into a subdirectory
myfile = "favtutor.txt"
Path(myfile).touch()
print("favtutor.txt file created")
print(os.listdir())
print("-----------------------------------------------------")
file = pathlib.Path("favtutor.txt")
file.unlink(missing_ok=False)
print(os.listdir())
print("favtutor.txt file deleted")
Method 5) pathlib.Path.rmdir()
It helps us to remove an empty directory. You need to first select the Path() for the empty
directory, and then call rmdir() method on that path. It will check the folder size. If it's 0 byte i.e.
empty, the will be deleted successfully else throws an error. This is a good way to delete empty
folders without any fear of losing actual data.
It is similar to os.rmdir() method only way of writing the syntax is different, You can just replace the
os.rmdir(dir_path) line with this function.
6. To read the entire remaining contents of the file as a string from a file object infile, we use
____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
1. f = None
2. for i in range (5):
3. with open("data.txt", "w") as f:
4. if i > 2:
5. break
6. print(f.closed)
a) True
b) False
c) None
d) Error
8. To read the next line of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
9. To read the remaining lines of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
11. In file handling, what does this terms means “r, a”?
a) read, append
b) append, read
c) write, append
d) none of the mentioned
17. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned
20. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned
5-marks
10- Marks
1.Python | Append String to list
2.Python | Append suffix/prefix to strings in list
3.Python - Append Missing elements from other List
5.Python - Append List every Nth index
6.Python - Append given number with every element of the list
7.Append list of dictionary and series to a existing Pandas DataFrame in Python
8.Python | Perform append at beginning of list
9.numpy.append() in Python
10.append() and extend() in Python
….……………………………………..UNIT -5 Completed…………………………………………