You are on page 1of 166

Semester-IV

SSE-256 PYTHON PROGRAMMING(SEC)

Getting Started with Python

Introduction to Python

Python is a widely used general-purpose, object oriented, high level


programming language. It was created by Guido van Rossum in 1991 and
further developed by the Python Software Foundation. It was designed with an
emphasis on code readability, and its syntax allows programmers to express
their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate
systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite
different.

It is used for:

 web development (server-side),


 software development,

 mathematics,

 system scripting.

What is High-Level-Programming Language?

High-level programming languages mean that languages of writing


computer instructions in a way that is easily understandable and close
to human language. High-level languages are created by developers so
that programmers don’t need to know highly difficult low
level/machine language. Programmers can easily learn high-level
languages as it is very close to human language.
BASIC, C/C++ and Java are popular examples of high-level languages.
Assembly Language:

This is a programming language that is a little more understandable


but still requires that you understand how the microprocessor, the
heart of the computer, works. Assembly language was a big step
forward. In order for the computer to understand the assembly
language program however, it must be translated into binary code by a
special program called an Assembler.

General Purpose Programming Language:-


"The programming languages which can fulfill the needs of a wide variety of domains
are called as general purpose programming languages."

These languages can fulfill more than one purpose, for example they can be apt for
mathematical calculations, research work and application development at the same
time.

For example
o Java can be used for developing interactive webpages as well as making games.
o C++ can be used for writing applications as well as developing system programs.
o Python, Perl, Ruby can be used for web programming as well as development of desktop
applications.
A list of various general purpose programming languages:
o Java
o Ruby
o Python
o C
o C++
o D
o Dart
o C#

What is an IDE?
An IDE, or Integrated Development Environment, enables programmers to
consolidate the different aspects of writing a computer program.

IDEs increase programmer productivity by combining common activities of


writing software into a single application: editing source code, building
executables, and debugging.

Editing Source Code


Writing code is an important part of programming. We start with a blank file,
write a few lines of code, and a program is born! IDEs facilitate this process
with features like syntax highlighting and autocomplete.

Syntax Highlighting
An IDE that knows the syntax of your language can provide visual cues.
Keywords, words that have special meaning like class in Java, are highlighted
with different colors.

Autocomplete
When the IDE knows your programming language, it can anticipate what
you’re going to type next!
We’ve seen statements with System.out.println() quite a bit so far. In an IDE, we
might see System as an autocomplete option after only typing Sy. This saves
keystrokes so the programmer can focus on logic in their code.

Python - IDLE
IDLE (Integrated Development and Learning Environment) is an
integrated development environment (IDE) for Python. The Python
installer for Windows contains the IDLE module by default.

IDLE can be used to execute a single statement just like Python


Shell and also to create, modify, and execute Python scripts. IDLE
provides a fully-featured text editor to create Python script that
includes features like syntax highlighting, autocompletion, and smart
indent. It also has a debugger with stepping and breakpoints
features.

To start an IDLE interactive shell, search for the IDLE icon in the
start menu and double click on it.
Python IDLE

This will open IDLE, where you can write and execute the Python
scripts, as shown below.
Python IDLE

You can execute Python statements same as in Python Shell as


shown below.
Python IDLE

To execute a Python script, create a new file by selecting File -> New
File from the menu.
Enter multiple statements and save the file with extension .py using
File -> Save. For example, save the following code as hello.py.
Python Script in IDLE

Now, press F5 to run the script in the editor window. The IDLE shell
will show the output.

Python Script Execution Result in IDLE


Thus, it is easy to write, test and run Python scripts in IDLE.

IDLE is Python’s Integrated Development and Learning Environment.

IDLE has the following features:

 coded in 100% pure Python, using the tkinter GUI toolkit


 cross-platform: works mostly the same on Windows, Unix, and macOS
 Python shell window (interactive interpreter) with colorizing of code input, output,
and error messages
 multi-window text editor with multiple undo, Python colorizing, smart indent, call
tips, auto completion, and other features
 search within any window, replace within editor windows, and search through
multiple files (grep)
 debugger with persistent breakpoints, stepping, and viewing of global and local
namespaces
 configuration, browsers, and other dialogs

What is a python interpreter?


A compiler is essentially a translator. It will take human language (also known as a source
language) and convert it into machine language (object language). The interpreter uses the
source language and converts the program through each line of data. Then, the computer will
be able to complete any command given through the program.

How Do Compilers and Interpreters Work?


Python is interactive and a compiler reads the entire program on the initial standard
input. When it reads the program, it generates the object code instantly. The process is
fast and effective; whereas the interpreter does the opposite. It will read each line
and doesn’t create an immediate object code like the compiler does. Compilation occurs
instantly, instead. Compilation with the compiler occurs before the program is executed.

What Is A Python Interpreter?


What is python interpreter? People often struggle to understand what is it or what it
does, but, it’s incredibly easy to get-to-grips with. Python uses both a compiler and
interpreter in its programs. Interpreter python is widely used throughout the computer
programming and source coding industries.
Python interpreter takes an interactive command and executes it. All lines of source
code are completed (translated) one line at a time. Compilation of the source codes
occur through the translation process.

A python compiler does a lot less work than the interpreter, however. Codes are
compiled in to a byte code which means a compiler isn’t always necessary.
The interpreter will read the python code and then look at each line of code created to
verify the instructions and ensure they’re formatted correctly. If there are any errors
within the software, they will appear as each line is translated. The interpreter can
execute the codes immediately through the standard input.

Essentially, the python interpreter reads and executes codes instantly and does so in
interactive mode. It can also be script, source or pre-compiled code. Installing python is
a simple process and takes only a few minutes. If you want to install python, follow the
instructions given.

The Processes Are Different


An interpreter in python offers a one-step process. The code is compiled and
executed at the same time, whereas the compiler splits the process into two parts.
Firstly, the compiler will take the code it’s given and translate it. Secondly, the code is
put into the target program and executed. While the differences between python
compiler and interpreter are minor, the processing time can vary considerably. Standard
input will also differ.

Remember, the interpreter can be far quicker than the compiler because it translates
the code and executes the program at the same time. A compiler requires an additional
step to complete the process. Also, compilers are used in program languages like C+
and are generally the same no matter which version number of python is being used.
Interpreter uses interactive mode and python C languages. C command is vastly
popular with python and you can easily select a file name to bring up the program.

More Memory Required


Compilers deal with object code and as a result, it occurs in greater volumes. That
means compiler uses more memory within a program and hardware than
interpreter. Interpreter utilizes less memory and makes things more compact, in a way.
While it might seem fairly minor now, it could have a major impact later. Depending on
what you’re aiming to do, you may need a lot of memory so it will make a difference.

However, compilers are faster than interpreters. Since a compiler opts to translate the
entire program at once (rather than line-by-line like interpreter), it makes the process
quicker. First Python interpreters can be fairly quick, but again, the compiler translates
the codes at one time so it is faster than the interpreters. It may impact web
development and computer programming later also. Sys.argv is another program
widely used in python and sys.argv is a popular choice. You could use the command
line to open this file up.

Handling Errors during Translation


The python interpreter will run the translation of the source code and if an error is
spotted, it will stop the error from being translated. It will also remove the error and the
translation will continue on so that it doesn’t affect runtime. The interpreter will display
each error it locates – one at a time – and can make them easier to spot than with the
compiler.

When the compiler picks up an error, it will stop the translation of the code and will take
steps to remove the error. However, once it does, the coding is translated again. The
compiler shows all of the errors found at the same time and it may make it difficult to
know where the errors took place. There are slight differences for translation, but can
make a huge difference later with python online. The interactive mode is easy to use
and runs automatically, use the primary prompt to select a file to open.

How to Find and Run a Python Script


Interpreter
Searching for first Python is incredibly easy to do. To find the Python interpreter,
you’ll need to locate your file manager and search for the appropriate version of the
software. You can locate the Python interpreter Windows easily if you’re using a
Windows operating system. Go to your Windows page by pressing the Windows button
located on your keyboard. Once you’ve done so, search for python.exe or Python C on
your computer. You should be able to see where it’s installed and whichever version
you have, click on a script name, type a command line and run the file. Locate the
primary prompt, choose a file name and open it.

To run Python scripts, select a script name like sys.argv, by using the Python
command. You need to open the command line and type the path to the script file, so
input a script name. Choose the relevant script (like sys.argv) and that’s it.
The interactive mode can be easy to use. You can repeat the process again with a
different command line if you want to use different scripts. Or use primary prompt to
choose a new script or file name.

Conclusion
Understanding what is interpreter in python is easy. An interpreter for python is an
important concept for web development and computer programming. A Python
interpreter and compiler are quite similar to one another. Essentially, they both do the
same job, but in very different ways. Each has a slightly different procedure when
generating a source code, but the end result remains the same.

Python interpreter uses a line-by-line approach whereas the compiler opts for a whole
program approach. They both have their advantages and disadvantages but they make
the overall process quicker and easier for all. Even beginners can understand sys.argv
and C Command by using Python.

The Interpreter and Its Environment


Source Code Encoding
By default, Python source files are treated as encoded in UTF-8. In that encoding,
characters of most languages in the world can be used simultaneously in string literals,
identifiers and comments — although the standard library only uses ASCII characters
for identifiers, a convention that any portable code should follow. To display all these
characters properly, your editor must recognize that the file is UTF-8, and it must use a
font that supports all the characters in the file.

To declare an encoding other than the default one, a special comment line should be
added as the first line of the file. The syntax is as follows:

# -*- coding: encoding -*-

where encoding is one of the valid codecs supported by Python.

For example, to declare that Windows-1252 encoding is to be used, the first line of your
source code file should be:

# -*- coding: cp1252 -*-

One exception to the first line rule is when the source code starts with a UNIX
“shebang” line. In this case, the encoding declaration should be added as the second
line of the file. For example:

#!/usr/bin/env python3
# -*- coding: cp1252 -*-

Why Python Programming?


Every Programming language serves some purpose or use-case according to
a domain. for eg, Javascript is the most popular language amongst web
developers as it gives the developer the power to handle applications via
different frameworks like react, vue, angular which are used to build beautiful
User Interfaces. Similarly, they have pros and cons at the same time. so if we
consider python it is general-purpose which means it is widely used in every
domain the reason is it’s very simple to understand, scalable because of
which the speed of development is so fast. Now you get the idea why besides
learning python it doesn’t require any programming background so that’s why
it’s popular amongst developers as well. Python has simpler syntax similar to
the English language and also the syntax allows developers to write programs
with fewer lines of code. Since it is open-source there are many libraries
available that make developers’ jobs easy ultimately results in high
productivity. They can easily focus on business logic and Its demanding skills
in the digital era where information is available in large data sets.

IEEE spectrum list of top programming language 2021. The list of


programming languages is based on popularity.
I
EEE list for top programming language

Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
 Python has a simple syntax similar to the English language.

 Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.

 Python runs on an interpreter system, meaning that code can be


executed as soon as it is written. This means that prototyping can be very
quick.

 Python can be treated in a procedural way, an object-oriented way or a


functional way.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.

 Python can connect to database systems. It can also read and modify
files.
 Python can be used to handle big data and perform complex
mathematics.

 Python can be used for rapid prototyping, or for production-ready


software development.

Python Syntax compared to other programming languages


 Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.

 Python relies on indentation, using whitespace, to define scope; such as


the scope of loops, functions and classes. Other programming languages
often use curly-brackets for this purpose.

Real-World Examples:
1) NASA (National Aeronautics and Space Agency): One of Nasa’s Shuttle
Support Contractors, United Space Alliance developed a Workflow
Automation System (WAS) which is fast. Internal Resources Within critical
project stated that:

“Python allows us to tackle the complexity of programs like the WAS without
getting bogged down in the language”.

Nasa also published a website (https://code.nasa.gov/) where there are 400


open source projects which use python.

2) Netflix: There are various projects in Netflix which use python as follow:

 Central Alert Gateway


 Chaos Gorilla
 Security Monkey
 Chronos
Amongst all projects, Regional failover is the project they have as the system
decreases outage time from 45 minutes to 7 minutes with no additional cost.

3) Instagram: Instagram also uses python extensively. They have built a


photo-sharing social platform using Django which is a web framework for
python. Also, they are able to successfully upgrade their framework without
any technical challenges.

Applications of Python Programming:


1) Web Development: Python offers different frameworks for web
development like Django, Pyramid, Flask. This framework is known for
security, flexibility, scalability.

2) Game Development: PySoy and PyGame are two python libraries that are
used for game development

