Scripting Languages (Python)
Scripting Languages (Python)
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a popular BBC
comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying Circus" for their newly created programming language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and unpredictable,
which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.
Python programming language is being updated regularly with new features and supports. There are lots of
update in Python versions, started from 1994 to current release.
The most common question asked by the beginners - "What is the best way to learn Python"? It is the initial
and relevant question because first step in learning any programming language is to know how to learn.
The proper way of learning will help us to learn fast and become a good Python developer.
In this section, we will discuss various tips that we should keep in mind while learning 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.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
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.
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.
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.
The goal should be clear before learning the Python. Python is an easy, a vast language as well. It includes
numbers of libraries, modules, in-built functions and data structures. If the goal is unclear then it will be a
boring and monotonous journey of learning Python. Without any clear goal, you perhaps won't make it done.
So, first figure out the motivation behind learning, which can anything be such as knowing something new,
develop projects using Python, switch to Python, etc. Below are the general areas where Python is widely
used. Pick any of them.
Choose any one or two areas according to your interest and start the journey towards learning Python.
So it will take minimum amount of time to learning its syntax. Once we get its syntax properly, further
learning will be easier and quicker getting to work on projects.
Writing the code is the most effective and robust way to learn Python. First, try to write code on paper and
run in mind (Dry Run) then move to the system. Writing code on paper will help us get familiar quickly with
the syntax and the concept store in the deep memory. While writing the code, try to use proper functions
and suitable variables names.
There are many editors available for Python programming which highlights the syntax related issue
automatically. So we don't need to pay lot of attention of these mistakes.
4. Keep Practicing
The next important step is to do the practice. It needs to implementing the Python concepts through the
code. We should be consistence to our daily coding practice.
Consistency is the key of success in any aspect of life not only in programming. Writing code daily will help
to develop muscle memory.
We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It may seem
hard but muscle memory plays large part in programing. It will take us ahead from those who believe only
the reading concept of Python is sufficient.
Creating notes by own is an excellent method to learn the concepts and syntax of Python. It will establish
stability and focus that helps you become a Python developer. Make brief and concise notes with relevant
information and include appropriate examples of the subject concerned.
Maintain own notes are also helped to learn fast. A study published in Psychological Science that -
The students who were taking longhand notes in the studies were forced to be more selective — because
you can't write as fast as you can type.
Coding seems to be solitary activity, but we can enhance our skills by interacting with the others. We should
discuss our doubts to the expert or friends who are learning Python. This habit will help to get additional
information, tips and tricks, and solution of coding problems. One of the best advantages of Python, it has a
great community. Therefore, we can also learn from passionate Python enthusiasts.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
7. Do small Projects
After understanding Python's basic concept, a beginner should try to work on small projects. It will help to
understand Python more deeply and become more component in it. Theoretical knowledge is not enough
to get command over the Python language. These projects can be anything as long as they teach you
something. You can start with the small projects such as calculator app, a tic-toc-toe game, an alarm clock
app, a to-do list, student or customer management system, etc.
Once you get handy with a small project, you can easily shift toward your interesting domain (Machine
Learning, Web Development, etc.).
8. Teach Others
There is a famous saying that "If you want to learn something then you should teach other". It is also true
in case of learning Python. Share your information to other students via creating blog posts, recording videos
or taking classes in local training center. It will help us to enhance the understanding of Python and explore
the unseen loopholes in your knowledge. If you don't want to do all these, join the online forum and post
your answers on Python related questions.
Python consists of vast libraries and various frameworks. After getting familiar with Python's basic concepts,
the next step is to explore the Python libraries. Libraries are essential to work with the domain specific
projects. In the following section, we describe the brief introduction of the main libraries.
o TensorFlow - It is an artificial intelligence library which allows us to create large scale AI based
projects.
o Django - It is an open source framework that allows us to develop web applications. It is easy, flexible,
and simple to manage.
o Flask - It is also an open source web framework. It is used to develop lightweight web applications.
o Pandas - It is a Python library which is used to perform scientific computations.
o Keras - It is an open source library, which is used to work around the neural network.
There are many libraries in Python. Above, we have mentioned a few of them.
As we know, Python is an open source language that means it is freely available for everyone. We can also
contribute to Python online community to enhance our knowledge. Contributing to open source projects is
the best way to explore own knowledge. We also receive the feedback, comments or suggestions for work
that we submitted. The feedback will enable the best practices for Python programming and help us to
become a good Python developer.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
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.
o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing
In the next topic, we will discuss the Python Application, where we have defined Python's usage in detail.
o Your Python program and executable code can reside in any directory of your system, therefore
Operating System provides a specific search path that index the directories Operating System should
search for executable code.
o The Path is set in the Environment Variable of My Computer properties:
o To set path follow the steps:
Right click on My Computer ->Properties ->Advanced System setting ->Environment Variable ->New
In Variable name write path and in Variable value copy path up to C://Python(i.e., path where Python is
installed). Click Ok ->Ok.
8. Click on Ok button:
9. Click on Ok button:
Python Variables
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
A variable is the name given to a memory location. A value-holding Python variable is also known as an
identifier.
Since Python is an infer language that is smart enough to determine the type of a variable, we do not need
to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both letters and digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct variables.
Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the program.
The standards to name an identifier are given underneath.
o Python doesn't tie us to pronounce a variable prior to involving it in the application. It permits us to
make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is declared automatically
whenever a value is added to it.
o The equal (=) operator is utilized to assign worth to a variable.
Object References
When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared to
a lot of other programming languages, the procedure for dealing with variables is a little different.
Python is the exceptionally object-arranged programming language; Because of this, every data item is a part
of a particular class. Think about the accompanying model.
1. print("John")
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Output:
John
The Python object makes a integer object and shows it to the control center. We have created a string object
in the print statement above. Make use of the built-in type() function in Python to determine its type.
1. type("John")
Output:
<class 'str'>
In Python, factors are an symbolic name that is a reference or pointer to an item. The factors are utilized to
indicate objects by that name.
1. a = 50
1. a = 50
2. b = a
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
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.
1. a = 50
2. b =100
Python manages memory efficiently if we assign the same variable to two different values.
Object Identity
Every object created in Python has a unique identifier. Python gives the dependable that no two items will
have a similar identifier. The object identifier is identified using the built-in id() function. consider about the
accompanying model.
1. a = 50
2. b = a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:
140734982691168
140734982691168
2822056960944
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
We assigned the b = a, an and b both highlight a similar item. The id() function that we used to check returned
the same number. We reassign a to 500; The new object identifier was then mentioned.
Variable Names
The process for declaring the valid variable has already been discussed. Variable names can be any length
can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and highlight character(_). Take a look
at the names of valid variables in the following example.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:
Devansh
20
80.5
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
11. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
Output:
ABCDEDEFGFI
We have declared a few valid variable names in the preceding example, such as name, _name_, and so on.
However, this is not recommended because it may cause confusion when we attempt to read code. To make
the code easier to read, the name of the variable ought to be descriptive.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single statement, is a feature
of Python.
We can apply different tasks in two ways, either by relegating a solitary worth to various factors or doling
out numerous qualities to different factors. Take a look at the following example.
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
There are two types of variables in Python - Local variable and Global variable. Let's understand the following
variables.
Local Variable
The variables that are declared within the function and have scope within the function are known as local
variables. Let's examine the following illustration.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()
Output:
Explanation:
We declared the function add() and assigned a few variables to it in the code above. These factors will be
alluded to as the neighborhood factors which have scope just inside the capability. We get the error that
follows if we attempt to use them outside of the function.
1. add()
2. # Accessing local variable outside the function
3. print(a)
Output:
We tried to use local variable outside their scope; it threw the NameError.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Global Variables
Global variables can be utilized all through the program, and its extension is in the whole program. Global
variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global variable. Python gives the
worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local
variable if we don't use the global keyword. Let's examine the following illustration.
Example -
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value to it. We then created a function and
used the global keyword to access the declared variable within the function. We can now alter its value.
After that, we gave the variable x a new string value and then called the function and printed x, which
displayed the new value.
=
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. 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 -
1. # Assigning a value to x
2. x = 6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined
Python, to the other programming languages, does not support long int or float data types. It uses the int
data type to handle all integer values. The query arises here. In Python, what is the maximum value that the
variable can hold? Take a look at the following example.
Example -
Output:
<class 'int'>
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
10000000000000000000000000000000000000000001
As we can find in the above model, we assigned a large whole number worth to variable x and really look at
its sort. It printed class <int> not long int. As a result, the number of bits is not limited, and we are free to
use all of our memory.
We can print numerous factors inside the single print explanation. The examples of single and multiple
printing values are provided below.
Output:
5
5
1. a = 5
2. b = 6
3. # printing multiple variables
4. print(a,b)
5. # separate the variables by the comma
6. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
56
12345678
Basic Fundamentals:
ii) Comments
a)Tokens:
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
o The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
o The token is the smallest unit inside the given program.
o Keywords.
o Identifiers.
o Literals.
o Operators.
Every value has a datatype, and variables can hold values. Python is a powerfully composed language;
consequently, we don't have to characterize the sort of variable while announcing it. The interpreter binds
the value implicitly to its type.
1. a = 5
We did not specify the type of the variable a, which has the value five from an integer. The Python interpreter
will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in Python returns
the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data types.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer,
while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by Python. The
following is a list of the Python-defined data types.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk about every single one of them
exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with a
Python Numbers datatype. Python offers the type() function to determine a variable's data type. The
instance () capability is utilized to check whether an item has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An integer
can be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within 15
decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the genuine
and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string can be defined
in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities and
administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is
used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator.
Example - 1
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in the
rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list is
handled by the concatenation operator (+) and the repetition operator (*).
Example:
Output:
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data types.
A parenthetical space () separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
Example:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an
associative array or a hash table. Value is any Python object, while the key can hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Output:
True and False are the two default values for the Boolean type. These qualities are utilized to decide the
given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or the
letter "F," while true can be represented by any value that is not zero.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and has
remarkable components. The elements of a set have no set order; It might return the element's altered
sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to
create the set or the built-in function set() is used to create the set. It can contain different kinds of values.
Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial,
we will discuss the most popular data type in Python, i.e., string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple
quotes. The computer does not understand the characters; internally, it stores manipulated character as
the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also
called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes.
Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax:
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1.
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides
triple-quotes to represent the string, but it is generally used for multiline string or docstrings.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given in the below figure.
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in Python to access the substring from the given string. Consider the
following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str =
'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1.
The second rightmost index indicates -2, and so on. Consider the following image.
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
8. print(str[::-1])
9. print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't
support item assignment i.e., A string can only be replaced with new string since its content cannot be
partially replaced. Strings are immutable in Python.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
However, in example 1, the string str can be assigned completely to a new content as specified in the
following example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the string. But
we can delete the entire string using the del keyword.
1. str = "JAVATPOINT"
2. del str[1]
Output:
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to print
the actual meaning of escape characters such as "C://python". To define any string as a raw
string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how formatting
is done in python.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can
be written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and
double-quotes.
Example
Consider the following example to understand the real use of Python operators.
Output:
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special
character and it interpreted differently. The single quotes inside the string must be escaped. We can apply
the same as in the double quotes.
Example -
Output:
2. \\ Backslash print("\\")
Output:
\
1. print("C:\\Users\\Biswadeep \\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")
Output:
C:\Users\Biswadeep \Python32\Lib
This is the
multiline quotes
This is HEX representation
We can ignore the escape sequence from the given string by using the raw string. We can do this by
writing r or R in front of the string. Consider the following example.
1. print(r"C:\\Users\\Biswadeep \\Python32")
Output:
C:\\Users\\Biswadeep \\Python32
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
The format() method
The format() method is the most flexible and useful method in formatting strings. The curly braces {} are
used as the placeholder in the string and replaced by the format() method argument. Let's have a look at
the given an example:
Output:
Python allows us to use the format specifiers used in C's printf statement. The format specifiers in Python
are treated in the same way as they are treated in C. However, Python provides an additional operator %,
which is used as an interface between the format specifiers and their values. In other words, we can say
that it binds the format specifiers to the values.
1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My value is %s"%
(Integer,Float,String))
Output:
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
center(width ,fillchar) It returns a space padded string with the original string centred with
equal number of left and right spaces.
decode(encoding = 'UTF8', errors = Decodes the string using codec registered for encoding.
'strict')
encode() Encode S using the codec registered for encoding. Default encoding
is 'utf-8'.
endswith(suffix It returns a Boolean value if the string terminates with given suffix
,begin=0,end=len(string)) between begin and end.
expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default space value
is 8.
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
index(subsring, beginIndex, It throws an exception if string is not found. It works same as find()
endIndex) method.
isalnum() It returns true if the characters in the string are alphanumeric i.e.,
alphabets or numbers and there is at least 1 character. Otherwise, it
returns false.
isalpha() It returns true if all the characters are alphabets and there is at least
one character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
isdigit() It returns true if all the characters are digits and there is at least one
character, otherwise False.
istitle() It returns true if the string is titled properly and false otherwise. A
title string is the one in which the first character is upper-case
whereas the other characters are lower-case.
isupper() It returns true if all the characters of the string(if exists) is true
otherwise it returns false.
ljust(width[,fillchar]) It returns the space padded strings with the original string left
justified to the given width.
lstrip() It removes all leading whitespaces of a string and can also be used
to remove particular character from leading.
partition() It searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
replace(old,new[,count]) It replaces the old sequence of characters with the new sequence.
The max characters are replaced if max is given.
rjust(width,[,fillchar]) Returns a space padded string having original string right justified to
the number of characters specified.
rstrip() It removes all trailing whitespace of a string and can also be used to
remove particular character from trailing.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the backward
direction. It returns the list of words in the string. If Separator is not
specified then the string splits according to the white-space.
split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It returns the
list of substring concatenated with the delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.
startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given str between
begin and end.
title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.
translate(table,deletechars = '') It translates the string according to the translation table passed in
the function .
rpartition()
Python List
In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds of
values or items. Since Python lists are mutable, we can change their elements after forming. The comma (,)
and the square brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most common and reliable form. A list, a
type of sequence data, is used to store the collection of data. Tuples and Strings are two similar data formats
for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other languages, such as Array
List in Java and Vector in C++. A list is a collection of items separated by commas and denoted by the symbol
[].
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
List Declaration
Code
1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10. print(type(list1))
11. print(type(list2))
Output:
Characteristics of Lists
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b
Output:
False
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
The indistinguishable components were remembered for the two records; however, the subsequent
rundown changed the file position of the fifth component, which is against the rundowns' planned request.
False is returned when the two lists are compared.
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b
Output:
True
Records forever protect the component's structure. Because of this, it is an arranged collection of things.
Code
Output:
In the preceding illustration, we printed the employee and department-specific details from lists that we had
created. To better comprehend the List's concept, look at the code above.
The indexing procedure is carried out similarly to string processing. The slice operator [] can be used to get
to the List's components.
The index ranges from 0 to length -1. The 0th index is where the List's first element is stored; the 1st index
is where the second element is stored, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
The start parameter is the initial index, the step is the ending index, and the value of the end parameter is
the number of elements that are "stepped" through. The default value for the step is one without a specific
value. Inside the resultant Sub List, the same with record start would be available, yet the one with the file
finish will not. The first element in a list appears to have an index of zero.
Code
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default, the index value is 0 so its starts from the 0th element and go for index -1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
In contrast to other programming languages, Python lets you use negative indexing as well. The negative
indices are counted from the right. The index -1 represents the final element on the List's right side, followed
by the index -2 for the next member on the left, and so on, until the last element on the left is reached.
Let's have a look at the following example where we will use negative indexing to access the elements of the
list.
Code
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Negative indexing allows us to obtain an element, as previously mentioned. The rightmost item in the List
was returned by the first print statement in the code above. The second print statement returned the sub-
list, and so on.
Due to their mutability and the slice and assignment operator's ability to update their values, lists are
Python's most adaptable data structure. Python's append() and insert() methods can also add values to a
list.
Consider the following example to update the values inside the List.
Code
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
1. # updating list values
2. list = [1, 2, 3, 4, 5, 6]
3. print(list)
4. # It will assign value to the value to the second index
5. list[2] = 10
6. print(list)
7. # Adding multiple-element
8. list[1:3] = [89, 78]
9. print(list)
10. # It will add value at the end of the list
11. list[-1] = 25
12. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python also provides us the remove() method
if we do not know which element is to be deleted from the list.
Code
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were working with the
strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on different occasions.
Code
1. # repetition of list
2. # declaring the list
3. list1 = [12, 14, 16, 18, 20]
4. # repetition operator *
5. l = list1 * 2
6. print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
Code
Output:
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
3. Length
Code
Output:
4. Iteration
Code
Output:
12
14
16
39
40
5. Membership
Code
Output:
False
False
False
True
True
True
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated as
follows.
Code
1. # iterating a list
2. list = ["John", "David", "James", "Jonathan"]
3. for i in list:
4. # The i variable will iterate over the elements of the List and contains each element in each iteration.
5. print(i)
Output:
John
David
James
Jonathan
The append() function in Python can add a new item to the List. In any case, the annex() capability can
enhance the finish of the rundown.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Consider the accompanying model, where we take the components of the rundown from the client and print
the rundown on the control center.
Code
Output:
The remove() function in Python can remove an element from the List. To comprehend this idea, look at the
example that follows.
Example -
Code
1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")
Output:
Python provides the following built-in functions, which can be used with the lists.
1. len()
2. max()
3. min()
len( )
Code
Output:
Max( )
Code
782
Min( )
Code
Output:
103
Code
1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:
Example:2- Compose a program to track down the amount of the component in the rundown.
Code
1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Output:
Example: 3- Compose the program to find the rundowns comprise of somewhere around one normal
component.
Code
1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)
Output:
The main difference between the two is that we cannot alter the components of a tuple once they have been
assigned. On the other hand, we can edit the contents of a list.
Example
o Tuples are an immutable data type, meaning their elements cannot be changed after they are
generated.
o Each element in a tuple has a specific order that will never change because tuples are ordered
sequences.
Forming a Tuple:
All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis ().
Although parentheses are not required, they are recommended.
Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be
contained in a tuple.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Code
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not necessary for the construction of multiples. This is known as triple pressing.
Code
Essentially adding a bracket around the component is lacking. A comma must separate the element to be
recognized as a tuple.
Code
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Indexing
Indexing We can use the index operator [] to access an object in a tuple, where the index starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised assuming we attempt
to get to a list from the Tuple that is outside the scope of the tuple record. An index above four will be out
of range in this scenario.
Because the index in Python must be an integer, we cannot provide an index of a floating data type or any
other type. If we provide a floating index, the result will be TypeError.
The method by which elements can be accessed through nested tuples can be seen in the example below.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Code
Output:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
o Negative Indexing
The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.
Code
Output:
Slicing
Tuple slicing is a common practice in Python and the most common way for programmers to deal with
practical issues. Look at a tuple in Python. Slice a tuple to access a variety of its elements. Using the colon as
a straightforward slicing operator (:) is one strategy.
To gain access to various tuple elements, we can use the slicing operator colon (:).
Code
Output:
Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or remove tuple
components as a result.
Code
Output:
Code
Output:
Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are a few ways to work with tuples in
Python. With some examples, this essay will go over these two approaches in detail.
o Count () Method
The times the predetermined component happens in the Tuple is returned by the count () capability of the
Tuple.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Code
1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:
Code
1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Tuple Membership Test
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.
Code
Output:
True
False
False
True
Code
Output:
Python
Tuple
Ordered
Immutable
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Changing a Tuple
This suggests that once the elements of a tuple have been defined, we cannot change them. However, the
nested elements can be altered if the element itself is a changeable data type like a list.
Code
Output:
The + operator can be used to combine multiple tuples into one. This phenomenon is known as
concatenation.
We can also repeat the elements of a tuple a predetermined number of times by using the * operator. This
is already demonstrated above.
Code
Output:
This tutorial will study the major differences between lists and tuples and how to handle these two data
structures.
Lists and tuples are types of data structures that hold one or more than one objects or items in a predefined
order. We can contain objects of any data type in a list or tuple, including the null data type defined by the
None Keyword.
In most cases, lists and tuples are equivalent. However, there are some important differences to be explored
in this article.
The syntax of a list differs from that of a tuple. Items of a tuple are enclosed by parentheses or curved
brackets (), whereas items of a list are enclosed by square brackets [].
Example Code
1. # Python code to show the difference between creating a list and a tuple
2.
3. list_ = [4, 5, 7, 1, 7]
4. tuple_ = (4, 1, 8, 3, 9)
5.
6. print("List is: ", list_)
7. print("Tuple is: ", tuple_)
Output:
We declared a variable named list_, which contains a certain number of integers ranging from 1 to 10. The
list is enclosed in square brackets []. We also created a variable called tuple_, which holds a certain number
of integers. The tuple is enclosed in curly brackets (). The type() method in Python returns the data type of
the data structure or object passed to it.
Example Code
1. # Code to print the data type of the data structure using the type() function
2. print( type(list_) )
3. print( type(tuple_) )
Output:
<class 'list'>
<class 'tuple'>
An important difference between a list and a tuple is that lists are mutable, whereas tuples are immutable.
What exactly does this imply? It means a list's items can be changed or modified, whereas a tuple's items
cannot be changed or modified.
We can't employ a list as a key of a dictionary because it is mutable. This is because a key of a Python
dictionary is an immutable object. As a result, tuples can be used as keys to a dictionary if required.
Let's consider the example highlighting the difference between lists and tuples in immutability and
mutability.
Example Code
We altered the string of list_ at index 3 in the above code, which the Python interpreter updated at index 3
in the output. Also, we tried to modify the last index of the tuple in a try block, but since it raised an error,
we got output from the except block. This is because tuples are immutable, and the Python interpreter raised
TypeError on modifying the tuple.
Size Difference
Since tuples are immutable, Python allocates bigger chunks of memory with minimal overhead. Python, on
the contrary, allots smaller memory chunks for lists. The tuple would therefore have less memory than the
list. If we have a huge number of items, this makes tuples a little more memory-efficient than lists.
For example, consider creating a list and a tuple with the identical items and comparing their sizes:
Example Code
Output:
Size of tuple: 28
Size of list: 52
Available Functions
Tuples have fewer built-in functions than lists. We may leverage the in-built function dir([object] to access
all the corresponding methods for the list and tuple.
Example Code
Output:
Example Code
Output:
As we can observe, a list has many more methods than a tuple. With intrinsic functions, we can perform
insert and pop operations and remove and sort items from the list not provided in the tuple.
o They both hold collections of items and are heterogeneous data types, meaning they can contain
multiple data types simultaneously.
o They're both ordered, which implies the items or objects are maintained in the same order as they
were placed until changed manually.
o Because they're both sequential data structures, we can iterate through the objects they hold; hence,
they are iterables.
o An integer index, enclosed in square brackets [index], can be used to access objects of both data
types.
The Array is an idea of storing multiple items of the same type together, making it easier to calculate the
position of each element by simply adding an offset to the base value. A combination of the arrays could
save a lot of time by reducing the overall size of the code. It is used to store multiple values in a single
variable. If you have a list of items that are stored in their corresponding variables like this:
1. car1 = "Lamborghini"
2. car2 = "Bugatti"
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
3. car3 = "Koenigsegg"
If you want to loop through cars and find a specific one, you can use the Array. You can use an array to store
more than one item in a specific variable.
The Array can be handled in Python by a module named Array. It is useful when we must manipulate only
specific data values. The following are the terms to understand the concept of an array:
Index - The location of an element in an array has a numerical index, which is used to identify the element's
position. The index value is very much important in an Array.
Array Representation:
An array can be declared in various ways and in different languages. The important points that should be
considered are as follows:
Array operations
The Array can be created in Python by importing the array module to the python program.
We can access the array elements using the respective indices of those elements.
Program code:
Here we give an example of how we access the elements of an array using its index value in Python. The
code is given below -
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
1. import array as arr
2. a = arr.array('i', [2, 4, 5, 6])
3. print("First element is:", a[0])
4. print("Second element is:", a[1])
5. print("Third element is:", a[2])
6. print("Forth element is:", a[3])
7. print("last element is:", a[-1])
8. print("Second last element is:", a[-2])
9. print("Third last element is:", a[-3])
10. print("Forth last element is:", a[-4])
11. print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
Explanation:
In the above example, we have imported an array, defined a variable named "a" that holds the elements of
an array, and printed the elements by accessing elements through the indices of an array. Here we can easily
find out the array element by using the array index like a[0], a[1], a[-1], and so on.
Arrays are mutable, and their elements can be changed similarly to lists.
Program code:
Here in this example, we can change or add or replace any element from the Array in Python. The code is
given below -
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
Explanation:
In the above example, we have imported an array and defined a variable named "numbers," which holds the
value of an array. If we want to change or add the elements in an array, we can do it by defining the index
of an array where we want to change or add the elements. Here we just mentioned the index number of
elements you want to change and declared the new value by which you want to replace the old elements.
A combination of arrays saves a lot of time. The Array can reduce the overall size of the code. Using an array,
we can solve a problem quickly in any language. The Array is used for dynamic memory allocation.
The elements can be deleted from an array using Python's del statement. If we want to delete any value
from the Array, we can use the indices of a particular element.
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
The length of an array is defined as the number of elements present in an array. It returns an integer value
that is equal to the total number of the elements present in that array.
Syntax
By using the syntax below, we can easily find the length of the given Array. The syntax is -
1. len(array_name)
Array Concatenation
Example 1:
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
Explanation
In the above example, we have defined variables named as "a, b, c" that hold the values of an array.
Example 2:
Output:
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
First element: 4
Second element: 7
Second last element: 22
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
Explanation:
In the above example, first, we imported an array and defined a variable named "x," which holds the value
of an array. Then, we printed the elements of an array using the index value of this array element.
Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating real-
world data arrangements where a certain value exists for a given key.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object. The
keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers. Dictionary entries are
ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered.
Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches
as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its
value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:
In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an
immutable object.
Code
Output
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to create the dictionary.
Code
Output
Empty Dictionary:
{}
To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be
used to obtain the values because they are unique from one another. The following method can be used to
access dictionary values.
Code
Output
ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary values. It would give
the same result as given by the indexing.
The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key] =
value and the value can both be modified. An existing value can also be updated using the update() method.
Example - 1:
Code
Output
Empty Dictionary:
{}
Example - 2:
Code
Output
<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the details of the new
employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}
The items of the dictionary can be deleted by using the del keyword as given below.
Code
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Lets try to print it again
NameError: name 'Employee' is not defined.
The last print statement in the above code, it raised an error because we tried to print the Employee
dictionary that already deleted.
A dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove items using this
unordered, mutable data type by using their keys. The pop() method is one of the ways to get rid of elements
from a dictionary. In this post, we'll talk about how to remove items from a Python dictionary using the pop()
method.
The value connected to a specific key in a dictionary is removed using the pop() method, which then returns
the value. The key of the element to be removed is the only argument needed. The pop() method can be
used in the following ways:
Code
1. # Creating a Dictionary
2. Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
3. # Deleting a key
4. # using pop() method
5. pop_key = Dict1.pop(2)
6. print(Dict1)
Output
Additionally, Python offers built-in functions popitem() and clear() for removing dictionary items. In contrast
to the clear() method, which removes all of the elements from the entire dictionary, popitem() removes any
element from a dictionary.
Iterating Dictionary
Example 1
Code
Output
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Name
Age
salary
Company
Example 2
Code
Output
John
29
25000
WIPRO
Example - 3
Code
1. #for loop to print the values of the dictionary by using values() method.
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.values():
4. print(x)
Output
John
29
25000
WIPRO
Example 4
Code
1. #for loop to print the items of the dictionary by using items() method
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.items():
4. print(x)
Output
('Name', 'John')
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a
single key, then the value which is last assigned is considered as the value of the key.
Code
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
2. "John"}
3. for x,y in Employee.items():
4. print(x,y)
Output
Name John
Age 29
Salary 25000
Company WIPRO
2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples can be used as the
key, however mutable objects like lists cannot be used as the key in a dictionary.
Code
Output
A function is a method that can be used on a construct to yield a value. Additionally, the construct is
unaltered. A few of the Python methods can be combined with a Python dictionary.
The built-in Python dictionary methods are listed below, along with a brief description.
o len()
The dictionary's length is returned via the len() function in Python. The string is lengthened by one for each
key-value pair.
Code
Output
4
o any()
Like how it does with lists and tuples, the any() method returns True indeed if one dictionary key does have
a Boolean expression that evaluates to True.
Code
Output
True
o all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True Boolean value.
Code
Output
False
o sorted()
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Like it does with lists and tuples, the sorted() method returns an ordered series of the dictionary's keys. The
ascending sorting has no effect on the original Python dictionary.
Code
Output
[ 1, 5, 7, 8]
The built-in python dictionary methods along with the description and Code are given below.
o clear()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # clear() method
4. dict.clear()
5. print(dict)
Output
{}
o copy()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)
Output
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # pop() method
4. dict_demo = dict.copy()
5. x = dict_demo.pop(1)
6. print(x)
Output
popitem()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # popitem() method
4. dict_demo.popitem()
5. print(dict_demo)
Output
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # keys() method
4. print(dict_demo.keys())
Output
dict_keys([1, 2, 3, 4, 5])
o items()
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
It returns all the key-value pairs as a tuple.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # items() method
4. print(dict_demo.items())
Output
dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
o get()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # get() method
4. print(dict_demo.get(3))
Output
Facebook
o update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # update() method
4. dict_demo.update({3: "TCS"})
5. print(dict_demo)
Output
It returns all the values of the dictionary with respect to given input.
Code
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # values() method
4. print(dict_demo.values())
Output
In this article, we are discussing Python Operators. The operator is a symbol that performs a specific
operation between two operands, according to one definition. Operators serve as the foundation upon
which logic is constructed in a program in a particular programming language. In every programming
language, some operators perform several tasks. Same as other languages, Python also has some operators,
and these are given below -
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are many arithmetic
operators. It includes the exponent (**) operator as well as the + (addition), - (subtraction), * (multiplication),
/ (divide), % (reminder), and // (floor division) operators.
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand
is less than the second operand, the value results negative. For example, if a = 20, b
= 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a
(Multiplication) * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent
operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two
division) operands.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators compare the values of
the two operands and return a true or false Boolean value in accordance. The example of comparison
operators are ==, !=, <=, >=, >, <. In the below table, we explain the works of the operators.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Program Code:
Now we give code examples of Comparison operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Using the assignment operators, the right expression's value is assigned to the left operand. There are some
examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In the below table, we explain the works of
the operators.
Operator Description
+= By multiplying the value of the right operand by the value of the left operand, the left operand
receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a
= a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be
equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a
= a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Program Code:
Now we give code examples of Assignment operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of Bitwise
operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift
(>>). Consider the case below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
10. Let, Binary of x = 0101
11. Binary of y = 1000
12. Bitwise OR = 1101
13. 8 4 2 1
14. 1 1 0 1 = 8 + 4 + 1 = 13
15.
16. Bitwise AND = 0000
17. 0000 = 0
18.
19. Bitwise XOR = 1101
20. 8 4 2 1
21. 1 1 0 1 = 8 + 4 + 1 = 13
22. Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
23. ~x = -6
In the below table, we are explaining the works of the bitwise operators.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0
and) is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be
1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the value of
the left operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Program Code:
Now we give code examples of Bitwise operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The examples of logical
operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend upon the
second one. In the case of logical OR, if the first one is 1, it does not depend on the second one. Python
supports the following logical operators. In the below table, we explain the works of the logical operators.
Operator Description
and The condition will also be true if the expression is true. If the two expressions a and b are the
same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two expressions,
then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is given below -
Output:
Now we give code examples of Bitwise operators in Python. The code is given below -
Membership Operators
The membership of a value inside a Python data structure can be verified using Python membership
operators. The result is true if the value is in the data structure; otherwise, it returns false.
Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be true (list, tuple,
or dictionary).
not in If the first operand is not present in the second operand, the evaluation is true (list, tuple, or
dictionary).
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Program Code:
Now we give code examples of Membership operators in Python. The code is given below -
1. x = ["Rose", "Lotus"]
2. print(' Is value Present?', "Rose" in x)
3. print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Identity Operators
Operator Description
is If the references on both sides point to the same object, it is determined to be true.
is not If the references on both sides do not point at the same object, it is determined to be true.
Program Code:
Now we give code examples of Identity operators in Python. The code is given below -
1. a = ["Rose", "Lotus"]
2. b = ["Rose", "Lotus"]
3. c = a
4. print(a is c)
5. print(a is not c)
6. print(a is b)
7. print(a is not b)
8. print(a == b)
9. print(a != b)
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
True
False
False
True
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
True
False
Operator Precedence
The order in which the operators are examined is crucial to understand since it tells us which operator needs
to be considered first. Below is a list of the Python operators' precedence tables.
Operator Description
** Overall other operators employed in the expression, the exponent operator is given
precedence.
* / % // the division of the floor, the modules, the division, and the multiplication.
<= < > >= Comparison operators (less than, less than equal to, greater than, greater then equal
to).
Conclusion:
So, in this article, we are discussing all the Python Operators. We briefly discuss how they work and share
the program code using each operator in Python.
We will gain knowledge about both Python operator precedence and associativity in this tutorial.
Understanding the mechanics of Python operators is critical for developers.
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
It would be best if the reader understood how Python assesses the ordering of its operators after checking
it. Some operators prioritize others; for example, the division operator takes precedence over the
multiplication operator; therefore, division comes first.
The Python interpreter executes operations of higher precedence operators first in any given logical or
arithmetic expression. Except for the exponent operator (**), all other operators are executed from left to
right.
An expression is a collection of numbers, variables, operations, and built-in or user-defined function calls.
The Python interpreter can evaluate a valid expression.
Code
1. 2 - 7
Output:
-5
The expression 2 - 7 is used as an example here. In an expression, we can add multiple operators. There is a
principle of precedence in Python for evaluating these types of expressions. It directs the sequence in which
certain tasks are completed.
Code
Output:
24.0
However, we can reverse this sequence by employing parenthesis (), which takes precedence over division.
Code
Output:
16.0
The following table shows the precedence of Python operators. It's in reverse order (the upper operator
holds higher precedence than the lower operator).
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
or Logical OR
Assume we're building an if...else block that only executes if the color is red or green and quantity is greater
than or equal to 5.
Code
Output:
Code
Output:
We can observe that a given category contains many operators in the list above. The order of these operators
is identical.
Associativity aids in determining the sequence of operations when two operators share the same priority.
The direction in which any given expression with more than one operator having the same precedence is
assessed is associativity. Almost every operator is associative from left to right.
Code
Output:
12
12
Unit 1 : INTRODUCTION, VARIABLES AND DATA TYPES
Code
Output:
6561
729
Several operators, such as comparison or assignment operators, don't have such associativity rules in
Python. Patterns of this type of operator have their own rules that can not be represented as associativity.
For instance, a < b < c is not the same as (a < b) < c or a < (b < c). a < b < c is assessed from left to right and is
similar to a < b and b < c.
Code
Output:
a = b = c += 2
^
SyntaxError: invalid syntax
<< >> Bitwise left shift / Bitwise right shift left to right
< <= Relational operators: less than / less than or equal to / greater than / left to right
> >= greater than or equal to
Bracket, Order, Division, Multiplication, Addition, and Subtraction are all acronyms for BODMAS. When
various arithmetic operations are present in an equation, this rule specifies the sequence they should be
computed.
If we peek at the precedence chart given above, we'll notice that the order of operators is in the following
manner:
Conclusion
Precedence rules determine the priority in which various operators are implemented in an equation.
The way several operations of the identical level, or operators having the same precedence, are used in an
equation is determined by the rules of associativity.
Unit 2 : Control Structures
Conditional Expressions in Python
Python's conditional statements carry out various calculations or operations according to whether a
particular Boolean condition is evaluated as true or false. In Python, IF statements deal with conditional
statements.
To make decisions, utilize the if statement in Python. It has a body of instructions that only executes
whenever the if statement's condition is met. The additional else statement, which includes some
instructions for the else statement, runs if the if condition is false.
Python's if-else statement is used when you wish to satisfy one statement while the other is false.
1. if <conditional expression>
2. Statement
3. else
4. Statement
Code
Output:
a is greater than b
The "else condition" is usually used when judging one statement based on another. If the condition
mentioned in the if code block is wrong, then the interpreter will execute the else code block.
Unit 2 : Control Structures
Code
Output:
a is greater than b
There could be a lot of situations where your "otherwise condition" doesn't produce the desired outcome.
Due to a flaw in the program's logic, it will print the incorrect result. This typically occurs when there are
more than two statements or conditions in a program.
Since both variables, in this case, are identical (9, 9), the program's output that "x is greater than y" is FALSE.
This is because it evaluates the first condition, or the if expression in Python, then prints the next condition
(the else statement) by default if the first condition fails. The following step will examine how to fix this
mistake.
Code
Output:
Unit 2 : Control Structures
a is greater than b
We can employ the "elif" clause to fix the issue caused by the "else condition" made earlier. You can instruct
the software to print the third condition or alternative when the first two conditions fail or are erroneous by
using the "elif" condition.
Code
Output:
a is equal to b
Code
Output:
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running
the loops. The basic functionality of all the techniques is the same, although the syntax and the amount of
time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.
1 While loop Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.
2 For loop This type of loop executes a code block multiple times and abbreviates the code
that manages the loop variable.
Statements used to control loops and change the course of iteration are called control statements. All the
objects produced within the local scope of the loop are deleted when execution is completed.
Python provides the following control statements. We will discuss them later in detail.
1 Break statement This command terminates the loop's execution and transfers the program's
control to the statement next to the loop.
2 Continue This command skips the current iteration of the loop. The statements
statement following the continue statement are not executed once the Python
interpreter reaches the continue statement.
3 Pass statement The pass statement is used when a statement is syntactically necessary, but
no code is to be executed.
Python's for loop is designed to repeatedly execute a code block while iterating through a list, tuple,
dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration.
In this case, the variable value is used to hold the value of every item present in the sequence before the
iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
Code
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
As already said, a for loop executes the code block until the sequence element is reached. The statement is
written right after the for loop is executed after the execution of the for loop is complete.
Only if the execution is complete does the else statement comes into play. It won't be executed if we exit
the loop or if an error is thrown.
Code
Output:
P
y
t
h
Unit 2 : Control Structures
If block
n
L
If block
If block
p
Syntax:
Code
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
Unit 2 : Control Structures
The range() Function
With the help of the range() function, we may produce a series of numbers. range(10) will produce values
between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step
size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object can be characterized
as being "slow." It does provide in, len, and __getitem__ actions, but it is not an iterator.
Code
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We can use indexing
to iterate through the given sequence by combining it with an iterable's len() function. Here's an illustration.
Code
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. However, the statement in the
program that follows the while loop is executed once the condition changes to false.
1. while <condition>:
2. { code block }
All the coding statements that follow a structural command define a code block. These statements are
intended with the same number of spaces. Python groups statements together with indentation.
Code
Output:
Python Loops
Python Loops
Python Loops
Python Loops
As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the
same syntax.
Code
1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
Unit 2 : Control Structures
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where we
can write the code block in a single line.
Code
Now we will discuss the loop control statements in detail. We will see an example of each control statement.
Continue Statement
Code
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and
empty control statements.
Code
Output:
Unit 2 : Control Structures
Last Letter: s
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:
1. #loop statements
2. break;
Code
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.
Code
Output:
p
y
t
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.
Code
Output:
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.
Code
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.
Unit 3 : FUNCTION MODULES AND PACKAGES
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.
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.
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.
Syntax
We will define a function that returns the argument number's square when called.
Output:
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.
Output:
In the Python programming language, all parameters are passed by reference. It shows that if we modify the
worth of contention within a capability, the calling capability will similarly mirror the change. For instance,
Code
Output:
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
Output:
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
Output:
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
Output:
Unit 3 : FUNCTION MODULES AND PACKAGES
Passing out of order arguments
number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments
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:
Code
Output:
return Statement
Unit 3 : FUNCTION MODULES AND PACKAGES
When a defined function is called, a return statement is written to exit the function and return the calculated
value.
Syntax:
The return statement can be an argument, a statement, or a value, and it is provided as output when a
particular job or function is finished. A declared function will return an empty string if no return statement
is written.
Code
Output:
Since we do not use the def keyword to declare these kinds of Python functions, they are unknown. The
lambda keyword can define anonymous, short, single-output functions.
Arguments can be accepted in any number by lambda expressions; However, the function only produces a
single value from them. They cannot contain multiple instructions or expressions. Since lambda needs
articulation, a mysterious capability can't be straightforwardly called to print.
Lambda functions can only refer to variables in their argument list and the global domain name because they
contain their distinct local domain.
In contrast to inline expressions in C and C++, which pass function stack allocations at execution for efficiency
reasons, lambda expressions appear to be one-line representations of functions.
Syntax
Code
Output:
A variable's scope refers to the program's domain wherever it is declared. A capability's contentions and
factors are not external to the characterized capability. They only have a local domain as a result.
The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same as the
lifespan of its internal variables. When we exit the function, they are taken away from us. As a result, the
value of a variable in a function does not persist from previous executions.
Output:
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.
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
Output:
If we have been working with OOPS paradigm languages, we should've heard the word "attributes" quite
often. There are two types of attributes-class attributes and instance attributes. This tutorial explains what
attributes are and their types, along with examples.
As Python is a huge supporter of the OOPS paradigm, everything is regarded as an object. We create classes
and objects. Before understanding attributes, understanding classes and objects is the foundation. In a
simple sentence, a class is like a blueprint and to use that blueprint, we create objects for that class.
Example:
1. class student:
2. sch_name = "Delhi public school"
3. place = "Delhi"
4. grade = 5
5. def display(self):
6. print("School:", self.sch_name)
7. print("Place:", self.place)
8. print("Grade:", self.grade)
9. s1 = student()
10. s2 = student()
11. print(s1.sch_name)
12. s1.display()
13. print(s2.sch_name)
14. s2.display()
Output:
Understanding:
In the above example, we created a class called "student" with three variables and a function that prints the
values of the three variables. Every object we create for the class has access to the variables in the class.
These variables are called the "Attributes", and the functions are called methods (also referred to as
functions). In the above program, we created the class's two objects, s1 and s2, and accessed the attribute
sch_name and the method display() printed the values of the attributes.
Types of Attributes:
Class Attributes:
o In the previous example, we declared attributes that don't change, which means that for any object
we create for the class, the values of the attributes remain the same.
o Such attributes are called the "Class attributes".
Example:
1. class Address:
2. University = "Harvard"
3. City = "Cambridge"
4. State = "Massachusetts"
5. Capital = "Boston"
6. Country = "United States"
7. student1 = Address()
8. print("Student1: Ryan")
9. print(student1.University,"",student1.City,"",student1.State,"",student1.Capital,"",student1.Country)
10. student2 = Address()
11. print("Student2: Tony")
12. print(student2.University,"",student2.City,"",student2.State,"",student2.Capital,"",student2.Country)
Output:
Student1: Ryan
Harvard Cambridge Massachusetts Boston United States
Student2: Tony
Harvard Cambridge Massachusetts Boston United States
o Observe that the information in the class is storing the same values representing the address of the
university and we used the same information for all the objects-students.
Unit 3 : FUNCTION MODULES AND PACKAGES
Instance Attributes:
o What if we wanted to create a class that allows every object to have its attributes? It is possible too.
For example, every object should hold information about an individual student.
o Such class attributes that can let objects hold different values for the same attribute are called the
"Instance attributes".
o We need to use the __init__ method and self variable to declare these attributes.
o __init__ method: It is a constructor that allows objects to have different values for the same
attribute. It is executed as soon as an object is created for the class without any manual call.
o self variable: It is like a placeholder for the object created for the class inside the __init__ method:
Example:
1. class Student_info:
2. def __init__(self, name, age, college):
3. self.name = name;
4. self.age = age;
5. self.college = college;
6. student1 = Student_info("Ryan", 18, "NYU")
7. student2 = Student_info("Roy", 18, "Duke")
8. print("Student1: ")
9. print(student1.name, student1.age, student1.college)
10. print("Student2: ")
11. print(student2.name, student2.age, student2.college)
Output:
Student1:
Ryan 18 NYU
Student1:
Roy 18 Duke
o We created two objects, student1 and student2, and the two objects hold different information
about two individuals.
o What happens here is that once an object is created, __init__ method is invoked, and the object will
replace the self variable in the method:
Both Instance attributes and Class attributes play a prominent role in creating a sound class. Here is an
example using both class variables and instance variables to create a class:
1. class Address:
2. University = "Harvard"
3. City = "Cambridge"
4. State = "Massachusetts"
5. Capital = "Boston"
6. Country = "United States"
7. def __init__(self, name, age, CGPA):
8. self.name = name
9. self.age = age
10. self.CGPA = CGPA
11. student1 = Address("Ryan", 18, 9.2)
12. print("Student1:")
13. print(student1.name, student1.age, student1.CGPA)
14. print(student1.University, student1.City, student1.State, student1.Capital, student1.Country)
15. print("\nStudent2:")
16. student2 = Address("Roy", 18, 9.1)
17. print(student2.name, student2.age, student2.CGPA)
18. print(student2.University, student2.City, student2.State, student2.Capital, student2.Country)
Output:
Student1:
Ryan 18 9.2
Harvard Cambridge Massachusetts Boston United States
Student2:
Roy 18 9.1
Harvard Cambridge Massachusetts Boston United States
o We used class attributes to store the data common to all the objects and instance attributes for
storing distinct data of every single object.
o Also, observe that:
Class attributes:
1. University
2. City
3. State
4. Capital
5. Country
Instance attributes:
1. name
2. age
3. CGPA
Python provides two built-in functions that can print the attributes of a particular object:
1. dir() -> It returns both class attributes and instance attributes of the object along with the attributes
of the ancestor classes of the object.
2. vars() -> It returns the instance attributes of an object in the form of a dictionary.
Example:
1. print(vars(student1))
2. print()
3. print(dir(student1))
Output:
['CGPA', 'Capital', 'City', 'Country', 'State', 'University', '__class__', '__delattr__', '__dict__', '__dir__',
'__doc__
Unit 3 : FUNCTION MODULES AND PACKAGES
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:
1. def add_func(a,b):
2. sum = a + b
3. return sum
4. num1 = int(input("Enter the value of the first number: "))
5. num2 = int(input("Enter the value of the second number: "))
6. print("Sum of two numbers: ",add_func(num1, num2))
Output:
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:
Unit 3 : FUNCTION MODULES AND PACKAGES
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:
Output:
o The function has three parameters-name, age and grade. So, it accepts three arguments.
o In the first function call:
1. details("Raghav", 12, 6)
The arguments are passed position-wise to the parameters, which mean according to the passed order:
Here, the first argument, "Santhosh", is passed based on its position to name, and the next two arguments
are passed by assignment to their respective parameters. As you can observe, here, the position didn't
matter.
Important Point:
o Keyword arguments must always follow positional arguments. If not, Python will raise a syntax
error:
This is the most important concept on arguments and parameters. Based on the type of arguments passed
to the parameters, there are two methods of invoking/ calling functions-Call by value and Call by reference.
When the values of arguments are passed into parameters in the function, the values are copied into
parameters. This method is called "Call by value".
In this method, arguments and parameters are different and are stored in different memory locations.
o Changes done on parameters inside the function do not affect the arguments in the program and
vice versa.
o Java functions/ methods follow only Call by value.
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.
Unit 3 : FUNCTION MODULES AND PACKAGES
Which Method does Python Follow?
Python doesn't use Call by value or Call by reference. It follows a method called "Call by assignment". In
Python, every single entity is an object. Objects are divided into Mutable and Immutable objects. What
happens in Python when we assign a value to a variable is different from other low-level languages like C or
Java.
a = 20
a is the variable, and 20 is the value assigned. Here in a memory location, 20 is saved, and a is the name
we're giving to the reference we're making to the memory location. Now, if we say:
a = 21
The name stops referring to the memory location with 20 and starts to refer to another memory location
with 21.
In other languages like C, variables are the memory locations that store the values.
Example:
In C:
1. #include<stdio.h>
2. int main()
3. {
4. int a;
5. a = 20;
6. printf("%p", (void*)&a);
7. a = 22;
8. printf("\n%p", (void*)&a);
9. }
Output:
000000000062FE1C
000000000062FE1C
In Python:
1. a = 20
2. print(id(a))
3. a = 21
4. print(id(a))
Output:
Unit 3 : FUNCTION MODULES AND PACKAGES
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.
1. Mutable objects are those objects/ data types in Python that we can modify after creating them Ex:
Lists, Dictionaries, Sets
2. Immutable objects, on the other hand, are objects that can't be modified once created. Ex: int, float,
strings, tuples
Example:
Mutable Objects:
Output:
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:
1. a = 20
2. print(id(a))
3. a += 23
4. print(id(a))
Output:
140714950863232
140714950863968
Unit 3 : FUNCTION MODULES AND PACKAGES
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?
Example:
Output:
Understanding:
The function accepts 4 arguments. Notice the arguments grade and marks. grade is an integer value which
means it is immutable. Hence, once created, we can't modify it. It follows "Call by Value". As we discussed
Unit 3 : FUNCTION MODULES AND PACKAGES
earlier in the tutorial, when following Call by reference, "Changes done on the parameters (pointers) will
not affect the values of the arguments in the program". Hence, the original value of grade in the program
is not modified after concatenating the string in the function definition.
In the case of marks, it is a list and is mutable. So, it follows "Call by Reference," which means, "Changes
done on the parameters (pointers) will affect the values of the arguments in the program". Hence, the
change is reflected in the original program after appending the list in the function definition.
Variables in Python language serve as the storage units for the various data values and data structures. When
a variable is assigned to any Python object, it then points toward that object since they are reference, or a
pointer, to that particular object in the memory location. Python programming language is not "statically
typed," unlike other languages like C/C++/JAVA. Variables do not have to have their types or initial values
declared before use. When a variable is initially given a value, it is considered to have been formed.
Code
1. # Python program to show how variables are assigned to the data values
2.
3. # Assigning a variable name to an integer
4. integer = 45
5.
6. # Assigning a variable name to a floating point number
7. floating = 1456.8
8.
9. # Assigning a variable name to a string
10. string = "John"
11.
12. print("This value is stored in the variable 'integer':- ", integer)
13. print("This value is stored in the variable 'floating':- ", floating)
14. print("This value is stored in the variable 'string':- ", string)
Output:
Scope of a Variable
The scope of a Python variable refers to the area where we may locate it and, if necessary, access it.
Global variables are those we declare and define outside of any functions but not specific to any of them.
Any section of the program can make use of them.
Unit 3 : FUNCTION MODULES AND PACKAGES
Code
1. # Python program to show how any function can use global variables
2.
3. # Declaring a global variable
4. a = 2
5.
6. # Accessing the global variable in the main function
7. print("This is in the main function:- ", a)
8.
9. # Defining a function that uses the global variable
10. def f1():
11. print("This is in function 'f1()':- ", a)
12.
13. # Defining another function that uses the global variable
14. def f2():
15. print("This is in function 'f2()':- ", a)
16.
17. # Calling the functions
18. f1()
19. f2()
Output:
Suppose a variable is defined within the local scope of that function and has the same name as the global
variable. In that case, it will only display the value supplied to the variable inside that particular function and
not the value assigned in the global scope.
Code
1. # Python program to show function accesses the variable value that is in the function's scope
2.
3. # Declaring a global variable
4. a = "This is assigned in the global scope."
5.
6. # Defining a function that has a variable having the name same as the global variable
7. def func():
Unit 3 : FUNCTION MODULES AND PACKAGES
8. a = "This is defined inside the function."
9. print(a)
10.
11. # Calling the function
12. func()
Output:
Before defining the function func(), the variable 'a' is assigned to a string that states, "This is assigned in the
global scope.". The print(a) statement of the function func() will first search for variable 'a' in its local scope.
Since there is already a variable 'a' assigned to a different string, the function will print the value of this
variable and will not go in the global scope. The function, in this case, will not use the value of variable 'a'
from the global scope.
What will be the result of modifying the value of variable 'a' inside the function 'func()' is the next question.
Will it also have an impact on the global variable 'a'? The following snippet of code is used to test it:
Code
1. # Python program to show function accesses the variable value that is in the function's scope
2.
3. # Declaring a global variable
4. a = "This is assigned in the global scope."
5.
6. # Defining a function that has a variable having the name same as the global variable
7. def func():
8. a = "This is defined inside the function."
9. print("Accessed in the local scope of function:- ", a)
10.
11. # Calling the function
12. func()
13.
14. # Accessing the variable a in the global scope after changing its value inside the function
15. print("Accessed in the global scope:- ", a)
Output:
Accessed in the local scope of function:- This is defined inside the function.
Accessed in the global scope:- This is assigned in the global scope.
We must use the Python global keyword to make the preceding program function. Only when making
assignments or changing the variable value do we need to use the Python global keyword inside a function.
The global keyword is not necessary for displaying and accessing a variable present in the global scope. Why?
Since the assignment to the variable 'a' inside of func(), Python "presumes" that we desire to access the local
Unit 3 : FUNCTION MODULES AND PACKAGES
variable, which is why the initial print command returns the variable's value in the local scope. If a variable
is modified or assigned inside a function without being defined as a global variable, it is considered a local
variable. The following example demonstrates how to use the global keyword to instruct the Python
interpreter that we wish to modify the global variable:
Code
1. # Python program to show function accesses the variable value that is in the function's scope
2.
3. # Declaring a global variable
4. a = "This is assigned in the global scope."
5.
6. # Defining a function that uses the global keyword before assigning a new value to the global variable
7. def func():
8. global a
9. a = "This is defined inside the function."
10.
11. print("Accessed in the local scope of function:- ", a)
12.
13. # Calling the function
14. func()
15.
16. # Accessing the variable a in the global scope after changing its value inside the function
17. print("Accessed in the global scope:- ", a)
Output:
Accessed in the local scope of function:- This is defined inside the function.
Accessed in the global scope:- This is defined inside the function.
Code
Output:
Non-local Keyword
In Python, the nested functions are handled with the Python nonlocal keyword. This keyword acts similarly
global keyword, except that in the case of nested functions, it defines a variable to refer to the variable
assigned in the outer enclosing function rather than the global variable.
Code
Output:
Variables in any programming language have a crucial role. Variables are classified into Global variables and
Local variables based on their scope. The main difference between Global and local variables is that global
variables can be accessed globally in the entire program, whereas local variables can be accessed only within
the function or block in which they are defined. In this topic, we will first understand what are the variables
and scope, along with local variables, global variables, and then differences between both the variables.
Unit 3 : FUNCTION MODULES AND PACKAGES
What is a Variable?
A variable is a name given to a memory location to store values in a computer program. It is used to store
information that can be referenced and manipulated in a program.
We can choose any name for the variable, but it must follow the programming semantics. Such as it can be,
a, b, x, y, z, sub, div, total, avg, etc.
Let's say there are two values, 10 and 20, that we want to store and use in our program. For this, we need
to use a variable, and we will do the below steps:
As we can see in the above image, there are two memory slots, 001 and 002, and we have given names to
these locations as A and B. A is containing 10, and B is containing 20.
Different programming languages have different ways to declare the variable. For example, in C language,
we can declare the variable in the following manner:
Example:
1. #include <stdio.h>
2. void main(){
Unit 3 : FUNCTION MODULES AND PACKAGES
3. int a;
4. int b;
5. int sum;
6. }
Scope of Variable
Each variable is defined and can be used within its scope and determines that wherein the program this
variable is available to use. The scope means the lifetime of that variable. It means the variable can only be
accessed or visible within its scope.
The scope of variables can be defined with their declaration, and variables are declared mainly in two ways:
o Global variables are those variables which are declared outside of all the functions or block and can
be accessed globally in a program.
o It can be accessed by any function present in the program.
o Once we declare a global variable, its value can be varied as used with different functions.
o The lifetime of the global variable exists till the program executes. These variables are stored in fixed
memory locations given by the compiler and do not automatically clean up.
o Global variables are mostly used in programming and useful for cases where all the functions need
to access the same data.
Example:
1. #include<stdio.h>
2. int a=50, b=40;
3. void main()
4. {
5. printf("a = %d and b=%d",a,b);
6. }
o Global variables can be accessed by all the functions present in the program.
o Only a single declaration is required.
o Very useful if all the functions are accessing the same data.
Unit 3 : FUNCTION MODULES AND PACKAGES
Disadvantages of Global Variable
o The value of a global variable can be changed accidently as it can be used by any function in the
program.
o If we use a large number of global variables, then there is a high chance of error generation in the
program.
o Variables that are declared within or inside a function block are known as Local variables.
o These variables can only be accessed within the function in which they are declared.
o The lifetime of the local variable is within its function only, which means the variable exists till the
function executes. Once function execution is completed, local variables are destroyed and no longer
exist outside the function.
o The reason for the limited scope of local variables is that local variables are stored in the stack, which
is dynamic in nature and automatically cleans up the data stored within it.
o But by making the variable static with "static" keyword, we can retain the value of local variable.
Example:
1. #include<stdio.h>
2. void main()
3. {
4. int x=50, y=40;
5. printf("x = %d and y=%d",x, y);
6. }
In the above example, we have declared x and y two variables inside the main function. Hence these are
local variables.
o The same name of a local variable can be used in different functions as it is only recognized by the
function in which it is declared.
o Local variables use memory only for the limited time when the function is executed; after that same
memory location can be reused.
o The scope of the local variable is limited to its function only and cannot be used by other functions.
o Data sharing by the local variable is not allowed.
Unit 3 : FUNCTION MODULES AND PACKAGES
Comparison Chart Between Global Variable and Local Variable
Global variables are declared outside all the Local Variables are declared within a function block.
function blocks.
The scope remains throughout the program. The scope is limited and remains within the function only in
which they are declared.
Any change in global variable affects the Any change in the local variable does not affect other
whole program, wherever it is being used. functions of the program.
A global variable exists in the program for the A local variable is created when the function is executed, and
entire time the program is executed. once the execution is finished, the variable is destroyed.
It can be accessed throughout the program by It can only be accessed by the function statements in which
all the functions present in the program. it is declared and not by the other functions.
If the global variable is not initialized, it takes If the local variable is not initialized, it takes the garbage
zero by default. value by default.
Global variables are stored in the data Local variables are stored in a stack in memory.
segment of memory.
We cannot declare many variables with the We can declare various variables with the same name but in
same name. other functions.
Now let's understand examples in different programming languages to better understand the difference
between local and global variables.
Unit 3 : FUNCTION MODULES AND PACKAGES
Local vs Global in C
Example-1:
1. #include<stdio.h>
2.
3. // Global variables
4. int a;
5. int b;
6. int Add()
7. {
8.
9. return a + b;
10. }
11.
12. int Mul()
13.
14. {
15. int c=10; //Local Variable
16. int d=20; ////Local Variable
17. return c*d;
18. }
19. void main()
20. {
21. int Ans1, Ans2, c=30;// Local variable
22. a = 50;
23. b = 70;
24.
25. Ans1 = Add();
26. Ans2= Mul();
27.
28. printf("The addition result is: %d\n",Ans1);
29. printf("The Multiplication result is: %d\n",Ans2);
30. printf("%d\n", c);
31. }
Output:
If we try to use c and d variables outside the Mul() function, they will be used as new variables. As we have
shown by taking c in the main() function also, it is treated as a new variable.
Example-1:
Output:
Hey, I am a Local Variable!, I can be used within this block only in the program.
Hey, I am Global Variable!, I can be used everywhere in the program.
In the above program, we have taken one global variable v1 and one local variable v2. Since v1 is global, it
can be easily accessed in any function, and v2 is local; it is used only within its declared function. But if we
try to use v1 in func1, it will give an error. Let's see the below example:
Example-2
Runtime Error:
Output:
Hey, I am Local Variable!, I can be used within this block only in the program.
Hey, I am Global Variable!, I can be used everywhere in the program.
Hey, I am Global Variable!, I can be used everywhere in the program.
In Java, there is no concept of global variables; since Java is an Object-oriented programming language,
everything is a part of the Class. But if we want to make a variable globally accessible, we can make it static
by using a static Keyword.
1. class Demo {
2.
3. // static variable
4. static int a = 10;
5.
6. // non-static or local variable
7. int b = 20;
8. }
9.
10. public class Main {
11. public static void main(String[] args) {
12. Demo obj = new Demo();
13.
14. // accessing the non-static variable
15. System.out.println("Value of non-static variable is: " + (obj.b));
16.
17. // accessing the static variable
18. System.out.println("Value of static variable is:" + (Demo.a));
19. }
20. }
Output:
It is often that many coders and amateur programmers may confuse between a module and a package. The
problem generally arises when it becomes hard to identify when and where a module or a package should
be implemented.
In the following tutorial, we will discuss a clear set of differences in modules and packages in the Python
programming language that will make it easy for the programmers to work more professionally while dealing
with both modules and packages.
A module is a pythonic statement containing different functions. Modules act as a pre-defined library in the
script, which is accessible to both the programmers as well as the user.
The python modules also store pre-defined functions from the library when the code is being executed.
Example:
Output:
Explanation:
In the above snippet of code, we have imported the required module and used the pow() function to
calculate the powers of the given number as arguments. We have then printed the value of the pow for the
user.
Unit 3 : FUNCTION MODULES AND PACKAGES
Understanding the Packages in Python
A package is considered a collection of tools that allows the programmers to initiate the code. A Python
package acts as a user-variable interface for any source code. This feature allows a Python package to work
at a defined time for any functional script in the runtime.
Example:
Output:
Explanation:
In the above snippet of code, we have imported the math package that consists of various modules and
functions for the programmers and printed a statement for the users.
1. A Package consists of the __init__.py file for each user-oriented script. However, the same does not
apply to the modules in runtime for any script specified to the users.
2. A module is a file that contains a Python script in runtime for the code specified to the users. A
package also modifies the user interpreted code in such a manner that it gets easily operated in the
runtime.
A python "module" contains a unit namespace, with the variables that are extracted locally along with some
parsed functions like:
There are some usually utilized tools that allow the programmers to build a new platform with the help of
the modules for better code executions. This installs and distributes packages throughout the library in
runtime as well.
It becomes easier for us to employ the user-specific tools with the help of a well-structured and standard
layout for the package.
Unit 4 File Input or Output Text procesing Regular expressions
How to take input in Python?
Taking input is a way of interact with users, or get data to provide some result. Python provides two built-
in methods to read the data from the keyboard. These methods are given below.
o input(prompt)
o raw_input(prompt)
input()
The input function is used in all latest version of the Python. It takes the input from the user and then
evaluates the expression. The Python interpreter automatically identifies the whether a user input a string,
a number, or a list. Let's understand the following example.
Example -
Output:
The Python interpreter will not execute further lines until the user enters the input.
Example - 2
Output:
Explanation:
By default, the input() function takes input as a string so if we need to enter the integer or float type input
then the input() function must be type casted.
We can see in the above code where we type casted the user input into int and float.
o The flow of the program has stopped until the user enters the input.
o The text statement which also knows as prompt is optional to write in input() function. This prompt
will display the message on the console.
o The input() function automatically converts the user input into string. We need to explicitly convert
the input using the type casting.
o raw_input() - The raw_input function is used in Python's older version like Python 2.x. It takes the
input from the keyboard and return as a string. The Python 2.x doesn't use much in the industry. Let's
understand the following example.
Example -
Output:
Python print() function prints the given object on the screen or other standard output devices.
Unit 4 File Input or Output Text procesing Regular expressions
Signature
Parameters
object(s): It is an object to be printed. The Symbol * indicates that there may be more than one object.
sep='separator' (optional): The objects are separated by sep. The default value of sep is ' '.
file (optional): - The file must be an object with write(string) method. If it is omitted, sys.stdout will be used
which prints objects on the screen.
flush (optional): If True, the stream is forcibly flushed. The default value of flush is False.
Return
Output:
Explanation:
In the above code, only objects parameter is passed to print() function (in all three print statements).
The end parameter '\n' (newline character) is used to display output in the next line, and it is by default. As
we can see, each print statement displays output in the new line.
Unit 4 File Input or Output Text procesing Regular expressions
If the file is saved as sys.stdout, then, the output is printed on the screen.
Here the value of flush is False, so the stream is not forcibly flushed.
The below example use print() with separator and end parameters.
1. x = 7
2. print("x =", x, sep='00000', end='\n\n\n')
3. print("x =", x, sep='0', end='')
Output:
a =000007
a =07
Python File Handling
Introduction:
In this tutorial, we are discussing Python file handling. Python supports the file-handling process. Till now,
we were taking the input from the console and writing it back to the console to interact with the user. Users
can easily handle the files, like read and write the files in Python. In another programming language, the file-
handling process is lengthy and complicated. But we know Python is an easy programming language. So, like
other things, file handling is also effortless and short in Python.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very
large, and only a limited amount of data can be displayed on the console since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
The file handling plays an important role when the data needs to be stored permanently into the file. A file
is a named location on disk to store related information. We can access the stored information (non-volatile)
after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the text or binary format, and
each line of a file is ended with the special character like a comma (,) or a newline character. Python executes
the code line by line. So, it works in one line and then asks the interpreter to start the new line again. This is
a continuous process in Python.
o Open a file
o Read or write - Performing operation
o Close the file
Opening a file
Unit 4 File Input or Output Text procesing Regular expressions
A file operation starts with the file opening. At first, open the File then Python will start the operation. File
opening is done with the open() function in Python. This function will accepts two arguments, file name and
access mode in which the file is accessed. When we use the open() function, that time we must be specified
the mode for which the File is opening. The function returns a file object which can be used to perform
various operations like reading, writing, etc.
Syntax:
SN Access Description
mode
1 r r means to read. So, it opens a file for read-only operation. The file pointer exists at the
beginning. The file is by default open in this mode if no access mode is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists at the beginning of
the file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file pointer exists at the
beginning of the file.
5 w It opens the file to write only. It overwrites the file if previously exists or creates a new
one if no file exists with the same name. The file pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file if it exists previously
or creates a new one if no file exists. The file pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the sense that it overwrites
the previous file if one exists whereas r+ doesn't overwrite the previously written file. It
creates a new file if no file exists. The file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file pointer exists at the
beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the end of the previously
written file if exists any. It creates a new file if no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer exists at the end of the
previously written file. It creates a new file in binary format if no file exists with the same
name.
11 a+ It opens a file to append and read both. The file pointer remains at the end of the file if a
file exists. It creates a new file if no file exists with the same name.
12 ab+ It opens a file to append and read both in binary format. The file pointer remains at the
end of the file.
Unit 4 File Input or Output Text procesing Regular expressions
The files can be accessed using various modes like read, write, or append. The following are the details about
the access mode to open a file.
Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode
and printing its content on the console.
It is a read operation in Python. We open an existing file with the given code and then read it. The code is
given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
<class '_io.TextIOWrapper'>
file is opened successfully
In the above code, we have passed filename as a first argument and opened file in read mode as we
mentioned r as the second argument. The fileptr holds the file object and if the file is opened successfully,
it will execute the print statement
It is a write operation in Python. We open an existing file using the given code and then write on it. The code
is given below -
1. file = open('file.txt','w')
2. file.write("Here we write a command")
3. file.write("Hello users of JAVATPOINT")
4. file.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
1. > Hi
2. ERROR!
3. Traceback (most recent call last):
Unit 4 File Input or Output Text procesing Regular expressions
4. File "<stdin>", line 1, in <module>
5. NameError: name 'Hi' is not defined
The close method used to terminate the program. Once all the operations are done on the file, we must
close it through our Python script using the close() method. Any unwritten information gets destroyed once
the close() method is called on a file object.
We can perform any operation on the file externally using the file system which is the currently opened in
Python; hence it is good practice to close the file once all the operations are done. Earlier use of the close()
method can cause the of destroyed some information that you want to write in your File.
Syntax
1. fileobject.close()
Here we write the program code for the closing method in Python. The code is given below -
After closing the file, we cannot perform any operation in the file. The file needs to be properly closed. If any
exception occurs while performing some operations in the file then the program terminates without closing
the file.
1. try:
2. fileptr = open("file.txt")
3. # perform file operations
4. finally:
5. fileptr.close()
Unit 4 File Input or Output Text procesing Regular expressions
The with statement
The with statement was introduced in python 2.5. The with statement is useful in the case of manipulating
the files. It is used in the scenario where a pair of statements is to be executed with a block of code in
between.
Syntax:
The advantage of using with statement is that it provides the guarantee to close the file regardless of how
the nested block exits.
It is always suggestible to use the with statement in the case of files because, if the break, return, or
exception occurs in the nested block of code then it automatically closes the file, we don't need to write
the close() function. It doesn't let the file to corrupt.
Here we write the program code for with statement in Python. The code is given below -
1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)
Here we write the program code for with statement in Python. The code is given below -
To write some text to a file, we need to open the file using the open method and then we can use the write
method for writing in this File. If we want to open a file that does not exist in our system, it creates a new
one. On the other hand, if the File exists, then erase the past content and add new content to this File. the
It is done by the following access modes.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists.
Unit 4 File Input or Output Text procesing Regular expressions
Program code 1 for Write Method:
Here we write the program code for write method in Python. The code is given below -
1. # open the file.txt in append mode. Create a new file if no such file exists.
2. fileptr = open("file2.txt", "w")
3.
4. # appending the content to the file
5. fileptr.write(''''''''Python is the modern programming language. It is done any kind of program in shortest w
ay.''')
6.
7. # closing the opened the file
8. fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
File2.txt
Python is the modern programming language. It is done any kind of program in shortest way.
We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file and we have written
the content in the file using the write() function
Here we write the program code for write method in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Hello coders
Welcome to javaTpoint
Here we write the program code for write method in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
We can see that the content of the file is modified. We have opened the file in a mode and it appended the
content in the existing file2.txt.
To read a file using the Python script, the Python provides the read() method. The read() method reads a
string from the file. It can read the data in the text as well as a binary format.
Syntax:
1. fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the
count is not specified, then it may read the content of the file until the end.
Here we write the program code for read() method in Python. The code is given below -
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r")
3. #stores all the data of the file into the variable content
4. content = fileptr.read(10)
5. # prints the type of the data stored in the file
6. print(type(content))
7. #prints the content of the file
8. print(content)
9. #closes the opened file
10. fileptr.close()
Unit 4 File Input or Output Text procesing Regular expressions
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
<class 'str'>
Python is
In the above code, we have read the content of file2.txt by using the read() function. We have passed count
value as ten which means it will read the first ten characters from the file.
If we use the following line, then it will print all content of the file. So, it only prints 'Python is'. For read the
whole file contents, the code is given below -
1. content = fileptr.read()
2. print(content)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
We can use read() method when we open the file. Read method is also done through the for loop. We can
read the file using for loop. Consider the following example.
Here we give an example of read file using for loop. The code is given below -
1. #open the file.txt in read mode. causes an error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Here we give an example of read file using for loop. The code is given below -
Output:
Line1: H
Line2: e
Line3: l
Line4: l
Line5: o
Line6:
Line7: C
Line8: o
Line9: d
Line10: e
Line11: r
Line12: s
Line13:
Line14: J
Line15: a
Line16: v
Line17: a
Line18: T
Line19: p
Line20: o
Line21: i
Line22: n
Unit 4 File Input or Output Text procesing Regular expressions
Line23: t
Line24:
Python facilitates to read the file line by line by using a function readline() method. The readline() method
reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can
get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first line of our
file "file2.txt" containing three lines. Consider the following example.
Here we give the example of reading the lines using the readline() function in Python. The code is given
below -
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #stores all the data of the file into the variable content
4. content = fileptr.readline()
5. content1 = fileptr.readline()
6. #prints the content of the file
7. print(content)
8. print(content1)
9. #closes the opened file
10. fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
We called the readline() function two times that's why it read two lines from the file.That means, if you
called readline() function n times in your program, then it read n number of lines from the file. This is the
uses of readline() function in Python. Python provides also the readlines() method which is used for the
reading lines. It returns the list of the lines till the end of file(EOF) is reached.
Example 2:
Here we give the example of reading the lines using the readline() function in Python. The code is given
below -
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
Unit 4 File Input or Output Text procesing Regular expressions
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.readlines()
6.
7. #prints the content of the file
8. print(content)
9.
10. #closes the opened file
11. fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
['Python is the modern day language.\n', 'It makes things so simple.\n', 'Python has easy syntax and user-
friendly interaction.']
Example 3:
Here we give the example of reading the lines using the readline() function in Python. The code is given
below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Line1: Hello
Line2: Coders
Line3: JavaTpoint
x, a and w is the modes of open() function. The uses of these modes are given below -
x: it creates a new file with the specified name. It causes an error a file exists with the same name.
a: It creates a new file with the specified name if no such file exists. It appends the content to the file if the
file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.
Here we give an example for creating a new file in Python. For creates a file, we have to used the open()
method. The code is given below -
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Here we give an example for creating a new file in Python. For creates a file, we have to use the open()
method. Here we use try block for erase the errors. The code is given below -
1. try:
2. with open('file1.txt', 'w') as f:
3. f.write('Here we create a new file')
4. except FileNotFoundError:
5. print("The file is does not exist")
Output:
Unit 4 File Input or Output Text procesing Regular expressions
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Python provides the tell() method which is used to print the byte number at which the file pointer currently
exists. The tell() methods is return the position of read or write pointer in this file. The syntax of tell() method
is given below -
1. fileobject.tell()
Here we give an example for how to find file pointer position in Python. Here we use tell() method and it is
return byte number. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Here we give another example for how to find file pointer position in Python. Here we also use tell() method,
which is return byte number. The code is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
In real-world applications, sometimes we need to change the file pointer location externally since we may
need to read or write the content at various locations.
For this purpose, the Python provides us the seek() method which enables us to modify the file pointer
position externally. That means, using seek() method we can easily change the cursor in the file, from where
we want to read or write a file.
Syntax:
1. <file-ptr>.seek(offset[, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the beginning
of the file is used as the reference position. If it is set to 1, the current position of the file pointer is used as
the reference position. If it is set to 2, the end of the file pointer is used as the reference position.
Here we give the example of how to modifying the pointer position using seek() method in Python. The code
is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Python OS module:
The Python os module enables interaction with the operating system. It comes from the Python standard
utility module. The os module provides a portable way to use the operating system-dependent functionality
in Python. The os module provides the functions that are involved in file processing operations like renaming,
deleting, etc. It provides us the rename() method to rename the specified file to a new name. Using the
rename() method, we can easily rename the existing File. This method has not any return value. The syntax
to use the rename() method is given below.
Syntax:
1. rename(current-name, new-name)
The first argument is the current file name and the second argument is the modified name. We can change
the file name bypassing these two arguments.
Here we give an example of the renaming of the files using rename() method in Python. The current file
name is file2.txt, and the new file name is file3.txt. The code is given below -
1. import os
2.
3. #rename file2.txt to file3.txt
4. os.rename("file2.txt","file3.txt")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Here we give an example of the renaming of the files using rename() method in Python. The current file
name is the source, and the new file name is the destination. The code is given below -
Unit 4 File Input or Output Text procesing Regular expressions
1. import os
2. def main():
3. i=0
4. path="D:/JavaTpoint/"
5. for filename in os.listdir(path):
6. destination = "new" + str(i) + ".png"
7. source = path + filename
8. destination = path + destination
9. os.rename(source, destination)
10. i += 1
11.
12. if __name__ == '__main__':
13. main()
The os module provides the remove() method which is used to remove the specified file.
Syntax:
1. remove(file-name)
1. import os;
2. #deleting the file named file3.txt
3. os.remove("file3.txt")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Here we give an example of removing a file using the remove() method in Python. The file name is file3.txt,
which the remove() method deletes. Print the command "This file is not existed" if the File does not exist.
The code is given below -
1. import os
2. if os.path.exists("file3.txt "):
3. os.remove("file3.txt ")
Unit 4 File Input or Output Text procesing Regular expressions
4. else:
5. print("This file is not existed")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
The mkdir() method is used to create the directories in the current working directory.It creates dictionary in
numeric mode. If the file already presents in the system, then it occurs error, which is known as
FileExistsError in Python. The mkdir() method does not return any kind of value. The syntax to create the
new directory is given below.
Syntax:
Output:
Parameter:
path - A path like object represent a path either bytes or the strings object.
mode - Mode is represented by integer value, which means mode is created. If mode is not created then the
default value will be 0o777. Its use is optional in mkdir() method.
dir_fd - When the specified path is absolute, in that case dir_fd is ignored. Its use is optional in mkdir()
method.
Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is
given below -
1. import os
2.
3. #creating a new directory with the name new
4. os.mkdir("new")
Output:
Unit 4 File Input or Output Text procesing Regular expressions
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is
given below -
1. import os
2. path = '/D:/JavaTpoint'
3. try:
4. os.mkdir(path)
5. except OSError as error:
6. print(error)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
This method returns the current working directory which have absolute value. The getcwd() method returns
the string value which represents the working dictionary in Python. In getcwd() method, do not require any
parameter.
Syntax
1. os.getcwd()
Here we give the example of getcwd() method by which we can create new dictionary in Python. The code
is given below -
1. import os
2. os.getcwd()
Output:
Unit 4 File Input or Output Text procesing Regular expressions
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
'C:\\Users\\BISWADEEP BASAK'
Here we give the example of getcwd() method by which we can create new dictionary in Python. The code
is given below -
1. import os
2. c = os.getcwd()
3. print("The working directory is:", c)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
The chdir() method is used to change the current working directory to a specified directory.The chdir()
method takes a single argument for the new dictionary path. The chdir() method does not return any kind
of value.
Syntax
1. chdir("new-directory")
Here we give the example of chdir() method by which we can change the current working dictionary into
new dictionary in Python. The code is given below -
1. import os
2. # Changing current directory with the new directiory
3. os.chdir("C:\\Users\\BISWADEEP BASAK \\ Documents")
4. #It will display the current working directory
5. os.getcwd()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Unit 4 File Input or Output Text procesing Regular expressions
'C:\\Users\\BISWADEEP BASAK \\Documents'
Here we give another example of chdir() method by which we can change the current working dictionary
into new dictionary in Python. The code is given below -
1. import os
2. os.chdir(r"C:\Users\JavaTpoint")
3. print("Currently working directory is changed")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Deleting directory:
The rmdir() method is used to delete the specified directory. If the directory is not empty then there is occurs
OSError. The rmdir() method does not have and kind of return value.
Syntax
1. os.rmdir(directory name)
Here we give the example of rmdir() method by which we can delete a dictionary in Python. The code is given
below -
1. import os
2. #removing the new directory
3. os.rmdir("directory_name")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Here we give another example of rmdir() method by which we can delete a dictionary in Python. The code is
given below -
1. import os
Unit 4 File Input or Output Text procesing Regular expressions
2. directory = "JavaTpoint"
3. parent = "/D:/User/Documents"
4. path = os.path.join(parent, directory)
5. os.rmdir(path)
6. print("The directory '%s' is successfully removed", %directory)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Output:
Here we give the example of rmdir() method by which we can delete a dictionary in Python. Here we use try
block for handle the error. The code is given below -
1. import os
2. dir = "JavaTpoint"
3. parent = "/D:/User/Documents"
4. path = os.path.join(parent, dir)
5. try:
6. os.rmdir(path)
7. print("The directory '%s' is successfully removed", %dir)
8. except OSError as error:
9. print(error)
10. print("The directory '%s' cannot be removed successfully", %dir)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
In Python, there are the requirements to write the output of a Python script to a file.
The check_call() method of module subprocess is used to execute a Python script and write the output of
that script to a file.
The following example contains two python scripts. The script file1.py executes the script file.py and writes
its output to the text file output.txt.
Unit 4 File Input or Output Text procesing Regular expressions
Program code:
file1.py
1. temperatures=[10,-20,-289,100]
2. def c_to_f(c):
3. if c< -273.15:
4. return "That temperature doesn't make sense!"
5. else:
6. f=c*9/5+32
7. return f
8. for t in temperatures:
9. print(c_to_f(t))
file.py
1. import subprocess
2.
3. with open("output.txt", "wb") as f:
4. subprocess.check_call(["python", "file.py"], stdout=f)
The file object provides the following methods to manipulate the files on various operating systems. Here
we discuss the method and their uses in Python.
Unit 4 File Input or Output Text procesing Regular expressions
SN Method Description
1 file.close() It closes the opened file. The file once closed, it can't be read or write
anymore.
4 File.isatty() It returns true if the file is connected to a TTY device, otherwise returns
false.
7 File.readline([size]) It reads one line from the file and places the file pointer to the beginning
of the new line.
8 File.readlines([sizehint]) It returns a list containing all the lines of the file. It reads the file until the
EOF occurs using readline() function.
9 File.seek(offset[,from) It modifies the position of the file pointer to a specified offset with the
specified reference.
10 File.tell() It returns the current position of the file pointer within the file.
Readlines in Python
o Readlines ( ) is a function that is used in Python to read a particular file line by line in a single go.
o It is very useful in reducing the time complexity while reading a file using the brute force approach
and using loops and different iterations.
o It is a one-line code and simple function, which much better than using many loops for just reading
a file.
o In C programming, reading a file is quite a tough task, but it is very easy to implement due to this
readlines ( ) function in Python.
o readlines ( ) function reads only one complete line from the given file; after reading, it returns the
whole line containing all elements in the form of a list.
o If we want to open the file in normal read mode, readline ( ) function will return us the string.
o If we want to open the file in binary mode, then readline ( ) function will return you a binary object.
Unit 4 File Input or Output Text procesing Regular expressions
o It is also very beneficial to appends a newline ( " \n " ) at the end of the line.
o This readlines ( ) function is mostly suitable for small-sized files, containing fewer data to read the
whole file within less time easily.
o It first reads the file's content to a memory in a single go and then separates them into various lines.
With the help of the strip ( ) function, we can iterate over the whole list, which has been generated
by the readline ( ) function, and by using the strip ( ) function, we can strip the newline ' \n ' character.
Python programming language has various inbuilt functions for writing, creating, and reading files. Two
types of files are handled in Python, which is normal text files, and the second one is binary files mainly
written in binary language that is 0's and 1's.
1. Text files: These files contain the data in the form of text, which is terminated with a special character
called EOL ( end of a line ), the new line character ( ' \n ' ) in Python by default.
2. Binary files: These types of files contain the data in the form of binary sequences, consisting of mainly
0's and 1's.
Opening a file: Opening a file is done using the open ( ) function; while using this function, we must pass the
file name and Access mode as an argument.
1. Read-only ( r ): It is used to read the data from the file. It is positioning the beginning of the file. If
the file mentioned is not present, it will generate an input/output error. Read-only is the default
mode of opening the file; while using this mode, we cannot edit the data of the file or cannot write
it into the file.
2. Write only ( ' w ' ): It is used to write the data into the file, positioning the beginning of the file. If the
file mentioned is not present, then it will generate an input/output error. While using this mode, we
cannot read the data from the file.
3. Read and Write ( ' r+ ' ): This mode is used for writing and reading the data from the file. If we
compare it with the previous mode, we can distinguish that we cannot write into the file in the read-
only mode, but we can read and write into the file in this mode.
For example, if we have a file named hello.txt and we want to open it in write mode, then we can use it as:
Closing a file: Close function is used to free up the memory space required by the file; this method is when
there is no longer need for the file or if we want to close the entire file and want to open the file in a different
mode. It is performed by using the close ( ) function, and inside this function, we are not required to pass
any argument; this function can be accessed using the file name and supplied by the dot close function.
Unit 4 File Input or Output Text procesing Regular expressions
For example, if we have a file named hello.txt and we want to open it in write mode, then we can use it as:
Writing in a file: As the name suggests, we can easily predict what we are required to write in a file in this
method. There are two ways to write in a file:
1. Write ( ): In this function, we must pass a single argument, the string we want to insert into the file.
For example, if we have a file named hello.txt and we want to open it in write mode, then we can use
it as:
File1 = open ( " hello.txt " , " w " )
File1.write ( str )
Here, str is the string that we want to insert into the file.
2. Writelines ( ): In this function, we must pass an array or a list consisting of multiple strings. It is used
to insert multiple various strings into the file at a single time.
For example, if we have a file named hello.txt and we want to open it in write mode, then we can use
it as:
File1 = open ( " hello.txt " , " w " )
File1.writelines( S ) for S = [ str1 , str2 , str3 ]
Reading from a file: Similarly, in this, we can predict that what we have to do in this; even in this tutorial,
we are going to read among one of the reading methods in detail. In this method, we need to read the data
from the particular file. There are three ways for reading the data from the file:
1. Read ( ): Returns the read bytes in the form of a string. Reads n bytes; if n is not specified, then reads
the entire file.
2. Readline ( ): Reads a line of the file and returns in the form of a string. For specified n, reads at most
n bytes. readline ( ) function does not read more than one line at a time; even if n exceeds, it reads
only one line. Readline ( ) function reads a line of the file and returns it in the string. It takes an integer
value n as a parameter to read the number of characters read at a time. Readline ( ) method is very
efficient in reading the data from a very large file because it fetches the data line by line and returns
and prints on the screen. Readline ( ) returns the next line of the file, which contains a newline
character in the end. Also, if the end of the file is reached, it will return an empty string.
3. readlines ( ): Reads all the lines and returns them as a string element in a list. Readlines ( ) is used to
read all the lines at a single go and then return them as a string element in a list. This function can be
used for small files, as it reads the whole file content to the memory, then splits it into separate lines.
Using the strip () function, we can iterate over the list and strip the newline ' \n ' character using the
strip ( ) function.
Now let us understand the concept of reading a file in detail with the help of an example:
1. # Python program to implement the file concept using readlines ( ) for reading a file
2. Fruits = ["Apple\n", "Orange\n", "Banana\n"]
3. # writing to file
4. file = open('hello.txt', 'w')
5. file.writelines(Fruits) # writelines is used to write the data into the file in
# the form of a list, by inserting multiple values at the same time,
6. # here, we are taking the hello.txt file
7. file.close() # This instruction is used to close the file, i.e., hello.txt
8. # Using readlines()
9. file = open('hello.txt', 'r')
10. Statements = file.readlines()
11. count = 0
12. # Strips the newline character
13. for line in Statements: # Using for loop to print the data of the file
14. count = count + 1
15. print("Statement{}: {}".format(count, line.strip()))
Example 2:
1. # Python program to implement the file concept using readline() for reading a file
2. Fruit = [ "Apple\n" , "Graphs\n" , "Mango\n" , "Orange\n" , "Kiwi\n" ]
3. # Writing to a file
4. file1 = open('new.txt', 'w')
5. file1.writelines((Fruit)) # writelines is used to write the data into the file in
# the form of list, by inserting multiple values at a same time,
6. # here we are taking new.txt file
7.
8. file1.close() # This instruction is used to close the file, i.e., hello.txt
Unit 4 File Input or Output Text procesing Regular expressions
9.
10. # Using readline()
11. file1 = open('new.txt', 'r')
12. count = 0
13. while True:
14. count = count + 1
15. # Get next line from file
16. s = file1.readline()
17.
18. # if line is empty
19. # end of file is reached
20. if not s:
21. break
22. print("Statement{}: {}".format(count, s.strip()))
23. file1.close()
Example 3:
In this method, we are not using the readline ( ) function and not even using the readlines ( ) function, as we
have already seen the use of both of the functions in the above examples; in this method, we will use the
for loop for printing the data of the file. We will iterate the objects of the file and read a file line by line,
although we are using some python predefined built-in functions. Using these built-in Python functions, we
can easily iterate over the file object implicitly using a for loop, in combination with using the iterable object.
1. ## Python program to implement the file concept using the simple for loop for reading a file
2. Fruits = ["Apple \n", " Orange \n", "Banana \n", "Mango\n", "Pineapple\n" ]
3. # Writing to file
4. file2 = open('file2.txt', 'w')
5. file2.writelines(Fruits) # writelines is used to write the data into the file in
Unit 4 File Input or Output Text procesing Regular expressions
6. # the form of list, by inserting multiple values at a same time,
7. # here we are taking file2.txt file
8. file2.close() # This instruction is used to close the file, i.e., hello.txt
9.
10. # Opening file
11. file2 = open('file2.txt', 'r')
12. count = 0
13. # Using for loop
14. print("Using for loop")
15. for line in file2:
16. count = count + 1
17. print("Statement{}: {}".format(count, line.strip()))
18. # Closing files
19. file2.close()
Example 4:
If we notice the above 3 examples, we can easily observe that every time whenever the file needs to be
open, then it is required to be closed; if we do not close the file, then it will create several bugs in the program
because many changes not done in the file or come into effect until we do not close the file.
So, to overcome this problem, we will use the ' with ' statement, which is mainly used in exception handling
in Python, to make the code clearer and much more readable. Here, in this example, you can easily observe
that we are not using the file.close ( ) function, again and again, to prevent the file, using it can be
automatically done with the statement. Hence it reduces lines of code and makes the program faster to run
and implement more efficiently.
1. # Python program to implement the file concept using with statement for reading a file
Unit 4 File Input or Output Text procesing Regular expressions
2. Veges = ["Potato\n", "Onion\n", "Tomamto\n"]
3. # Writing to file
4. with open("file3.txt", "w") as file:
5. file.writelines(Veges) # writelines is used to write the data into the file in
6. # the form of list, by inserting multiple values at a same time,
7. # here we are taking file3.txt file
8. # using readlines()
9. count = 0
10. print("Using readlines()")
11. with open("file3.txt") as file:
12. Statements = file.readlines()
13. for line in Statements:
14. count = count + 1
15. print("Satement{}: {}".format(count, line.strip()))
16. # Using readline()
17. count = 0
18. print("\nUsing readline()")
19. with open("file3.txt") as file:
20. while True:
21. count = count + 1
22. line = file.readline()
23. if not line:
24. break
25. print("Statement{}: {}".format(count, line.strip()))
26. # Using for loop
27. count = 0
28. print("\n Using for loop")
29. with open("file3.txt") as file:
30. for line in file:
31. count = count + 1
32. print("Statements{}: {}".format(count, line.strip()))
The python open() function opens the file and returns a corresponding file object.
Signature
Parameters
file: It is a path like object giving the pathname of the file to be opened.
mode (optional): It specifies the mode in which the file is opened. If not provided, it defaults to 'r' which
means open for reading in text mode.
closefd (optional): It must be True (default) if given otherwise an exception will be raised.
Return
It returns a file object which can used to read, write and modify file.
Output:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
Output:
Explanation: In the above example, we specify different modes('r', 'w', 'a') for opening a file.
The close() method in Python is used to close an open file. When you are done working with a file, it's good
practice to close it using the close() method. Closing a file is important because it releases system
resources associated with the file, and it ensures that any changes made to the file are saved.
In this example, the open() function is used to open the file in write mode, content is written to the file,
and then the close() method is called to close the file.
It's often recommended to use the with statement when working with files. The with statement ensures
that the file is properly closed, even if an exception occurs during the execution of the block. Here's an
example using the with statement:
Using the with statement is a safer and more concise way to work with files in Python because it takes care
of closing the file for you.
The tell() method in Python is used to get the current position of the file cursor within the file. The file
cursor represents the location in the file where the next read or write operation will occur. The position is
given as an offset, in bytes, from the beginning of the file.
In this example, after reading the first 10 characters from the file, the tell() method is used to retrieve the
current position of the file cursor. This position is then printed to the console.
Keep in mind that the position is represented in bytes, so it indicates the number of bytes from the
beginning of the file where the next operation will occur. If you perform a read or write operation, the file
cursor will be moved accordingly.
Unit 4 File Input or Output Text procesing Regular expressions
You can use the seek(offset, whence) method to move the file cursor to a specific position within the file.
The offset parameter specifies the number of bytes to move, and whence specifies the reference point for
the offset. The whence parameter can take the values 0 (absolute file positioning), 1 (seek relative to the
current position), or 2 (seek relative to the file's end).
The seek(offset, whence) method in Python is used to change the current file position within an open file.
This method takes two parameters:
1. offset: This is the number of bytes to move the file pointer. The offset can be positive or negative. Positive
values move the pointer forward, and negative values move it backward.
2. whence: This parameter specifies the reference point for the offset. It can take one of the following values:
0 (default): The offset is relative to the beginning of the file.
1: The offset is relative to the current file position.
2: The offset is relative to the end of the file.
# Move the file cursor 10 bytes forward from the current position
file.seek(10, 1)
# Move the file cursor 5 bytes back from the end of the file
file.seek(-5, 2)
# Move the file cursor to the beginning and read the updated content
file.seek(0, 0)
content_after = file.read()
In this example, the seek() method is used to move the file cursor to different positions within the file, and
subsequent read and write operations are performed at those positions. The seek(0, 0) is used to move the
cursor to the beginning of the file, and seek(-5, 2) is used to move it 5 bytes back from the end. The
resulting content of the file is then printed.
Unit 4 File Input or Output Text procesing Regular expressions
The flush() method in Python is used to flush the internal buffer of a file. When you write data to a file, it is
often buffered, meaning that the data is not immediately written to the file on disk but is instead stored in
an internal buffer. The flush() method forces the contents of the buffer to be written to the file.
In this example, after writing "Hello, World!" to the file, the flush() method is called. This is useful in
situations where you want to ensure that the data is physically written to the file before continuing, for
example, if you need to check the file contents from another process.
Keep in mind that in many cases, the close() method also implicitly flushes the buffer before closing the
file. Therefore, if you are using a with statement to manage the file (which automatically closes the file
when exiting the block), you may not need to explicitly call flush() unless you have specific requirements
related to buffering and data consistency.
The fileno() method in Python is used to get the file descriptor associated with an open file. A file
descriptor is a low-level integer representing an open file in the operating system. The file descriptor is an
essential concept in systems programming, and it allows interaction with the underlying operating system's
I/O functions.
In this example, the open() function is used to open a file, and the fileno() method is then called on the file
object to retrieve the associated file descriptor. The file descriptor can be useful in certain situations, such
as when interacting with operating system-level functions or libraries that require a file descriptor as an
input.
It's important to note that the use of file descriptors is generally low-level and not required for typical file
I/O operations in Python. Most developers can perform file operations using higher-level Python file
objects without needing to directly manipulate file descriptors. The fileno() method is more commonly
used in scenarios where low-level interactions with the operating system are necessary.
The isatty() method in Python is used to check whether the file is associated with a terminal device (TTY). A
TTY is a device representing the terminal or console, and it's often used to determine if a script or program
is being run interactively in a terminal environment.
Unit 4 File Input or Output Text procesing Regular expressions
Here's a simple example:
if is_terminal:
print("This script is being run interactively in a terminal.")
else:
print("This script is not being run in a terminal.")
In this example, the isatty() method is called on the file object to check if the file is associated with a
terminal. The result is a Boolean value (True if it's a terminal, False otherwise).
This method is commonly used to customize the behavior of scripts based on whether they are run
interactively in a terminal or as part of a non-interactive process. For example, a script might provide
different output formats or prompts when run interactively compared to when it's part of an automated
process.
Keep in mind that this method is specific to file objects, so it's often used with standard input (sys.stdin) or
other file-like objects associated with input streams.
The next() function in Python is used to retrieve the next item from an iterator by calling its __next__()
method. It takes an iterator as an argument and returns the next element in the sequence.
# Create an iterator
next_element = next(my_iterator)
In this example, iter([1, 2, 3, 4, 5]) creates an iterator from the list, and next(my_iterator) retrieves the
first element from the iterator, which is 1.
The next() function can also take a second argument, which is a default value to be returned if the iterator
is exhausted. If the iterator has no more elements, and a default value is not provided, the function raises
the StopIteration exception.
In this example, the iterator has only three elements, so the third call to next() with a default value is used,
and it returns 'Default3'.
It's important to note that the next() function is often used implicitly when working with iterators in a
loop. For example, a for loop automatically calls next() for each iteration until the iterator is exhausted.
Unit 5 : Frameworks
The Model-View-Controller (MVC) is a design pattern widely used in software engineering, including the
development of web applications. It provides a structured way to organize code and separate concerns,
making it easier to maintain and scale applications. Here's an overview of the three components in the
MVC pattern:
1. Model:
- The Model represents the application's data and business logic. It is responsible for maintaining the
state of the application, processing data, and responding to requests from the Controller.
- In a web application, the Model could interact with a database, handle data validation, and perform
other operations that are not directly related to the user interface.
2. View:
- The View is responsible for presenting the data to the user and receiving user input. It displays
information from the Model and sends user actions (such as button clicks or form submissions) to the
Controller.
- In a web application, the View is often associated with the user interface, including HTML templates,
stylesheets, and client-side scripts.
3. Controller:
- The Controller acts as an intermediary between the Model and the View. It receives user input from the
View, processes it, and updates the Model accordingly. It also updates the View to reflect any changes in
the Model.
- In a web application, the Controller is often associated with server-side logic, handling HTTP requests,
and managing the flow of data between the Model and the View.
-Modularity:Each component (Model, View, Controller) has a distinct role and can be developed and
modified independently, promoting code reusability and maintainability.
- Separation of Concerns: The pattern separates the concerns of managing data, user interface, and
application flow, making the codebase more organized and easier to understand.
- Scalability: The modular structure allows for easier scalability of the application. For example, you can
update the View without affecting the underlying data processing logic.
Unit 5 : Frameworks
Popular web frameworks that implement the MVC pattern (or variations of it) include:
- Django (Python): A high-level web framework that follows the MVC pattern (or more precisely, the MTV
pattern - Model, Template, View).
- Ruby on Rails (Ruby): A web application framework that follows the convention over configuration (CoC)
and don't repeat yourself (DRY) principles, implementing the MVC pattern.
- Spring MVC (Java): A framework for building Java-based enterprise applications, providing support for the
development of web applications following the MVC pattern.
-Express (Node.js): A minimal and flexible Node.js web application framework that can be used to build
web applications following the MVC pattern.
These frameworks provide tools and conventions to help developers implement the MVC pattern in their
applications, making it easier to create robust and maintainable software.
Django is a high-level, open-source web framework for building web applications using the Python
programming language. It follows the Model-View-Controller (MVC) architectural pattern, although in
Django's case, it is more accurately described as following the Model-View-Template (MVT) pattern, where
the "Template" represents the View in traditional MVC.
Here are some key features and reasons why you might choose to use Django:
1. Batteries-Included Philosophy:
- Django follows a "batteries-included" philosophy, providing a wide range of built-in features and tools.
This includes an ORM (Object-Relational Mapping) for database interactions, an admin interface,
authentication, and more. This reduces the need to find and integrate third-party packages for common
functionalities.
4. Security Features:
- Django takes security seriously and includes various features to help developers build secure
applications. This includes protection against common web vulnerabilities such as CSRF (Cross-Site Request
Forgery), SQL injection, and more.
6. Template System:
- Django comes with a template system that allows developers to separate the HTML presentation from
the Python code. Templates are used for rendering dynamic content and are designed to be easy to read
and write.
8. Scalability:
- Django is designed to scale. It can handle the development of small projects and scale up to handle
large and complex applications. It follows best practices for code organization and modularity, making it
easier to maintain and extend as the project grows.
9. Versatility:
- Django is not limited to web applications. With its modular design, you can use specific components
(e.g., the ORM) in non-web contexts, making it versatile for a variety of projects.
Unit 5 : Frameworks
10. Django REST framework:
- For building APIs, Django integrates seamlessly with Django REST framework, an extension to Django
that simplifies the creation of RESTful APIs.
In summary, Django is a robust, versatile, and well-documented web framework that is suitable for a wide
range of web development projects. It provides a solid foundation for building secure, scalable, and
maintainable web applications, and its "batteries-included" approach can significantly speed up the
development process.
In Django, you can handle chains with filters using the Django QuerySet API. The QuerySet API provides a
powerful and expressive way to query your database. You can chain multiple filters and other operations
to create complex queries.
Assuming you have a Django model named `MyModel` with fields like `field1`, `field2`, etc., here's an
example of how you can create a chain of filters:
```python
from myapp.models import MyModel
# Apply filters
queryset = queryset.filter(field1='value1')
queryset = queryset.filter(field2__gte=10) # Double underscore for lookups
# Now 'results' contains instances of MyModel that satisfy all the applied filters
Unit 5 : Frameworks
In this example:
- `MyModel.objects.all()` creates an initial queryset that includes all records in the `MyModel` table.
- `queryset.filter(...)` adds filters to the queryset. You can chain multiple filters together. Note the use of
double underscores (`__`) for lookups, like `__gte` (greater than or equal to) and `__icontains` (case-
insensitive containment).
This is a basic example, and you can create much more complex chains of filters based on your specific
requirements.
```python
from myapp.models import MyModel
In this example, we are applying multiple filters, including one with the `exclude()` method to exclude
records where `field3` is null, and another using `__in` to filter by a list of options.
Remember to execute the query (e.g., using `all()`, `get()`, or other queryset methods) to retrieve the
actual results from the database.
Unit 5 : Frameworks
Django's QuerySet API provides a wide range of lookup types and methods for filtering, and you can refer
to the official Django documentation on queries for more details: [Django
Queries](https://docs.djangoproject.com/en/3.2/topics/db/queries/).
In Django, you can insert static files (such as stylesheets, JavaScript files, or images) into your templates
using the `{% static %}` template tag. This tag is part of the Django template engine and is used to generate
URLs for static files.
Here's a step-by-step guide on how to insert static files into your templates:
Ensure that you have configured static files properly in your Django project. In your `settings.py` file, you
should have the following configurations:
```python
# settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
This assumes that you have a `static` directory in your project directory where you'll store your static
files.
body {
background-color: #f0f0f0;
}
```
```html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Django App</title>
```html
<!-- templates/index.html -->
{% load static %}
<!DOCTYPE html>
<html lang="en">
<!-- ... rest of the template ... -->
```
This tag is necessary for using the `{% static %}` tag.
```python
# myproject/urls.py
urlpatterns = [
# ... your other URL patterns ...
]
Unit 5 : Frameworks
This allows Django to serve static files when you are running the development server.
Once you've followed these steps, your static files should be included correctly in your templates, and you
can see the styles or other assets applied when you load the corresponding pages.