3) Artificial Intelligence and Machine Learning: There is a large number of


open-source libraries which can be used while developing AI/ML applications.

4) Desktop GUI: Desktop GUI offers many toolkits and frameworks using
which we can build desktop applications.PyQt, PyGtk, PyGUI are some of the
GUI frameworks.

Python Language advantages and applications


Python is a high-level, interpreted, and general-purpose dynamic programming
language that focuses on code readability. It has fewer steps when compared to
Java and C. It was founded in 1991 by developer Guido Van Rossum. Python
ranks among the most popular and fastest-growing languages in the world.
Python is a powerful, flexible, and easy-to-use language. In addition, the
community is very active there. It is used in many organizations as it supports
multiple programming paradigms. It also performs automatic memory
management.

Advantages :
1. Presence of third-party modules
2. Extensive support libraries(NumPy for numerical calculations, Pandas for
data analytics etc)
3. Open source and community development
4. Versatile, Easy to read, learn and write
5. User-friendly data structures
6. High-level language
7. Dynamically typed language(No need to mention data type based on the
value assigned, it takes data type)
8. Object-oriented language
9. Portable and Interactive
10. Ideal for prototypes – provide more functionality with less coding
11. Highly Efficient(Python’s clean object-oriented design provides enhanced
process control, and the language is equipped with excellent text processing
and integration capabilities, as well as its own unit testing framework, which
makes it more efficient.)
12. (IoT)Internet of Things Opportunities
13. Interpreted Language
14. Portable across Operating systems

Applications :
1. GUI based desktop applications
2. Graphic design, image processing applications, Games, and Scientific/
computational Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10. Software Development

Organizations using Python :


1. Google(Components of Google spider and Search Engine)
2. Yahoo(Maps)
3. YouTube
4. Mozilla
5. Dropbox
6. Microsoft
7. Cisco
8. Spotify
9. Quora

How To Install Python 3 on


Windows 10
Prerequisites
 A system running Windows 10 with admin privileges
 Command Prompt (comes with Windows by default)

 A Remote Desktop Connection app (use if you are installing Python on a remote Windows
server)

Python 3 Installation on Windows


Step 1: Select Version of Python to Install
The installation procedure involves downloading the official Python .exe installer and running it
on your system.

The version you need depends on what you want to do in Python. For example, if you are
working on a project coded in Python version 2.6, you probably need that version. If you are
starting a project from scratch, you have the freedom to choose.

If you are learning to code in Python, we recommend you download both the latest version of
Python 2 and 3. Working with Python 2 enables you to work on older projects or test new
projects for backward compatibility.

Step 2: Download Python Executable Installer


1. Open your web browser and navigate to the Downloads for Windows section of the official
Python website.
2. Search for your desired version of Python. At the time of publishing this article, the latest Python
3 release is version 3.7.3, while the latest Python 2 release is version 2.7.16.

3. Select a link to download either the Windows x86-64 executable installer or Windows x86
executable installer. The download is approximately 25MB.
Step 3: Run Executable Installer
1. Run the Python Installer once downloaded. (In this example, we have downloaded Python
3.7.3.)

2. Make sure you select the Install launcher for all users and Add Python 3.7 to
PATH checkboxes. The latter places the interpreter in the execution path. For older versions of
Python that do not support the Add Python to Path checkbox, see Step 6.

3. Select Install Now – the recommended installation options.


For all recent versions of Python, the recommended installation options include Pip and IDLE.
Older versions might not include such additional features.

4. The next dialog will prompt you to select whether to Disable path length limit. Choosing this
option will allow Python to bypass the 260-character MAX_PATH limit. Effectively, it will
enable Python to use long path names.
The Disable path length limit option will not affect any other system settings. Turning it on will
resolve potential name length issues that may arise with Python projects developed in Linux.

Step 4: Verify Python Was Installed On Windows


1. Navigate to the directory in which Python was installed on the system. In our case, it is C:\Users\
Username\AppData\Local\Programs\Python\Python37 since we have installed the latest
version.
2. Double-click python.exe.

3. The output should be similar to what you can see below:


Step 5: Verify Pip Was Installed
If you opted to install an older version of Python, it is possible that it did not come with Pip
preinstalled. Pip is a powerful package management system for Python software packages. Thus,
make sure that you have it installed.

We recommend using Pip for most Python packages, especially when working in virtual
environments.

To verify whether Pip was installed:

1. Open the Start menu and type "cmd."


2. Select the Command Prompt application.

3. Enter pip -V in the console. If Pip was installed successfully, you should see the following
output:
Pip has not been installed yet if you get the following output:

'pip' is not recognized as an internal or external command,


Operable program or batch file.

Step 6: Add Python Path to Environment Variables


(Optional)
We recommend you go through this step if your version of the Python installer does not include
the Add Python to PATH checkbox or if you have not selected that option.

Setting up the Python path to system variables alleviates the need for using full paths. It instructs
Windows to look through all the PATH folders for “python” and find the install folder that
contains the python.exe file.

1. Open the Start menu and start the Run app.


2. Type sysdm.cpl and click OK. This opens the System Properties window.

3. Navigate to the Advanced tab and select Environment Variables.

4. Under System Variables, find and select the Path variable.

5. Click Edit.

6. Select the Variable value field. Add the path to the python.exe file preceded with
a semicolon (;). For example, in the image below, we have added ";C:\Python34."

7. Click OK and close all windows.

By setting this up, you can execute Python scripts like this: Python script.py

Instead of this: C:/Python34/Python script.py

As you can see, it is cleaner and more manageable.


Step 7: Install virtualnv (Optional)
You have Python, and you have Pip to manage packages. Now, you need one last software
package - virtualnv. Virtualnv enables you to create isolated local virtual environments for your
Python projects.

Why use virtualnv?

Python software packages are installed system-wide by default. Consequently, whenever a single
project-specific package is changed, it changes for all your Python projects. You would want to
avoid this, and having separate virtual environments for each project is the easiest solution.

To install virtualnv:

1. Open the Start menu and type "cmd."

2. Select the Command Prompt application.

3. Type the following pip command in the console:

C:\Users\Username> pip install virtualenv

Upon completion, virtualnv is installed on your system.

What is variable

It is a place where we can store values. Instead of using the values directly, we can refer the
variable name where the actual values are stored.

Example
> x = 2 === > here X is Variable
> name = 'John' === > here NAME is variable

What is Expression

It contains values, variables and operators.

Example
> 10
>x
> y = x + 10

What is Statement

It is a logical unit of code that can be executed at the Python interpreter. When we type statement at
the command promt, it will execute the code in the statement then provides the results, as long as
the code is clean. We can execute code that is in a file. In general these file contains scripts, these
scripts are combination of statements to perform units of work.

Example
> print("Hello World")
Hello World

Values and types

A value is one of the basic things a program works with, like a letter or a number. The values we
have seen so far are 1, 2, and 'Hello, World!'.

These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, so-
called because it contains a “string” of letters. You (and the interpreter) can identify strings
because they are enclosed in quotation marks.

The print statement also works for integers.

>>> print 4
4

If you are not sure what type a value has, the interpreter can tell you.

>>> type('Hello, World!')


<type 'str'>
>>> type(17)
<type 'int'>

Not surprisingly, strings belong to the type str and integers belong to the type int. Less
obviously, numbers with a decimal point belong to a type called float, because these numbers
are represented in a format called floating-point.

>>> type(3.2)
<type 'float'>

What about values like '17' and '3.2'? They look like numbers, but they are in quotation
marks like strings.

>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>

They’re strings.

When you type a large integer, you might be tempted to use commas between groups of three
digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:

>>> print 1,000,000


1 0 0

Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-separated
sequence of integers, which it prints with spaces between.

This is the first example we have seen of a semantic error: the code runs without producing an
error message, but it doesn’t do the “right” thing.

Variables

One of the most powerful features of a programming language is the ability to


manipulate variables. A variable is a name that refers to a value.

An assignment statement creates new variables and gives them values:

>>> message = 'And now for something completely


different'
>>> n = 17
>>> pi = 3.1415926535897931

This example makes three assignments. The first assigns a string to a new variable
named message; the second gives the integer 17 to n; the third assigns the (approximate) value
of π to pi.

A common way to represent variables on paper is to write the name with an arrow pointing to the
variable’s value. This kind of figure is called a state diagram because it shows what state each
of the variables is in (think of it as the variable’s state of mind). This diagram shows the result of
the previous example:
To display the value of a variable, you can use a print statement:

>>> print n
17
>>> print pi
3.14159265359

The type of a variable is the type of the value it refers to.

>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>

Variable names and keywords

Programmers generally choose names for their variables that are meaningful—they document
what the variable is used for.

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have
to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable
names with a lowercase letter (you’ll see why later).

The underscore character (_) can appear in a name. It is often used in names with multiple
words, such as my_name or airspeed_of_unladen_swallow.

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade'


SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax

76trombones is illegal because it does not begin with a letter. more@ is illegal because it contains
an illegal character, @. But what’s wrong with class?
It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize
the structure of the program, and they cannot be used as variable names.

Python has 31 keywords:

and del from not while


as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try

You might want to keep this list handy. If the interpreter complains about one of your variable
names and you don’t know why, see if it is on this list.

Statements

A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.

When you type a statement in interactive mode, the interpreter executes it and displays the result,
if there is one.

A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.

For example, the script

print 1
x = 2
print x

produces the output

1
2

The assignment statement produces no output.

Comments

As programs get bigger and more complicated, they get more difficult to read. Formal languages
are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or
why.
For this reason, it is a good idea to add notes to your programs to explain in natural language
what the program is doing. These notes are called comments, and they start with the # symbol:

# compute the percentage of the hour that has elapsed


percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end of a
line:

percentage = (minute * 100) / 60 # percentage of an


hour

Everything from the # to the end of the line is ignored—it has no effect on the program.

Comments are most useful when they document non-obvious features of the code. It is
reasonable to assume that the reader can figure out what the code does; it is much more useful to
explain why.

This comment is redundant with the code and useless:

v = 5 # assign 5 to v

This comment contains useful information that is not in the code:

v = 5 # velocity in meters/second.

Good variable names can reduce the need for comments, but long names can make complex
expressions hard to read, so there is a tradeoff.

Debugging

Three kinds of errors can occur in a program: syntax errors, runtime


errors, and semantic errors. It is useful
to distinguish between them in order to track them down more quickly.
Syntax error:
“Syntax” refers to the structure of a program
and the rules about that structure. For example, parentheses have
to come in matching pairs, so (1 + 2) is legal, but 8)
is a syntax error.

If there is a syntax error


anywhere in your program, Python displays an error message and quits,
and you will not be able to run the program. During the first few
weeks of your programming career, you might spend a lot of
time tracking down syntax errors. As you gain experience, you will
make fewer errors and find them faster.

Runtime error:
The second type of error is a runtime error, so
called because the error does not appear until after the program has
started running. These errors are also called exceptions
because they usually indicate that something exceptional (and bad)
has happened.
Runtime errors are rare in the simple programs you will see in the
first few chapters, so it might be a while before you encounter one.

Semantic error:
The third type of error is “semantic”, which
means related to meaning. If there is a semantic error in your
program, it will run without generating error messages, but it will
not do the right thing. It will do something else. Specifically,
it will do what you told it to do.
Identifying semantic errors can be tricky because it requires you to work
backward by looking at the output of the program and trying to figure
out what it is doing.

Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used
in the program. The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-
z), upper-case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %,
^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not
the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
Python does not bind us to declare a variable before using it in the application. It allows
us to create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Object References
It is necessary to understand how the Python interpreter works when we declare a
variable. The process of treating variables is somewhat different from many other
programming languages.

Python is the highly object-oriented programming language; that's why every data item
belongs to a specific type of class. Consider the following example.

1. print("John")

Output:

John

The Python object creates an integer object and displays it to the console. In the above
print statement, we have created a string object. Let's check the type of it using the
Python built-in type() function.

Let's understand the following example

1. a = 50

In the above image, the variable a refers to an integer object.


Suppose we assign the integer value 50 to a new variable b.

a = 50

b=a

The variable b refers to the same object that a points to because Python does not create
another object.

Let's assign the new value to b. Now both variables will refer to the different objects.

a = 50

b =100

Python manages memory efficiently if we assign the same variable to two different
values.

Object Identity
In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id() function, is
used to identify the object identifier. Consider the following example.

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

We assigned the b = a, a and b both point to the same object. When we checked by
the id() function it returned the same number. We reassign a to 500; then it referred to
the new object identifier.

Variable Names
We have already discussed how to declare the valid variable. Variable names can be any
length can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore
character(_). Consider the following example of valid variables names.

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

Consider the following valid variables name.

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, n
a56me)

Output:

A B C D E D E F G F I

In the above example, we have declared a few valid variable names such as name,
_name_ , etc. But it is not recommended because when we try to read code, it may
create confusion. The variable name should be descriptive to make code more readable.

The multi-word keywords can be created by the following method.

o Camel Case - In the camel case, each word or abbreviation in the middle of
begins with a capital letter. There is no intervention of whitespace. For example -
nameOfStudent, valueOfVaraible, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also
capital. For example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For
example - name_of_student, etc.

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is
also known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value to
multiple variables or assigning multiple values to multiple variables. Consider the
following example.

1. Assigning single value to multiple variables

Eg:

1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)

Output:

50
50
50

2. Assigning multiple values to multiple variables:

Eg:

1. a,b,c=5,10,15
2. print a
3. print b
4. print c

Output:

5
10
15

The values will be assigned in the order in which variables appear.

Python Variable Types


There are two types of variables in Python - Local variable and Global variable. Let's
understand the following variables.

Local Variable
Local variables are the variables that declared inside the function and have scope within
the function. Let's understand the following example.

Example -

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:

The sum is: 50

Explanation:

In the above code, we declared a function named add() and assigned a few variables
within the function. These variables will be referred to as the local variables which have
scope only inside the function. If we try to use them outside the function, we get a
following error.

1. add()
2. # Accessing local variable outside the function
3. print(a)

Output:

The sum is: 50


print(a)
NameError: name 'a' is not defined

We tried to use local variable outside their scope; it threw the NameError.

Global Variables
Global variables can be used throughout the program, and its scope is in the entire
program. We can use global variables inside or outside the function.

A variable declared outside the function is the global variable by default. Python
provides the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the
following example.

Example -

1. # Declare a variable and initialize it


2. x = 101
3.
4. # Global variable in function
5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To Javatpoint'
11. print(x)
12.
13. mainFunction()
14. print(x)

Output:

101
Welcome To Javatpoint
Welcome To Javatpoint

Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we
defined a function and accessed the declared variable using the global keyword inside
the function. Now we can modify its value. Then, we assigned a new string value to the
variable x.

Now, we called the function and proceeded to print x. It printed the as newly assigned
value of x.

Delete a variable
We can delete the variable using the del keyword. The syntax is given below.

Syntax -

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
Print Single and Multiple Variables in Python
We can print multiple variables within the single print statement. Below are the example
of single and multiple printing values.

Example - 1 (Printing Single Variable)

1. # printing single value


2. a=5
3. print(a)
4. print((a))

Output:

5
5

Example - 2 (Printing Multiple Variables)

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:

5 6
1 2 3 4 5 6 7 8

Statements and Expressions


A statement is an instruction that the Python interpreter can execute. We have
only seen the assignment statement so far. Some other kinds of statements that
we’ll see shortly are while statements, for statements, if statements,
and import statements. (There are other kinds too!)
An expression is a combination of values, variables, operators, and calls to
functions. Expressions need to be evaluated. If you ask Python to print an
expression, the interpreter evaluates the expression and displays the result.

print(1 + 1)

print(len("hello"))

In this example len is a built-in Python function that returns the number of
characters in a string. We’ve previously seen the print and the type functions, so
this is our third example of a function!

The evaluation of an expression produces a value, which is why expressions


can appear on the right hand side of assignment statements. A value all by itself
is a simple expression, and so is a variable. Evaluating a variable gives the value
that the variable refers to.

y = 3.14

x = len("hello")

print(x)

print(y)

If we take a look at this same example in the Python shell, we will see one of the
distinct differences between statements and expressions.

>>> y = 3.14
>>> x = len("hello")
>>> print(x)
5
>>> print(y)
3.14
>>> y
3.14
>>>

Note that when we enter the assignment statement, y = 3.14, only the prompt is
returned. There is no value. This is due to the fact that statements, such as the
assignment statement, do not return a value. They are simply executed.

On the other hand, the result of executing the assignment statement is the
creation of a reference from a variable, y, to a value, 3.14. When we execute the
print function working on y, we see the value that y is referring to. In fact,
evaluating y by itself results in the same response.

Difference between Expressions and Statements in Python:


Expression Statement

An expression evaluates to a value A statement executes something

The evaluation of a statement does not changes state The execution of a statement changes state

Execution of a statement may or may not produces


Evaluation of an expression always Produces or returns a
result value. or displays a result value, it only does whatever the
statement says.

Every expression can’t be a statement. Every statement can be an expression.

Example: >>> x = 3
Example: >>> a + 16 >>> print(x)
>>> 20
Output: 3

Conditional Execution:-

Decision-making is as important in any programming language as it is in life.


Decision-making in a programming language is automated using conditional
statements, in which Python evaluates the code to see if it meets the specified
conditions.
The conditions are evaluated and processed as true or false. If this is found to
be true, the program is run as needed. If the condition is found to be false, the
statement following the If condition is executed.

Python has six conditional statements that are used in decision-making:-

1. If the statement

2. If else statement

3. Nested if statement

4. If…Elif ladder

5. Short Hand if statement

6. Short Hand if-else statement

If Statement

The If statement is the most fundamental decision-making statement, in which


the code is executed based on whether it meets the specified condition. It has
a code body that only executes if the condition in the if statement is true. The
statement can be a single line or a block of code.

The if statement in Python has the subsequent syntax:


if expression
Statement

#If the condition is true, the statement will be executed.


Examples for better understanding:

Example – 1
num = 5
if num > 0:
print(num, "is a positive number.")
print("This statement is true.")
#When we run the program, the output will be:
5 is a positive number.
This statement is true.

Example – 2

a = 25
b = 170
if b > a:
print("b is greater than a")
output : b is greater than a

If Else Statement

This statement is used when both the true and false parts of a given condition
are specified to be executed. When the condition is true, the statement inside
the if block is executed; if the condition is false, the statement outside the if
block is executed.

The if…Else statement in Python has the following syntax:


if condition :
#Will executes this block if the condition is true
else :
#Will executes this block if the condition is false

Example for better understanding:


num = 5
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
output : Positive or Zero

If…Elif..else Statement

In this case, the If condition is evaluated first. If it is false, the Elif statement
will be executed; if it also comes false, the Else statement will be executed.
The If…Elif..else statement in Python has the subsequent syntax:
if condition :
Body of if
elif condition :
Body of elif
else:
Body of else

Example for better understanding:

We will check if the number is positive, negative, or zero.


num = 7
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
output: Positive number
Nested IF Statement

A Nested IF statement is one in which an If statement is nestled inside


another If statement. This is used when a variable must be processed more
than once. If, If-else, and If…elif…else statements can be used in the
program. In Nested If statements, the indentation (whitespace at the
beginning) to determine the scope of each statement should take precedence.

The Nested if statement in Python has the following syntax:


if (condition1):
#Executes if condition 1 is true
if (condition 2):
#Executes if condition 2 is true
#Condition 2 ends here
#Condition 1 ends here

Examples for better understanding:

Example-1
num = 8
if num >= 0:
if num == 0:
print("zero")
else:
print("Positive number")
else:
print("Negative number")
output: Positive number

Example-2
price=100
quantity=10
amount = price*quantity
if amount > 200:
if amount >1000:
print("The amount is greater than 1000")
else:
if amount 800:
print("The amount is between 800 and 1000")
elif amount 600:
print("The amount is between 600 and 1000")
else:
print("The amount is between 400 and 1000")
elif amount == 200:
print("Amount is 200")
else:
print("Amount is less than 200")
The output : “The amount is between 400 and 1000.”

Short Hand if statement


Short Hand if statement is used when only one statement needs to be
executed inside the if block. This statement can be mentioned in the same line
which holds the If statement.

The Short Hand if statement in Python has the following syntax:


if condition: statement

Example for better understanding:


i=15
# One line if statement
if i>11 : print (“i is greater than 11″)
The output of the program : “i is greater than 11.”

Short Hand if-else statement

It is used to mention If-else statements in one line in which there is only one
statement to execute in both if and else blocks. In simple words, If you have
only one statement to execute, one for if, and one for else, you can put it all
on the same line.

Examples for better understanding:

#single line if-else statement


a=3
b=5
print("A") if a > b else print("B")
output: B

#single line if-else statement, with 3 conditions


a=3
b=5
print("A is greater") if a > b else print("=") if a == b else print("B is greater")
output: B is greater

To summarise,

· The If the condition is used to print the result when only one of the conditions
listed is true or false.

· When one of the conditions is false, the If-else condition is used to print the
statement.

· When there is a third possible outcome, the Elif statement is used. In a


program, any number of Elif conditions can be used.

· By declaring all of the conditions in a single statement, we can reduce the


number of codes that must be executed.

· Nested if statements can be used to nest one If condition inside another.

Switch Case Statement in Python


What is Switch statement?

A switch statement is a multiway branch statement that compares the value of


a variable to the values specified in case statements.

Python language doesn’t have a switch statement.

Python uses dictionary mapping to implement Switch Case in Python

Example
function(argument){
switch(argument) {
case 0:
return "This is Case Zero";
case 1:
return " This is Case One";
case 2:
return " This is Case Two ";
default:
return "nothing";
};
};

For the above Switch case in Python


def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")

if __name__ == "__main__":
argument = 1
print (SwitchExample(argument))

Python Functions
What is a function in Python?
In Python, a function is a group of related statements that performs a specific
task.

Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.

Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

def function_name(parameters):

"""docstring"""
statement(s)

Above shown is a function definition that consists of the following


components.

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function.
They are optional.

4. A colon (:) to mark the end of the function header.

5. Optional documentation string (docstring) to describe what the function


does.

6. One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function.


Example of a function

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
How to call a function in python?

Once we have defined a function, we can call it from another function,


program, or even the Python prompt. To call a function we simply type the
function name with appropriate parameters.

>>> greet('Paul')
Hello, Paul. Good morning!

Try running the above code in the Python program with the function definition
to see the output.

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

greet('Paul')

Note: In python, the function definition should always be present before the
function call. Otherwise, we will get an error. For example,

# function call
greet('Paul')

# function definition
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
# Erro: name 'greet' is not defined

Docstrings
The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.

Although optional, documentation is a good programming practice. Unless you


can remember what you had for dinner last week, always document your
code.

In the above example, we have a docstring immediately below the function


header. We generally use triple quotes so that docstring can extend up to
multiple lines. This string is available to us as the __doc__ attribute of the
function.
For example:
Try running the following into the Python shell to see the output.

>>> print(greet.__doc__)

This function greets to


the person passed in as
a parameter

The return statement


The return statement is used to exit a function and go back to the place from
where it was called.
Syntax of return

return [expression_list]

This statement can contain an expression that gets evaluated and the value is
returned. If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return
the None object.
For example:

>>> print(greet("May"))
Hello, May. Good morning!
None

Here, None is the returned value since greet() directly prints the name and
no return statement is used.

Example of return

def absolute_value(num):
"""This function returns the absolute
value of the entered number"""

if num >= 0:
return num
else:
return -num

print(absolute_value(2))

print(absolute_value(-4))
Output

2
4

Types of Functions
Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


Example:- Python abs()
returns absolute value of a number
Python all()
returns true when all elements in iterable is true
Python any()
Checks if any Element of an Iterable is True
Python ascii()
Returns String Containing Printable Representation
Python bin()
converts integer to binary string
Python bool()
Converts a Value to Boolean
2. User-defined functions - Functions defined by the users themselves.
What are user-defined functions in Python?
Functions that we define ourselves to do certain specific task are
referred as user-defined functions.

Advantages of user-defined functions


1. User-defined functions help to decompose a large program into small
segments which makes program easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include
those codes and execute when needed by calling that function.

3. Programmars working on large project can divide the workload by


making different functions.

Example of a user-defined function


# Program to illustrate
# the use of user-defined functions

def add_numbers(x,y):
sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))

Output

Enter a number: 2.4


Enter another number: 6.5
The sum is 8.9

Here, we have defined the function my_addition() which adds two numbers and
returns the result.
This is our user-defined function. We could have multiplied the two numbers
inside our function (it's all up to us). But this operation would not be consistent
with the name of the function. It would create ambiguity.

It is always a good idea to name functions according to the task they perform.

The Anonymous Functions


These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
 Lambda forms can take any number of arguments but return just one value in
the form of an expression. They cannot contain commands or multiple
expressions.
 An anonymous function cannot be a direct call to print because lambda requires
an expression
 Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
 Although it appears that lambda's are a one-line version of a function, they are
not equivalent to inline statements in C or C++, whose purpose is by passing
function stack allocation during invocation for performance reasons.

Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −


Value of total : 30
Value of total : 40

Anonymous functions:
In Python, an anonymous function means that a function is without a name. As
we already know the def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions. Please see this for
details.

# Python code to illustrate the cube of a number


# using lambda function

def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))

print(cube_v2(7))

Output
343

Arguments in Functions
The argument is a value that is passed to the function when it’s called.

In other words on the calling side, it is an argument and on the function side it
is a parameter.

Let see how Python Args works –

Step 1) Arguments are declared in the function definition. While calling the
function, you can pass the values for that args as shown below
Step 2) To declare a default value of an argument, assign it a value at
function definition.

Example: x has no default values. Default values of y=0. When we supply only
one argument while calling multiply function, Python assigns the supplied
value to x while keeping the value of y=0. Hence the multiply of x*y=0

Step 3) This time we will change the value to y=2 instead of the default value
y=0, and it will return the output as (4×2)=8.
Step 4) You can also change the order in which the arguments can be passed
in Python. Here we have reversed the order of the value x and y to x=4 and
y=2.

Step 5) Multiple Arguments can also be passed as an array. Here in the


example we call the multiple args (1,2,3,4,5) by calling the (*args) function.

Example: We declared multiple args as number (1,2,3,4,5) when we call the


(*args) function; it prints out the output as (1,2,3,4,5)
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.

Function Arguments
You can call a function by using the following types of formal arguments −

 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the
function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
Live Demo
#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result −


Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
Live Demo
#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result −


My string
The following example gives more clear picture. Note that the order of parameters
does not matter.
Live Demo
#!/usr/bin/python

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50

Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed −
Live Demo
#!/usr/bin/python

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call. Following is a simple example −
Live Demo
#!/usr/bin/python

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −


Output is:
10
Output is:
70
60
50

Recursion
Python also accepts function recursion, which means a defined function can call
itself.

Recursion is a common mathematical and programming concept. It means that


a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.

Example
Recursion Example

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means
if you change what a parameter refers to within a function, the change also reflects
back in the calling function. For example −
Live Demo
#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
Live Demo
#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this
would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]

Explicit Type Conversion in Python


Explicit type conversion is also known as typecasting. Explicit type conversion takes
place when the programmer clearly and explicitly defines the same in the program. For
explicit type conversion, there are some in-built Python functions. The following table
contains some of the in-built functions for type conversion, along with their descriptions.
Function Description
int(y [base]) It converts y to an integer, and Base specifies the number base. For example, if you w
convert the string in decimal numbers then you’ll use 10 as base.
float(y) It converts y to a floating-point number.
complex(real It creates a complex number.
[imag])
str(y) It converts y to a string.
tuple(y) It converts y to a tuple.
list(y) It converts y to a list.
set(y) It converts y to a set.
dict(y) It creates a dictionary and y should be a sequence of (key, value) tuples.
ord(y) It converts a character into an integer.
hex(y) It converts an integer to a hexadecimal string.
oct(y) It converts an integer to an octal string

Now that we know the in-built functions provided by Python that are used for explicit
type conversion, let’s see the syntax for explicit type conversion:
(required_data type)(expression)

Let’s go over the following examples for explicit type conversion in Python.
# adding string and integer data types using explicit type
conversion
a = 100
b = “200”
result1 = a + b
b = int(b)
result2 = a + b
print(result2)

Output:
Traceback (most recent call last):
File “”, line 1, in
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
300

In the above example, variable a is of the number data type and variable b is of the
string data type. When we try to add these two integers and store the value in a variable
named result1, a TypeError occurs as shown in the output. So, in order to perform this
operation, we have to use explicit type casting.
As we can see in the above code block, we have converted the variable b into int type
and then added variables a and b. The sum is stored in the variable named result2, and
when printed it displays 300 as output, as we can see in the output block.

 Type conversion is the process of converting a data type into another data
type.
 Implicit type conversion is performed by a Python interpreter only.

 Explicit type conversion is performed by the user by explicitly using type


conversion functions in the program code.

 Explicit type conversion is also known as typecasting.

 Python, when performing implicit typecasting, avoids the loss of data.

Advantage of Functions in Python


There are the following advantages of Python functions.

o Using functions, we can avoid rewriting the same logic/code again and again in a
program.
o We can call Python functions multiple times in a program and anywhere in a
program.
o We can track a large Python program easily when it is divided into multiple
functions.
o Reusability is the main achievement of Python functions.
o However, Function calling is always overhead in a Python program.

Flow of Execution
The flow of execution basically refers to the order in which statements
are executed. That is to say, execution always starts at the first
statement of the program. Moreover, statements execute one at a time. It
happens in order, from top to bottom.
Further, functions definitions do not alter the flow of execution of the
program. However, it remembers the statements inside the function do
not execute until the functions is called.

Moreover, function calls are similar to a bypass in the flow of


execution. Thus, in place of going to the next statement, the flow will
jump to the first line of the called function. Then, it will execute all the
statements there. After that, it will come back to pick up where it left
off.

It is essential to remember that when reading a program, do not read it


from top to bottom. Instead, keep following the flow of execution. This
will ensure that one reads the def statements as they are scanning from
top to bottom.

However, one must skip the statements of the function definition until
they reach a point where that function is called.

ITERATIONS:
A computer program consists of line-by-line instructions. The computer
performs those instructions line-by-line. However, some instructions
may be repetitive with a common pattern. Recursion or iteration helps
one to write a few lines of codes to perform such repetitive tasks.
Suppose a Python list with five-string elements. We wish to print the
elements one in a line. This operation needs five lines of codes.

flowers = ['lily', 'tulip', 'rose', 'lavender',


'dandelion']
print(flowers[0])
print(flowers[1])
print(flowers[2])
print(flowers[3])
print(flowers[4])
Output:

It can be observed that the five lines of codes follow the same pattern.
The only difference in each line is the index of the list elements. What if
this list contains 100 or 1000 elements? Coding will become a tedious
task. These kinds of problems are resolved through either iteration or
recursion. Here, the iterative form of the above codes is as follows.

for flower in flowers:


print(flower)

Iteration in Python
Iterations are performed through ‘for’ and ‘while’ loops. Iterations
execute a set of instructions repeatedly until some limiting criteria is
met. In contrast to recursion, iteration does not require temporary
memory to keep on the results of each iteration. Rather, programmers
should define a variable (a number, or list, or string, or any mutable
data type) well before the start of iterative calls to collect the results (if
there are such arithmetic results) during each iteration.

Further, an iterative task can be accomplished by either a ‘for’ loop or a


‘while’ loop. A ‘for’ loop iterates over a sequence (such as a list, string,
tuple and range). It terminates the loop when there is no element left in
the sequence. It automatically traverses through the successive
elements. But a ‘while’ loop needs initialization of an iterator and
manual incrementation of the same. A ‘while’ loop is executed until an
iterator-based condition is satisfied.

Factorial of an Integer
Calculating factorial is a popular use case to understand iteration
For instance, we wish to calculate the factorial of 10. It can be
determined as 1*2*3*4*5*6*7*8*9*10 = 3628800. This can be viewed
as 10 subproblems of multiplying an incrementing integer to a final
result.

# using a for loop


n = 10
result = 1
for i in range(1,n+1):
result *= i
print(result)
Output:

A range function is implemented in a ‘for’ loop since it requires a


sequence to iterate over. Range function supplies values iteratively
from 1 through 10, one at a time. It stops iteration when the range
function stops supplying values(i.e., at 10).

# using a while loop


n = 10
result = 1
i = 1
while i <= n:
result *= i
i += 1
print(result)
Output:

In a ‘while’ loop, an iterator i is introduced and incremented through


every loop. While loop stops iterating when the value of i exceeds the
integer 10.
Updating variables
Variables are called variables because they can vary, but sometimes it takes a little
thought to understand how that can work. For example, in the code below we start
with num being set to 0, but then we make it bigger, and bigger, and bigger.

num = 0
print("The number is", num)
num = num + 1
print("The number is now", num)
num = num + 1
print("The number is up to", num)
num = num + 20
print("The number ends at", num)
How does that look? We re-use the num variable again and again, changing it each
time. One way of thinking about it:

 We set num = 0 to, yes, make num be 0.


 The first time we run num = num + 1…

o It calculates the right-hand side, num + 1

o This uses the current value of num (0), making 0 + 1. That’s 1.

o It then saves that 1 back into num, throwing away the old value for num

o Now num is 1!

 The second time we run num = num + 1…

o It calculates the right-hand side, num + 1

o This uses the new value of num (1), making 1 + 1. That’s 2.

o It then saves that 2 back into num, throwing away the old value for num

o Now num is 2!

 Then we run num = num + 20…

o It calculates the right-hand side, num + 20


o Since num is 2 now, that’s 2 + 20. That’s 22.

o It then saves that 22 back into num, throwing away the old value for num

o Now num is 22!

It might feel weird to see the same variable on both sides of the equals sign, but I
promise you’ll get used to it! Just know that you’re overwriting the old num every time
you do num = ... - the old num disappears into dust, and you’ll never be able to get it
back! (Not that you’d want to)

Two common reasons to update a variable are counting things, or if you’re too lazy to
have separate variable names.

Python While loop


The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of


iterations then the while loop is most effective to use.

The syntax is given below.

1. while expression:
2. statements

Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
While loop Flowchart

Example-1: Program to print 1 to 10 using while loop


1. i=1
2. #The while loop will iterate until condition becomes false.
3. While(i<=10):
4. print(i)
5. i=i+1

Example -2: Program to print table of given numbers.


1. i=1
2. number=0
3. b=9
4. number = int(input("Enter the number:"))
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i))
7. i = i+1
Using else with while loop
Python allows us to use the else statement with the while loop also. The else block is
executed when the condition given in the while statement becomes false. Like for loop,
if the while loop is broken using break statement, then the else block will not be
executed, and the statement present after else block will be executed. The else
statement is optional to use with the while loop. Consider the following example.

Example 1
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. else:
6. print("The while loop exhausted")

Example 2
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. if(i==3):
6. break
7. else:
8. print("The while loop exhausted")

The Infinite Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never
resolves to a FALSE value. This results in a loop that never ends. Such a loop is called
an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to
run continuously so that client programs can communicate with it as and when
required.
#!/usr/bin/python

var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num

print "Good bye!"

When the above code is executed, it produces the following result −


Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File "test.py", line 5, in <module>
num = raw_input("Enter a number :")
KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit the
program.

Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our program to
run continuously in the loop without any disturbance.

Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop")

Output:

Hi! we are inside the infinite while loop


Hi! we are inside the infinite while loop

Example 2
1. var = 1
2. while(var != 2):
3. i = int(input("Enter the number:"))
4. print("Entered value is %d"%(i))

Output:Enter the number:10

Enter the number:10


Entered value is 10
Enter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Infinite time
Enter the number:10
E

Loop Control Statements


We can change the normal sequence of while loop's execution using the loop control
statement. When the while loop's execution is completed, all automatic objects defined
in that scope are demolished. Python offers the following control statement to use
within the while loop.

1. Continue Statement - When the continue statement is encountered, the control


transfer to the beginning of the loop. Let's understand the following example.

Example:

1. # prints all letters except 'a' and 't'


2. i=0
3. str1 = 'javatpoint'
4.
5. while i < len(str1):
6. if str1[i] == 'a' or str1[i] == 't':
7. i += 1
8. continue
9. print('Current Letter :', a[i])
10. i += 1

Output:

Current Letter : j
Current Letter : v
Current Letter : p
Current Letter : o
Current Letter : i
Current Letter : n

2. Break Statement - When the break statement is encountered, it brings control out of
the loop.

Example:

1. # The control transfer is transfered


2. # when break statement soon it sees t
3. i=0
4. str1 = 'javatpoint'
5.
6. while i < len(str1):
7. if str1[i] == 't':
8. i += 1
9. break
10. print('Current Letter :', str1[i])
11. i += 1

Output:

Current Letter : j
Current Letter : a
Current Letter : v
Current Letter : a

3. Pass Statement - The pass statement is used to declare the empty loop. It is also
used to define empty class, function, and control statement. Let's understand the
following example.

Example -

1. # An empty loop
2. str1 = 'javatpoint'
3. i=0
4.
5. while i < len(str1):
6. i += 1
7. pass
8. print('Value of i :', i)

Output:

Value of i : 10
ntered value is 10
Infinite time

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 is given below.

#loop statements

1. break;

Example 1

1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:

nOutput:

item matched
found at 2 location
ter the number:10ue is 10

EExample 2

1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);

Output:

p
y
t
h
nter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Infinite time

Python continue Statement


The continue statement in Python is used to bring the program control to the beginning
of the loop. The continue statement skips the remaining lines of code inside the loop
and start with the next iteration. It is mainly used for a particular condition inside the
loop so that we can skip some specific code for a particular condition.The continue
statement in Python is used to bring the program control to the beginning of the loop.
The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we
can skip some specific code for a particular condition.

Syntax
1. #loop statements
2. continue
3. #the code to be skipped

Flow Diagram

Consider the following examples.

Example 1
1. i=0
2. while(i < 10):
3. i = i+1
4. if(i == 5):
5. continue
6. print(i)

Output:

1
2
3
4
6
7
8
9
10

Observe the output of above code, the value 5 is skipped because we have provided
the if condition using with continue statement in while loop. When it matched with
the given condition then control transferred to the beginning of the while loop and it
skipped the value 5 from the code.

ewti-Tiered Revamp of PlayStation Plus Revealed

Let's have a look at another example:

Example 2
1. str = "JavaTpoint"
2. for i in str:
3. if(i == 'T'):
4. continue
5. print(i)

Output:

J
a
v
a
p
o
i
n
t

Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want
to execute code, the pass can be used to execute empty. It is the same as the name
refers to. It just makes the control to pass by without executing any code. If we want to
bypass any code pass statement can be used.
It is beneficial when a statement is required syntactically, but we want we don't want to
execute or execute it later. The difference between the comments and pass is that,
comments are entirely ignored by the Python interpreter, where the pass statement is
not ignored.

Suppose we have a loop, and we do not want to execute right this moment, but we will
execute in the future. Here we can use the pass.

Consider the following example.

Example - Pass statement

1. # pass is just a placeholder for


2. # we will adde functionality later.
3. values = {'P', 'y', 't', 'h','o','n'}
4. for val in values:
5. pass

Example - 2:

1. for i in [1,2,3,4,5]:
2. if(i==4):
3. pass
4. print("This is pass block",i)
5. print(i)

Output:

1. 1
2. 2
3. 3
4. This is pass block 4
5. 4
6. 5

What is loop patterns in Python?


Patterns can be printed in python using simple for loops. First outer loop is used to
handle number of rows and Inner nested loop is used to handle the number of
columns. Manipulating the print statements, different number patterns, alphabet
patterns or star patterns can be printed.

Pattern - 1: Simple pyramid pattern


Example -

# This is the example of print simple pyramid pattern

1. n = int(input("Enter the number of rows"))


2. # outer loop to handle number of rows
3. for i in range(0, n):
4. # inner loop to handle number of columns
5. # values is changing according to outer loop
6. for j in range(0, i + 1):
7. # printing stars
8. print("* ", end="")
9.
10. # ending line after each row
11. print()

Output:

*
* *
* * *
* * * *
* * * * *

Pattern - 4: Printing Triangle Pyramid


Code -

1. n = int(input("Enter the number of rows: "))


2. m = (2 * n) - 2
3. for i in range(0, n):
4. for j in range(0, m):
5. print(end=" ")
6. m = m - 1 # decrementing m after each loop
7. for j in range(0, i + 1):
8. # printing full Triangle pyramid using stars
9. print("* ", end=' ')
10. print(" ")

Output:

Enter the number of rows: 10


*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *

Python 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.
Consider the following example in Python to create a string.

Syntax:
1. str = "Hi Python !"

Here, if we check the type of the variable str using a Python script

1. print(type(str)), then it will print a string (str).

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.

Creating String in Python


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.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)

Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring

Strings indexing and splitting


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.

Consider the following example:

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])

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.

String Slicing in Python


Python slicing is about obtaining a sub-string from the given string by slicing it
respectively from start to end.
Python slicing can be done in two ways.
 slice() Constructor
 Extending Indexing
slice() Constructor
The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step).
Syntax:
 slice(stop)
 slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each
index for slicing.
Return Type: Returns a sliced object containing elements in the given range
only.
Index tracker for positive and negative index:
Negative comes into considers when tracking the string in reverse.

Example
# Python program to demonstrate

# string slicing

# String slicing

String ='ASTRING'

# Using slice constructor

s1 = slice(3)

s2 = slice(1, 5, 2)

s3 = slice(-1, -12, -2)

print("String slicing")

print(String[s1])

print(String[s2])

print(String[s3])

Output:

String slicing
AST
SR
GITA
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This
is an easy and convenient way to slice a string both syntax wise and execution
wise.
Syntax
string[start:end:step]
start, end and step have the same mechanism as slice() constructor.
Example

# Python program to demonstrate string slicing

String ='ASTRING'

# Using indexing sequence

print(String[:3])

print(String[1:5:2])

print(String[-1:-12:-2])

# Prints string in reverse

print("\nReverse String")

print(String[::-1])

Output:

AST
SR
GITA

Reverse String
GNIRTSA

Looping and Counting:


Python Program to Count
Occurrence of a Character in a
String
Write a Python Program to Count Occurrence of a Character in a String with a
practical example. This python program allows you to enter a string and a
character.

# Python Program to Count Occurrence of a Character in a String

string = input("Please enter your own String : ")

char = input("Please enter your own Character : ")

count = 0

for i in range(len(string)):

if(string[i] == char):

count = count + 1

print("The total Number of Times ", char, " has Occurred = " , count)

Python Program to Count Occurrence


of a Character Example 2
This Python counting total occurrence of a character in a string program is the
same as the above. However, we just replaced the For Loop with While Loop.

# Python Program to Count Occurrence of a Character in a String


string = input("Please enter your own String : ")

char = input("Please enter your own Character : ")

i=0

count = 0

while(i < len(string)):

if(string[i] == char):

count = count + 1

i=i+1

print("The total Number of Times ", char, " has Occurred = " , count)

python character occurrence in a string output

Please enter your own String : python programs

Please enter your own Character : p

The total Number of Times p has Occurred = 2

>>>

Please enter your own String : hello

Please enter your own Character : l

The total Number of Times l has Occurred = 2


Python Program to Count Characters in
a String Example 2
This String Characters program is the same as the above example. However, in
this Python code, we are using the For Loop with Range.

# Python Program to Count Total Characters in a String

str1 = input("Please Enter your Own String : ")

total = 0

for i in range(len(str1)):

total = total + 1

print("Total Number of Characters in this String = ", total)

Please Enter your Own String : Python

Total Number of Characters in this String = 6

Python Program to Count Number of


Characters in a String Example 3
This python program to count characters is the same as above. However, we just
replaced the For Loop with While Loop.

# Python Program to Count Total Characters in a String


str1 = input("Please Enter your Own String : ")

total = 0

i=0

while(i < len(str1)):

total = total + 1

i=i+1

print("Total Number of Characters in this String = ", total)

Please Enter your Own String : Python Programming

Total Number of Characters in this String = 18

to Find String Length in Python


the first method, and the easiest one, len() directly returns the length of the passed
string object where it is called. The len() method also works on other iterable objects
like lists. The below-given code illustrates how we can use the function as well as how it works.
#Given string whose length is to be found
str1="Python is great!"
print("The given String is:",str1)

#calling our len() method to calculate


#the length of str1
print("Length =",len(str1))

Output:
String Length Using len() Method

Here,

str1 is the given string

Next, we directly call the method len() with the string and print the value returned
by it. As we can see, the method gives us the right length for the given string, str1.

Python “in” operator


Basically, the in operator in Python checks whether a specified value is a
constituent element of a sequence like string, array, list, or tuple etc.
When used in a condition, the statement returns a Boolean result
evaluating into either True or False. When the specified value
is found inside the sequence, the statement returns True. Whereas when
it is not found, we get a False.

Not let us take an example to get a better understanding of


the in operator working.

#in operator working

list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)

print(5 in list1) #True


print("is" in string1) #True
print(88 in tuple1) #False
Output:

Here:

Firstly, we have initialised a list list1, a string string1 and a


tuple tuple1 with some values. Then we use the in operator to check
whether some values are part of the above sequences or not.
As we can see from the above output, 5 in list1 evaluates into a True.
Which signifies that the value 5 is found inside the list.
Similarly, using the in operator we also confirm the presence of the
string “is” in string1. But for the last case, the condition results in
a False since 88 is not present inside the sequence tuple1.

Python “not in” operator


The not in operator in Python works exactly the opposite way as
the in operator works. It also checks the presence of a specified value
inside a given sequence but it’s return values are totally opposite to that
of the in operator.
When used in a condition with the specified value present inside the
sequence, the statement returns False. Whereas when it is not, we get
a True.
Let us take the previous example, just replacing in operator with the not
in one.
#not in operator working

list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)

print(5 not in list1) #False


print("is" not in string1) #False
print(88 not in tuple1) #True
Output:

1) Python In Membership Operator

This In operator is used in python to evaluate if a particular value is there or not in a


sequence. The In operator returns True if it the specified element found in the list, otherwise
it returns false.

Let’s consider a python program on how In operator works.

Program

a = 10
b = 7
list = [1,2,3,4,5,6,7,8,9..)

If (a is in list):
print: line - 1 “a is presented in the list”
else
print: line - 1 “a is not presented in the list”
If (b is in list):
print: line - 2 “b is presented in the list”
else
print: line - 2 “b is not presented in the list”

When you are done with the execution of above program, you will get the below output:

Line - 1- a is not available in the list. Hence False.


Line - 2- b is available in the list. Hence True

2) python Not in Membership Operator

“Not in” operator, the name itself is expressing the meaning that something is not inside. It
goes through a particular sequence to find weather a value is in the specified list or not. If it
finds there is no such value, it returns True, otherwise False.

Let’s consider a python program on how Not In operator works:

Program

# Not ‘in’ Operator


x = 23
y = 20
list = [10, 15,20, 30, 35, 40,45, 50];
if (x is not in list)
print: “ x is not available in the list”
else
print: “ x is available in the given list”
if (y is not in list)
print: “ y is not available in the given list”
else
print: “ y is available in the given list”

Run:

Line 1 - x is not there in given list. Hence True.


Line 2 - y is there in given list. Hence False.

String Comparison in Python


Let us see how to compare Strings in Python.
Method 1: Using Relational Operators
The relational operators compare the Unicode values of the characters of the
strings from the zeroth index till the end of the string. It then returns a boolean
value according to the operator used.
Example:
“Geek” == “Geek” will return True as the Unicode of all the characters are equal
In case of “Geek” and “geek” as the unicode of G is \u0047 and of g is \u0067
“Geek” < “geek” will return True and
“Geek” > “geek” will return False

 Python3

print("Geek" == "Geek")

print("Geek" < "geek")

print("Geek" > "geek")

print("Geek" != "Geek")

Output:
True
True
False
False
Method 2: Using is and is not
The == operator compares the values of both the operands and checks for
value equality. Whereas is operator checks whether both the operands refer to
the same object or not. The same is the case for != and is not.
Let us understand this with an example:

 Python3

str1 = "Geek"

str2 = "Geek"
str3 = str1

print("ID of str1 =", hex(id(str1)))

print("ID of str2 =", hex(id(str2)))

print("ID of str3 =", hex(id(str3)))

print(str1 is str1)

print(str1 is str2)

print(str1 is str3)

str1 += "s"

str4 = "Geeks"

print("\nID of changed str1 =", hex(id(str1)))

print("ID of str4 =", hex(id(str4)))

print(str1 is str4)

Output:
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
ID of changed str1 = 0x7f60356137d8
ID of str4 = 0x7f60356137a0
False
The object ID of the strings may vary on different machines. The object IDs of
str1, str2 and str3 were the same therefore they the result is True in all the
cases. After the object id of str1 is changed, the result of str1 and str2 will be
false. Even after creating str4 with the same contents as in the new str1, the
answer will be false as their object IDs are different.
Vice-versa will happen with is not.
Method 3: Creating a user-defined function.
By using relational operators we can only compare the strings by their
unicodes. In order to compare two strings according to some other parameters,
we can make user-defined functions.
In the following code, our user-defined function will compare the strings based
upon the number of digits.

 Python3

# function to compare string

# based on the number of digits

def compare_strings(str1, str2):

count1 = 0

count2 = 0

for i in range(len(str1)):

if str1[i] >= "0" and str1[i] <= "9":

count1 += 1
for i in range(len(str2)):

if str2[i] >= "0" and str2[i] <= "9":

count2 += 1

return count1 == count2

print(compare_strings("123", "12345"))

print(compare_strings("12345", "geeks"))

print(compare_strings("12geeks", "geeks12"))

Output:
False
False
True

Python String Methods


Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original string.
Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs


in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns


the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string


index() Searches the string for a specified value and returns
the position of where it was found

isalnum() Returns True if all characters in the string are


alphanumeric

isalpha() Returns True if all characters in the string are in the


alphabet

isascii() Returns True if all characters in the string are ascii


characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower


case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are


printable
isspace() Returns True if all characters in the string are
whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper


case

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three


parts

replace() Returns a string where a specified value is replaced


with a specified value
rfind() Searches the string for a specified value and returns
the last position of where it was found

rindex() Searches the string for a specified value and returns


the last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three


parts

rsplit() Splits the string at the specified separator, and returns


a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns


a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified


value
strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice
versa

title() Converts the first character of each word to upper


case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at


the beginning

Tuples & Dictionaries:

Tuple:- A tuple is an ordered collection of data.

How to create a tuple


1
2
3
4
5
6
tuple1=(1,2,"college",9)
tuple2=() # creates an empty tuple
tuple3=tuple((1,3,5,9,"hello"))
print(tuple1)
print(tuple2)
print(tuple3)

The fundamental distinction that Python makes on data is whether or not the
value of an object changes. An object is mutable if the value can change; else,
the object is immutable.

Tuples are immutable.

Though tuples are ordered, the elements cannot be sorted.


Tuples are immutable lists. Elements of a list can be modified, but elements in a tuple can only be
accessed, not modified. The name tuple does not mean that only two values can be stored in this data
structure.

The elements of a tuple can not be modified. If you try to assign a new value to one of the
elements in a tuple, an error is returned.
>>> t_var = (3,4,5) # a tuple
>>> t_var[0]= 8
>>> t_var

TypeError: 'tuple' object does not support item assignment

Dictionaries

A dictionary is an unordered collection of data that stores data in key-value


pairs.

How to create a dictionary


1
2
3
4
5
6
dict1={"key1":"value1","key2":"value2"}
dict2={} # empty dictionary
dict3=dict({1:"apple",2:"cherry",3:"strawberry"})
print(dict1)
print(dict2)
print(dict3)

Dictionaries are mutable and keys do not allow duplicates.

Dictionaries are enclosed in curly brackets in the form of key-value pairs.

The elements cannot be reversed, as the items in the dictionary are in the form
of key-value pairs
Let's store the ages of two people in a dictionary. The two people
are Gabby and Maelle. Gabby is 8 and Maelle is 5. Note the name Gabby is a string and the
age 8 is an integer.
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> type(age_dict)
dict

The values stored in a dictionary are called and assigned using the following syntax:
dict_name[key] = value
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict["Gabby"]
8
We can add a new person to our age_dict with the following command:
>>> age_dict = {"Gabby": 8 , "Maelle": 5}

>>> age_dict["Peter"]= 40
>>> age_dict
{'Gabby': 8, 'Maelle': 5, 'Peter': 40}

Items can be removed from dictionaries by calling the .pop() method. The dictionary key (and
that key's associated value) supplied to the .pop() method is removed from the dictionary.
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict.pop("Gabby")
>>> age_dict
{'Maelle': 5}

How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to
the first item of the second tuple; if they are not equal, this is the result of the
comparison, else the second item is considered, then the third and so on.

example
>>> a = (1, 2, 3)
>>> b = (1, 2, 5)
>>> a < b
True
There is another type of comparison that takes into account similar and different
elements. This can be performed using sets. Sets will take the tuples and take only
unique values. Then you can perform a & operation that acts like intersection to get the
common objects from the tuples.

example
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a) & set(b)
{5}

example
You can also use set.intersection function to perform this operation.
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a).instersection(set(b))
set([5])

Let us have a look at the following snippet which compares two tuples
in numerous scenarios:

# comparing integers
print((10, 20) < (10, 25))
print((10, 20) == (10, 25))
print((10, 20) > (10, 25))
# comparing strings
print(('x', 'y') < ('x', 'z'))
# comparing list of tuples
print(([4, 5], [5, 6]) == ([4, 5], [5, 6]))

Output:
True
False
False
True
True

Consider that you have couple of tuples with different lengths. Let us
have a look at how this comparison works in the following snippet:

tup1 = (10, 20, 30)


tup2 = (10, 20, 30, 40)
if tup1 > tup2:
print(tup1, ">", tup2, "--> TRUE")
else:
print(tup1, '<', tup2, "--> TRUE")

Output:
(10, 20, 30) < (10, 20, 30, 40) --> TRUE

Methods To Compare Two


Tuples In Python
➧ Method 1 : Using all() and zip()
 Python’s built-in all(x) function takes one iterable as an
argument x such as a list, tuple, or dictionary. It returns True if
all iterable elements evaluate to True using implicit Boolean
conversion, otherwise, it returns False . If the iterable is
empty, all() returns True because the condition is satisfied for all
elements.
 The zip() function takes an arbitrary number of iterables and
aggregates them to a single iterable, a zip object. It combines
the i-th values of each iterable argument into a tuple. Hence, if
you pass two iterables, each tuple will contain two values. If you
pass three iterables, each tuple will contain three values. For
example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5),
(3,6)] .
 Example:
 tup1 = (10, 20, 40)

 tup2 = (5, 15, 25)

 if all(x > y for x, y in zip(tup1, tup2)):

 print("tup1 is greater!")

 else:

 print("tup2 is greater!")

 Output:
 tup1 is greater!

 ➧ Method 2 : Using all() And map() With


A Lambda Function
 tup1 = (10, 20, 40)

 tup2 = (5, 15, 25)

 if all(map(lambda x, y: x>y,tup1, tup2)):

 print("tup1 is greater!")

 else:

 print("tup2 is greater!")

 Output:
 tup1 is greater!

TUPLE ASSIGNMENT

 An assignment to all of the elements in a tuple using a single assignment


statement.
 Python has a very powerful tuple assignment feature that allows a tuple of
variables on the left of an assignment to be assigned values from a tuple on the
right of the assignment.
 The left side is a tuple of variables; the right side is a tuple of values.
 Each value is assigned to its respective variable.
 All the expressions on the right side are evaluated before any of the
assignments. This feature makes tuple assignment quite versatile.
 Naturally, the number of variables on the left and the number of values on
the right have to be the same.
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack

Example:
-It is useful to swap the values of two variables. With conventional
assignment statements, we have to use a temporary variable. For example,
to swap a and b:

Swap two numbers


a=2;b=3
print(a,b)
temp = a
a=b
b = temp
print(a,b)

Output:
(2, 3)
(3, 2)
>>>
-Tuple assignment solves this problem neatly:
(a, b) = (b, a)

-One way to think of tuple assignment is as tuple packing/unpacking.


In tuple packing, the values on the left are ‘packed’ together in a tuple:
>>> b = ("George", 25, "20000") # tuple packing
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into
the variables/names on the right:
>>> b = ("George", 25, "20000") # tuple packing
>>> (name, age, salary) = b # tuple unpacking
>>> name
'George'
>>> age
25
>>> salary
'20000'
-The right side can be any kind of sequence (string,list,tuple)

Example:
-To split an email address in to user name and a domain
>>> mailid='god@abc.org'
>>> name,domain=mailid.split('@')
>>> print name
god
print (domain)
abc.org
Packing and Unpacking
In packing, we place value into a new tuple while in unpacking we extract
those values back into variables.
x = ("Guru99", 20, "Education") # tuple packing
(company, emp, profile) = x # tuple unpacking
print(company)
print(emp)
print(profile)

Python Tuple

A tuple is a collection which is ordered and unchangeable.

Tuples are identical to lists in all respects, except for the following
properties:

 Tuples are defined by enclosing the elements in parentheses ( )


instead of square brackets [ ] .

 Tuples are immutable ( elements of a tuple cannot be changed


once they have been assigned ).

Creating a Tuple

A tuple is created by placing all the elements inside parentheses( ),


separated by commas. The parentheses are optional, however, it is a
good practice to use them. A tuple can have any number of items and
they may be of different types (integer, float, list, string, etc.).

Examples:
my_tuple = (); //Empty tuplemy_tuple = (‘hello’,)
//For creating tuples with a single element, add a trailing comma to indicate that it is a
tuple.my_tuple = (10, ‘cat’, 99.9, (11, 22, 33))
//Nested tuple with mixed data type

Various operations that you have learned and performed on lists such
as accessing elements, indexing and negative indexing, slicing, looping
through elements, tuple length, checking if an element exists, and
sorting are true for tuples as well.

But tuples can’t be modified. The operations such as appending,


extending, changing elements, and removing elements from a tuple are
not possible, and eventually result in errors.

Deleting a tuple

A tuple can be deleted completely using the del keyword. For example,
my_tuple = (‘cat’, ‘rat’, ‘fish’)
del my_tuple //my_tuple gets deleted completely.

Tuple Methods

Python has two built-in methods count() and index() that you can use
on tuples.
count() Method

The count() method returns the number of times a specified value


appears in the tuple.
my_tuple = (30, 55, 23, 99, 21, 55, 23, 55, 42, 61, 99, 21, 55)
x = my_tuple.count(55)
//Returns the number of times the value 55 appears in the tuple.
print(x)

The output gives:


4

index() Method

The index() method finds the first occurrence of the specified value. It
raises an exception if the value is not found. Here is the example,
my_tuple = (30, 55, 23, 99, 21, 55, 23, 55, 42, 61, 99, 21, 55)
x = my_tuple.index(23)
//Searches for the first occurrence of the value 23, and returns its position.
print(x)

The output will be:


2

Thus, you can use a tuple when you don’t want your data to be
modified. If the values in the collection are meant to remain constant
for the entire life of the program, using a tuple guards against
accidental modification.
Python Dictionaries

Python dictionary is a collection which is unordered, changeable and


indexed. Each item of a dictionary has a key:value pair and are written
within curly brackets separated by commas. The values can repeat, but
the keys must be unique and must be of immutable type(string,
number or tuple).

Let’s go through some examples:


my_dict = {} //empty dictionarymy_dict = {1: ‘pizza’, 2: ‘burger’, 3: ‘milk’}
//dictionary with integer keysmy_dict = {‘name’: ‘Katie’, 1: [10, 20, 30], ‘dateofbirth’:1994 }
//dictionary with mixed keys

Accessing elements from a dictionary

You can access the elements of a dictionary by referring to its key


name, inside square brackets.
my_dict = {‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Canada’}
print(my_dict[‘age’])

There is also a method called get() to access the elements.


my_dict = {‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Canada’}
print(my_dict.get(‘age’))

Both the above programs give the following result:


20

Changing the value of an element

You can change the value of a specific element by referring to its key
name.
my_dict = {‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Canada’}
my_dict[‘place’] = ‘Australia’

The dictionary ‘my_dict’ becomes:


{‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Australia’}

Looping through a dictionary

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return values are the keys of
the dictionary.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x in my_dict:
print(x) //print all keys in the dictionary one by one

Output:
name
place
age

Note: Dictionaries are unordered collections. That is, the elements of


a dictionary are not stored in any particular order. So, the elements are
not iterated over in the same order in which they were created.

To print all the values in the dictionary one by one:


my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x in my_dict:
print(my_list[x])

Output:
Mariam
London
20

You can use the items() method for looping through both keys and
values.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x, y in my_dict.items():
print(x, “:”, y)

Output:
place : London
name : Mariam
age : 20

Checking if a key exists

To check if a specified key is present in a dictionary use the ‘in’


keyword.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
if ‘name’ in my_dict:
print(“Yes, name is one of the keys in my dictionary.”)

This will give:


Yes, name is one of the keys in my dictionary.

Dictionary Length

To determine how many elements (key-value pairs) a dictionary has,


use the len() function.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
print(len(my_dict))
which gives the output:
3

Adding elements to a dictionary

Adding an element to the dictionary is done by using a new index key


and assigning a value to it.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
my_dict[‘phone’] = 688143
print(my_dict)

The output becomes:


{‘age’: 20, ‘name’: ‘Mariam’, ‘phone’: 688143, ‘place’: ‘London’}

Removing elements from a dictionary

There are various ways to remove elements from a dictionary:

(i) pop() — removes the element with the specified key name.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
my_dict.pop(‘age’) //Removes the element with the key ‘age’
print(my_dict)

Output:
{‘name’: ‘Mariam’, ‘place’: ‘London’}

(ii) del — removes the element with the specified key name.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
del my_dict[‘age’]
print(my_dict)

Output:
{‘name’: ‘Mariam’, ‘place’: ‘London’}

The del keyword can also delete the dictionary completely.


my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
del my_dict //my_dict gets deleted completely.

(iv) clear() — empties the dictionary.


my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
my_dict.clear()
print(my_dict)

This will produce an empty dictionary:


{}
A dictionary in Python constitutes a group of elements in the
form of key-value pairs. Usually, we have single values for a
key in a dictionary.
However, we can have the values for keys as a collection like
a list. This way, we can have multiple elements in the
dictionary for a specific key.
For example,

d = {'a': [1,2],

'b': [2,3],

'c': [4,5]}

print(d)

Output:

{'a': [1, 2], 'b': [2, 3], 'c': [4, 5]}


Use a User-Defined Function to
Add Multiple Values to a Key in
a Dictionary
We can create a function to append key-value pairs in a
dictionary, with the value being a list.
For example,

def dict1(sample_dict, key, list_of_values):

if key not in sample_dict:

sample_dict[key] = list()

sample_dict[key].extend(list_of_values)

return sample_dict

word_freq = {'example': [1, 3, 4, 8, 10],

'for': [3, 10, 15, 7, 9],

'this': [5, 3, 7, 8, 1],

'tutorial': [2, 3, 5, 6, 11],

'python': [10, 3, 9, 8, 12]}

word_freq = dict1(word_freq, 'tutorial', [20, 21, 22])

print(word_freq)

Output:
{'example': [1, 3, 4, 8, 10], 'for': [3, 10, 15, 7, 9], 'this': [5, 3, 7, 8, 1],
'tutorial': [2, 3, 5, 6, 11, 20, 21, 22], 'python': [10, 3, 9, 8, 12]}

Note that, In the above code, we have created a


function dict1 with sample_dict, key and list_of_values as parameters
within the function. The extend() function will append a list as
the value for a key in the dictionary.

Use the defaultdict Module to Add


Multiple Values to a Key in a
Dictionary
is a part of the collections module. It is also a sub-class
defaultdict
of dict class that returns dictionary-like objects. For a key that
does not exist, it will give a default value.
Both defaultdict and dict have the same functionality except
that defaultdict never raises a keyerror.
We can use it to convert a collection of tuples to a dictionary.
We will specify the default value as a list. So whenever the
same key is encountered, it will append the value as a list.
For example,

from collections import defaultdict

s = [('rome', 1), ('paris', 2), ('newyork', 3), ('paris', 4), ('delhi', 1)]

d = defaultdict(list)

for k, v in s:

d[k].append(v)

sorted(d.items())
print(d)

Output:

defaultdict(<class 'list'>,

{'rome': [1],

'paris': [2, 4],

'newyork': [3],

'delhi': [1]

})

Use the setdefault() Method to


Add Multiple Values to a
Specific Key in a Dictionary
method is used to set default values to the key. When
setdefault()
the key is present, it returns some value. Else it inserts the
key with a default value. The default value for the key is none.
We will append the list as values for keys using this method.
For example,

s = [('rome', 1), ('paris', 2), ('newyork', 3), ('paris', 4), ('delhi', 1)]

data_dict = {}

for x in s:

data_dict.setdefault(x[0],[]).append(x[1])
print(data_dict)

Output:

{'rome': [1], 'paris': [2, 4], 'newyork': [3], 'delhi': [1]}

Using tuples as keys in dictionaries


Since tuples are hashable, and list is not, we must use tuple as the key if we
need to create a composite key to use in a dictionary.

Example: We would come across a composite key if we need to create a


telephone directory that maps, first-name, last-name, pairs of telephone
numbers, etc. Assuming that we have declared the variables as last and first
number, we could write a dictionary assignment statement as shown below:
directory[last,first] = number
Inside the brackets, the expression is a tuple. We could use tuple assignment
in a for loop to navigate this dictionary.
for last, first in directory:
print first, last, directory[last, first]
This loop navigates the keys in the directory, which are tuples. It assigns the
elements of each tuple to last and first and then prints the name and
corresponding telephone number.

Tuples and dictionary

Dictionary can return the list of tuples by calling items, where each tuple is a
key value pair.
a = {'x':100, 'y':200}
b = list(a.items())
print(b)

Here are the differences between List, Tuple, Set, and Dictionary in Python:

Parameters List Tuple Set Dictionary

Basics A list is basically The tuples refer to The sets are an In Python, the
Parameters List Tuple Set Dictionary

like a dynamically the collections of unordered dictionary refers to


sized array that various objects of collection of data a collection
gets declared in Python separated by types. These are (unordered) of
other languages commas between mutable, iterable, various data types.
(Arraylist in the them. and do not consist We use these for
case of Java, of any duplicate storing data values
vector in the case elements. such as maps, and
of C++). unlike other data
types capable of
holding only one
value in the form
of an element, a
dictionary can hold
the key: value pair.

Homogeneity A list refers to a A tuple also refers A set also refers A dictionary also
data structure of a to a data structure of to a data structure refers to a data
non-homogenous the non- of the non- structure of the
type that homogenous type homogenous non-homogenous
functions to store that functions to type, but it stores type that functions
various elements store various various elements to store key-value
in columns, elements in in a single row. pairs.
multiple rows, columns, multiple
and single rows. rows, and single
rows.

Representation We can represent We can represent a We can represent We can represent a


a List by [ ] Tuple by ( ) a Set by { } Dictionary by { }

Duplicate It allows various It allows various It does not allow The keys are not at
elements duplicate duplicate elements. any duplicate all duplicated.
elements. elements.

Nested Among It can be utilized It can be utilized in It can be utilized It can be utilized in
All in a List. a Tuple. in a Set. a Dictionary.

Example [6, 7, 8, 9, 10] (6, 7, 8, 9, 10) {6, 7, 8, 9, 10} {6, 7, 8, 9, 10}

Function for We can create a We can create a We can create a We can create a
Creation list using tuple using set using dictionary using
the list() function. the tuple() function. the set() function. the dict() function.

Mutation It is mutable. It It is immutable. It It is mutable. It It is mutable, but


means that a user means that a user means that a user the keys are not at
can make any can’t make any can make any all duplicated.
Parameters List Tuple Set Dictionary

changes to a list. changes to a tuple. changes to a set.

Order It is ordered in It is ordered in It is unordered in It is ordered in


nature. nature. nature. nature.

Empty If we want to If we want to create If we want to If we want to


Elements create an empty an empty tuple, we create an empty create an empty
list, we use: use: set, we use: dictionary, we use:
l=[] t=() a=set() d={}
b=set(a)

Python List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python
consists of six data-types that are capable to store the sequences, but the most
common and reliable type is the list.

A list can be defined as a collection of values or items of different types. The items in the
list are separated with the comma (,) and enclosed with the square brackets [].

A list can be define as below

1. L1 = ["John", 102, "USA"]


2. L2 = [1, 2, 3, 4, 5, 6]

A list is a sequence
Like a string, a list is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in list are
called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the
elements in square brackets (“[” and “]”):

[10, 20, 30, 40]


['crunchy frog', 'ram bladder', 'lark vomit']

The first example is a list of four integers. The second is a list of three strings.
The elements of a list don’t have to be the same type. The following list contains
a string, a float, an integer, and (lo!) another list:

['spam', 2.0, 5, [10, 20]]

A list within another list is nested.

A list that contains no elements is called an empty list; you can create one with
empty brackets, [].

As you might expect, you can assign list values to variables:

cheeses = ['Cheddar', 'Edam', 'Gouda']

numbers = [17, 123]

empty = []

print(cheeses, numbers, empty)

Traversing Lists
Lists are basically equal to arrays in other languages. However, they do
have the extra benefit of being dynamic in size. In Python, the list is a
kind of container in Data structures. It comes in use for storing
numerous data at the same time. Contrasting to sets, in Python, lists
are ordered and have a definite count. Moreover, there are various
ways for traversing lists in Python.

Methods of Traversing Lists


Here are the methods which one can refer to for traversing lists in
Python:
 Python range () method
 List Comprehension
 Python enumerate () method
 Lambda function
 Python NumPy module
 By using a for Loop
 By using a while Loop

Using For Loop

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Using for loop

for i in list:

print(i)

Output:

10
Using For Loop and Range ()
If you wish to use the traditional for loop which iterates from number x
to number y.

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# getting length of list

length = len(list)

# Iterating the index

# same as 'for i in range(len(list))'

for i in range(length):

print(list[i])

Output:

10

It is essential to remember that it is not recommended to iterate by


making use of the index if one can iterate over the elements (like how it
is done in the first method).
Using While Loop

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Getting length of list

length = len(list)

i = 0

# Iterating using while loop

while i < length:

print(list[i])

i += 1

Output:

10
Using List Comprehension
This one is possibly the most concrete way.

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Using list comprehension

[print(i) for i in list]

Output:

10

Using Enumerate()
If you wish to convert the list into an iterable list of tuples (or get the
index on the basis of a condition check, for instance, in linear search,
one might want to save the index of minimum element), one can use the
enumerate () function.

# Python3 code to iterate over a list

list = [1, 3, 5, 7, 9]

# Using enumerate()
for i, val in enumerate(list):

print (i, ",",val)

Output:

0 , 1

1 , 3

2 , 5

3 , 7

4 , 9

You can also use the second method for finding the index. However, the
first method cannot be used unless an extra variable is incremented
every iteration. Moreover, the fifth method gives a concise
representation of this indexing.

List Operations in Python


Given below are some of the most widely used list operations in Python:

1. append()
The append() method is used to add elements at the end of the list. This method can

only add a single element at a time. To add multiple elements, the append() method

can be used inside a loop.


Code:

myList.append(4)

myList.append(5)

myList.append(6)

for i in range(7, 9):

myList.append(i)
print(myList)

Output:

2. extend()
The extend() method is used to add more than one element at the end of the list.

Although it can add more than one element, unlike append(), it adds them at the end

of the list like append().

Code:

myList.extend([4, 5, 6])

for i in range(7, 9):

myList.append(i)
print(myList)
Output:

3. insert()
The insert() method can add an element at a given position in the list. Thus, unlike

append(), it can add elements at any position, but like append(), it can add only one

element at a time. This method takes two arguments. The first argument specifies the

position, and the second argument specifies the element to be inserted.

Code:

myList.insert(3, 4)

myList.insert(4, 5)

myList.insert(5, 6)
print(myList)

Output:

4. remove()
The remove() method is used to remove an element from the list. In the case of

multiple occurrences of the same element, only the first occurrence is removed.
Code:

myList.remove('makes learning fun!')

myList.insert(4, 'makes')

myList.insert(5, 'learning')

myList.insert(6, 'so much fun!')


print(myList)

Output:

5. pop()
The method pop() can remove an element from any position in the list. The parameter

supplied to this method is the index of the element to be removed.

Code:

myList.pop(4)

myList.insert(4, 'makes')

myList.insert(5, 'learning')

myList.insert(6, 'so much fun!')


print(myList)

Output:
6. slice
The slice operation is used to print a section of the list. The slice operation returns a

specific range of elements. It does not modify the original list.

Code:

print(myList[:4]) # prints from beginning to end index

print(myList[2:]) # prints from start index to end of list

print(myList[2:4]) # prints from start index to end index


print(myList[:]) # prints from beginning to end of list

Output:

7. reverse()
The reverse() operation is used to reverse the elements of the list. This method

modifies the original list. To reverse a list without modifying the original one, we use

the slice operation with negative indices. Specifying negative indices iterates the list

from the rear end to the front end of the list.


Code:

print(myList[::-1]) # does not modify the original list

myList.reverse() # modifies the original list


print(myList)

Output:

8. len()
The len() method returns the length of the list, i.e. the number of elements in the list.

Code:

print(len(myList))

Output:
9. min() & max()
The min() method returns the minimum value in the list. The max() method returns

the maximum value in the list. Both the methods accept only homogeneous lists, i.e.

list having elements of similar type.

Code:

print(min(myList))

Output:

Code:

print(min([1, 2, 3]))
print(max([1, 2, 3]))

Output:

10. count()
The function count() returns the number of occurrences of a given element in the list.
Code:

print(myList.count(3))

Output:

11. concatenate
The concatenate operation is used to merge two lists and return a single list. The +

sign is used to perform the concatenation. Note that the individual lists are not

modified, and a new combined list is returned.

Code:

yourList = [4, 5, 'Python', 'is fun!']


print(myList+yourList)

Output:

12. multiply
Python also allows multiplying the list n times. The resultant list is the original list

iterated n times.
Code:

print(myList*2)

Output:

13. index()
The index() method returns the position of the first occurrence of the given element. It

takes two optional parameters – the begin index and the end index. These parameters

define the start and end position of the search area on the list. When supplied, the

element is searched only in the sub-list bound by the begin and end indices. When not

supplied, the element is searched in the whole list.

Code:

print(myList.index('EduCBA')) # searches in the


whole list
print(myList.index('EduCBA', 0, 2)) # searches from 0th to

2nd position

Output:
14. sort()
The sort method sorts the list in ascending order. This operation can only be

performed on homogeneous lists, i.e. lists having elements of similar type.

Code:

yourList = [4, 2, 6, 5, 0, 1]

yourList.sort()
print(yourList)

Output:

15. clear()
This function erases all the elements from the list and empties them.

Code:

myList.sort()
print(myList)

Output:
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1,2,3] : print (x,end = ' ') 123 Iteration

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value


extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Note: Python does not have built-in support for Arrays, but Python Lists can be
used instead.

How to remove an item from the List in Python?


Method 1: Using del statement
The del statement is not a function of List. Items of the list can be deleted using del statement by
specifying the index of item (element) to be deleted.

# Python 3 code to
# remove an item from list

# using del statement

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

'Lily', 'Carnations']

print("Original List is :", lst)

# using del statement

# to delete item (Orchids at index 1)

# from the list

del lst[1]

print("After deleting the item :", lst)

Output:
Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
Method 2: Using remove()
We can remove an item from the list by passing the value of the item to be deleted as the parameter to
remove() function.

# Python 3 code to

# remove an item from list

# using function remove()


lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

'Lily', 'Carnations']

print("Original List is :", lst)

# using remove()

# to delete item ('Orchids')

# from the list

lst.remove('Orchids')

print("After deleting the item :", lst)

Output:
Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
Method 3: Using pop()
pop() is also a method of list. We can remove the element at the specified index and get the value of
that element using pop().

# Python 3 code to

# remove an item from list

# using function pop()

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',


'Lily', 'Carnations']

print("Original List is :", lst)

# using pop()

# to delete item ('Orchids' at index 1)

# from the list

a = lst.pop(1)

print("Item popped :", a)

print("After deleting the item :", lst)

Output –
Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
Item popped : Orchids
After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]

Python List Built-in functions


Python provides the following built-in functions, which can be used with the lists.

SN Function Description Example

1 cmp(list1, It compares the This method is not used in the


list2) elements of both the Python 3 and the above versions.
lists.

2 len(list) It is used to calculate L1 = [1,2,3,4,5,6,7,8]


print(len(L1))
the length of the list. 8
3 max(list) It returns the maximum L1 = [12,34,26,48,72]
print(max(L1))
element of the list. 72

4 min(list) It returns the minimum L1 = [12,34,26,48,72]


print(min(L1))
element of the list. 12

5 list(seq) It converts any sequence str = "Johnson"


s = list(str)
to the list. print(type(s))
<class list>

Strings
Strings can be defined as sequential collections of characters. This means that
the individual characters that make up a string are in a particular order from left
to right.

A string that contains no characters, often referred to as the empty string, is


still considered to be a string. It is simply a sequence of zero characters and is
represented by ‘’ or “” (two single or two double quotes with nothing in between).

Lists
A list is a sequential collection of Python data values, where each value is
identified by an index. The values that make up a list are called its elements.
Lists are similar to strings, which are ordered collections of characters, except
that the elements of a list can have any type and for any one list, the items can
be of different types.

There are several ways to create a new list. The simplest is to enclose the
elements in square brackets ( [ and ]).

[10, 20, 30, 40]


["spam", "bungee", "swallow"]

The first example is a list of four integers. The second is a list of three strings.
As we said above, the elements of a list don’t have to be the same type. The
following list contains a string, a float, an integer, and another list.

["hello", 2.0, 5, [10, 20]]


Convert List to String in Python with join()

The general approach you'll be using is the join() function, with a couple of
options to choose from. The function is invoked on a string denoting a
separator - and this separator will be added between all joined items.

Let's take a look at a list of characters that we'd like to join:


base_list = ['M', 'K', 'V', 'N', 'L', 'I', 'L', 'F', 'S', 'L', 'L', 'V']

The simplest way to join these into a single string is to just pass the list into
the join() function:
string = "".join(base_list)
print(string)

This results in:


MKVNLILFSLLV

We've joined a few characters, denoting the amino-acids present at the start
of the sequence of a protein found in the E. coli bacteria!

Each of these elements is of type str, so there's no issue in naturally putting


these into a string. Though, sometimes, you might want to convert a certain
element into a different type.

Additionally, if you use a different delimiter, you can get a different


representation as well:
string = ", ".join(base_list)

This results in:

M, K, V, N, L, I, L, F, S, L, L, V

Convert List to String in Python with List Comprehension

If you do have to convert the elements, you can simply use a list
comprehension:
string = "".join(str(element) for element in base_list)
Each element in the list is now passed through the str() function, which
converts them to a string. You can substitute this with any other function,
including custom ones. For instancec, let's create a function that capitalizes
each element in the 'off chance' an element isn't capitalized as it should be:
base_list = ['m', 'K', 'V', 'N', 'L', 'I', 'L', 'f', 'S', 'L', 'L', 'V']

def capitalize_char(char):
return char.upper()

string = "".join(capitalize_char(element) for element in base_list)

print(string)

m and f have been flipped to lowercase, which shouldn't have happened.


We've passed in the capitalize_char() function into the list comprehension,
returning the capitalized version of each element we've passed in. This results
in:
MKVNLILFSLLV

Convert List to String in Python with map()

Finally, for a more clean and easy way to pass elements through a function -
we can use map(). Generally, the map() function is used to map values of one
collection to another, typically using a different (or even reduced) format.

For instance, you could map each character to another list of booleans, where
each boolean represents if the character is uppercase or not.

Of course, you can also always do a 1-to-1 mapping using the map() function
and, well, just map a string to a string, joining them together into a single one:
base_list = ['M', 'K', 'V', 'N', 'L', 'I', 'L', 'F', 'S', 'L', 'L', 'V']

string = "".join(map(str, base_list))

print(string)

This results in:


MKVNLILFSLLV

Parsing Lines:
Python provides inbuilt functions for creating, writing, and reading files. There
are two types of files that can be handled in python, normal text files and binary
files (written in binary language, 0s, and 1s).
Using readlines()
readlines() is used to read all the lines at a single go and then return them as
each line 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 split it into separate lines. We
can iterate over the list and strip the newline ‘\n’ character using strip() function.

Example:
 Python3

# Python code to

# demonstrate readlines()

L = ["Geeks\n", "for\n", "Geeks\n"]

# writing to file

file1 = open('myfile.txt', 'w')

file1.writelines(L)

file1.close()

# Using readlines()

file1 = open('myfile.txt', 'r')


Lines = file1.readlines()

count = 0

# Strips the newline character

for line in Lines:

count += 1

print("Line{}: {}".format(count, line.strip()))

Output:

Line1: Geeks
Line2: for
Line3: Geeks

Using readline()
readline() function reads a line of the file and return it in the form of the string. It
takes a parameter n, which specifies the maximum number of bytes that will be
read. However, does not reads more than one line, even if n exceeds the length
of the line. It will be efficient when reading a large file because instead of
fetching all the data in one go, it fetches line by line. 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.

Example:
 Python3

# Python program to
# demonstrate readline()

L = ["Geeks\n", "for\n", "Geeks\n"]

# Writing to a file

file1 = open('myfile.txt', 'w')

file1.writelines((L))

file1.close()

# Using readline()

file1 = open('myfile.txt', 'r')

count = 0

while True:

count += 1

# Get next line from file

line = file1.readline()
# if line is empty

# end of file is reached

if not line:

break

print("Line{}: {}".format(count, line.strip()))

file1.close()

Output:
Line1 Geeks
Line2 for
Line3 Geeks

Using for loop


An iterable object is returned by open() function while opening a file. This final
way of reading in a file line-by-line includes iterating over a file object in a for
loop. Doing this we are taking advantage of a built-in Python function that
allows us to iterate over the file object implicitly using a for loop in a
combination with using the iterable object. This approach takes fewer lines of
code, which is always the best practice worthy of following.

Example:
 Python3

# Python program to
# demonstrate reading files

# using for loop

L = ["Geeks\n", "for\n", "Geeks\n"]

# Writing to file

file1 = open('myfile.txt', 'w')

file1.writelines(L)

file1.close()

# Opening file

file1 = open('myfile.txt', 'r')

count = 0

# Using for loop

print("Using for loop")

for line in file1:

count += 1
print("Line{}: {}".format(count, line.strip()))

# Closing files

file1.close()

Output:

Using for loop


Line1: Geeks
Line2: for
Line3: Geeks

With statement
In the above approaches, every time the file is opened it is needed to be closed
explicitly. If one forgets to close the file, it may introduce several bugs in the
code, i.e. many changes in files do not go into effect until the file is properly
closed. To prevent this with statement can be used. The With statement in
Python is used in exception handling to make the code cleaner and much more
readable. It simplifies the management of common resources like file streams.
Observe the following code example on how the use of with statement makes
the code cleaner. There is no need to call file.close() when using with the
statement. The with the statement itself ensures proper acquisition and release
of resources.

Example:
 Python3

# Python program to

# demonstrate with
# statement

L = ["Geeks\n", "for\n", "Geeks\n"]

# Writing to file

with open("myfile.txt", "w") as fp:

fp.writelines(L)

# using readlines()

count = 0

print("Using readlines()")

with open("myfile.txt") as fp:

Lines = fp.readlines()

for line in Lines:

count += 1
print("Line{}: {}".format(count, line.strip()))

# Using readline()

count = 0

print("\nUsing readline()")

with open("myfile.txt") as fp:

while True:

count += 1

line = fp.readline()

if not line:

break

print("Line{}: {}".format(count, line.strip()))

# Using for loop


count = 0

print("\nUsing for loop")

with open("myfile.txt") as fp:

for line in fp:

count += 1

print("Line{}: {}".format(count, line.strip()))

Output:

Using readlines()
Line1: Geeks
Line2: for
Line3: Geeks

Using readline()
Line1: Geeks
Line2: for
Line3: Geeks

Using for loop


Line1: Geeks
Line2: for
Line3: Geeks
Aliasing in Python
In python programming, the second name given to a piece of data is known as an alias.
Aliasing happens when the value of one variable is assigned to another variable because
variables are just names that store references to actual value.

Consider a following example:

first_variable = "PYTHON"
print("Value of first:", first_variable)
print("Reference of first:", id(first_variable))

print("--------------")

second_variable = first_variable # making an alias


print("Value of second:", second_variable)
print("Reference of second:", id(second_variable))

In the example above, first_variable is created first and then


string ‘PYTHON’ is assigned to it. Statement first_variable =
second_variable creates an alias
of first_variable because first_variable =
second_variable copies reference
of first_variable to second_variable.

To verify, let’s have look at the output of the above program:


Value of first_variable: PYTHON
Reference of first_variable: 2904215383152
--------------
Value of second_variable: PYTHON
Reference of second_variable: 2904215383152

From the output of the above program, it is clear that first_variable


and second_variable have the same reference id in memory.

So, both variables point to the same string object ‘PYTHON’.

And in Python programming, when the value of one variable is


assigned to another variable, aliasing occurs in which reference is
copied rather than copying the actual value.

Python function with Argument


List
In Python, Arguments in a function may be of any data types like list,
string, dictionary etc., Inside the function also it is treated as the same data
type.
If we give List as an argument to the function, it will consider the
argument as List even if it is inside the function. Let us give List as an
argument to the function and verify the results of it. For example, let us
give a list of class 5 students as an argument to the function names.
Python Code:
def names(students):
for x in students:
print(x)

class5 = ["naveen", "bhavana", "vamsi","priya"]


names(class5)
Output:
naveen
bhavana
vamsi
priya

How to pass a list as an argument in Python

Passing a list into a function allows that function to read and manipulate the list.

USE FUNCTION ARGUMENTS TO PASS A LIST AS AN ARGUMENT

Call a function and pass a list as an argument.

def append_to_list(input_list, element_to_append):


input_list.append(element_to_append)

sample_list = [0, 1]
append_to_list(sample_list, 2)

print(sample_list)
OUTPUT
[0, 1, 2]

You might also like