Python Unit-1
Python Unit-1
INTRODUCTION
INTRODUCTION TO PYTHON
Python
Today, Python is one of the most popular programming languages. Although it is a general-
purpose language, it is used in various areas of applications such as Machine Learning, Artificial
Intelligence, web development, IoT, and more.
This Python tutorial has been written for the beginners to help them understand the basic to
advanced concepts of Python Programming Language. After completing this tutorial, you will
find yourself at a great level of expertise in Python, from where you can take yourself to the next
levels to become a world class Software Engineer.
What is Python?
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level
programming language. Python is dynamically-typed and garbage-collected programming
language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source
code is also available under the GNU General Public License (GPL).
Python supports multiple programming paradigms, including Procedural, Object Oriented and
Functional programming language. Python design philosophy emphasizes code readability with
the use of significant indentation.
This tutorial gives a complete understanding of Python programming language starting from
basic conceopts to advanced concepts. This tutorial will take you through simple and practical
approaches while learning Python Programming language.
Python Jobs
Today, Python is very high in demand and all the major companies are looking for great Python
Programmers to develop websites, software components, and applications or to work with Data
Science, AI, and ML technologies. When we are developing this tutorial in 2022, there is a high
shortage of Python Programmers where as market demands more number of Python
Programmers due to it's application in Machine Learning, Artificial Intelligence etc.
Today a Python Programmer with 3-5 years of experience is asking for around $150,000 annual
package and this is the most demanding programming language in America. Though it can vary
depending on the location of the Job. It's impossible to list all of the companies using Python, to
name a few big companies are:
1
Google
Intel
NASA
PayPal
Facebook
IBM
Amazon
Netflix
Pinterest
Uber
Many more...
So, you could be the next potential employee for any of these major companies. We have
developed a great learning material for you to learn Python Programming which will help you
prepare for the technical interviews and certification exams based on Python. So, start learning
Python using this simple and effective tutorial from anywhere and anytime absolutely at your
pace.
Python is a MUST for students and working professionals to become a great Software Engineer
specially when they are working in Web Development Domain. I will list down some of the key
advantages of learning Python:
2
Python Online Compiler/Interpreter
We have provided Python Online Compiler/Interpreter which helps you
to Edit and Execute the code directly from your browser. Try to click the icon to run the
following Python code to print conventional "Hello, World!".
Below code box allows you to change the value of the code. Try to change the value
inside print() and run it again to verify the result.
Game developer
Web designer
Python developer
Full-stack developer
Machine learning engineer
Data scientist
Data analyst
Data engineer
DevOps engineer
Software engineer
Many more other roles
Characteristics of Python
Following are important characteristics of Python Programming −
3
Applications of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely used
language over the web. I'm going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
Target Audience
This tutorial has been prepared for the beginners to help them understand the basics to advanced
concepts of Python programming language. After completing this tutorial, you will find yourself
at a great level of expertise in Python programming, from where you can take yourself to the
next levels.
Prerequisites
Although it is a beginners tutorial, we assume that the readers have a reasonable exposure to any
programming environment and knowledge of basic concepts such as variables, commands,
syntax, etc.
4
Python History and Versions
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.
5
A list of Python versions with its released date is given below.
6
Tips to Keep in Mind While Learning Python
The most common question asked by the beginners - "What is the best way to learn
Python"? It is the initial and relevant question because first step in learning any programming
language is to know how to learn.
The proper way of learning will help us to learn fast and become a good Python developer.
In this section, we will discuss various tips that we should keep in mind while learning Python.
So, first figure out the motivation behind learning, which can anything be such as knowing
something new, develop projects using Python, switch to Python, etc. Below are the general
areas where Python is widely used. Pick any of them.
Choose any one or two areas according to your interest and start the journey towards learning
Python.
So it will take minimum amount of time to learning its syntax. Once we get its syntax properly,
further learning will be easier and quicker getting to work on projects.
Note - Learn Python 3, not Python 2.7, because the industry no longer uses it. Our Python tutorial is
based on its latest version Python 3.
7
3. Write Code by Own
Writing the code is the most effective and robust way to learn Python. First, try to write code on
paper and run in mind (Dry Run) then move to the system. Writing code on paper will help us
get familiar quickly with the syntax and the concept store in the deep memory. While writing the
code, try to use proper functions and suitable variables names.
There are many editors available for Python programming which highlights the syntax related
issue automatically. So we don't need to pay lot of attention of these mistakes.
4. Keep Practicing
The next important step is to do the practice. It needs to implementing the Python concepts
through the code. We should be consistence to our daily coding practice.
Consistency is the key of success in any aspect of life not only in programming. Writing code
daily will help to develop muscle memory.
We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It
may seem hard but muscle memory plays large part in programing. It will take us ahead from
those who believe only the reading concept of Python is sufficient.
Maintain own notes are also helped to learn fast. A study published in Psychological Science that
-
The students who were taking longhand notes in the studies were forced to be more selective —
because you can't write as fast as you can type.
8
7. Do small Projects
After understanding Python's basic concept, a beginner should try to work on small projects. It
will help to understand Python more deeply and become more component in it. Theoretical
knowledge is not enough to get command over the Python language. These projects can be
anything as long as they teach you something. You can start with the small projects such as
calculator app, a tic-toc-toe game, an alarm clock app, a to-do list, student or customer
management system, etc.
Once you get handy with a small project, you can easily shift toward your interesting domain
(Machine Learning, Web Development, etc.).
8. Teach Others
There is a famous saying that "If you want to learn something then you should teach other".
It is also true in case of learning Python. Share your information to other students via creating
blog posts, recording videos or taking classes in local training center. It will help us to enhance
the understanding of Python and explore the unseen loopholes in your knowledge. If you don't
want to do all these, join the online forum and post your answers on Python related questions.
There are many libraries in Python. Above, we have mentioned a few of them.
9
10. Contribute to Open Source
As we know, Python is an open source language that means it is freely available for everyone.
We can also contribute to Python online community to enhance our knowledge. Contributing to
open source projects is the best way to explore own knowledge. We also receive the feedback,
comments or suggestions for work that we submitted. The feedback will enable the best practices
for Python programming and help us to become a good Python developer.
Usage of Python
Python is a general purpose, open source, high-level programming language and also provides
number of libraries and frameworks. Python has gained popularity because of its simplicity, easy
syntax and user-friendly environment. The usage of Python as follows.
o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing
10
NEED OF PYTHON PROGRAMMING
11
.Net and C# compatible: IronPython
A version with C: CPython
Python combined with Ruby: RubyPython
Python integrated with Java: Jython
Python written with Objective C toolkits: PyObjc
7. High Salary: The salary of Python engineers is comparatively higher as compared to others
in the industry. In the United States, a Python developer earns an average of $116,028 per year.
8. Scripting and Automation: What most people don’t know about Python is that it can be
used as a scripting language. In scripting, the code is written in script form and gets executed.
So the code is read and interpreted by the machine and errors are checked during runtime.
After the code is checked, it can be used many times. It is also possible to automate specific
tasks in a problem by automation.
9. Artificial Intelligence: Without any dispute, Artificial intelligence is going to lead the
future IT. Python’s libraries such as Keras and TensorFlow enables machine learning
functionality. Also, libraries like OpenCV aids in computer vision or image recognition.
10. Computer Graphics: Python can be employed in small, large, online or offline projects. It
is used to develop GUI and desktop applications. It’s ‘Tkinter’ library enables simple and
rapid application development. This programming language is also used in game development
where the logic is written using a module ‘pygame’ which can also run on android devices.
11. Testing Framework: This language is an excellent tool for validating the products or ideas
for established enterprises. Python has numerous built-in testing frameworks that deal with
debugging and rapid workflows. Its tools and modules such as Selenium and Splinter work to
make things easier. Python also supports cross-platform and cross-browser testing with
frameworks like PyTest and Robot framework.
12. Web Development: Python’s different frameworks support website development. Python
has an array of frameworks for developing websites. Popular frameworks such as Django,
Flask, and Pylons are characterized by faster and stable code; this is because they are written in
Python.
FEATURES APPLICATIONS:
Features of Python:
Python is a High-level language. The following Features of Python listed below:
Simple : Python is a simple and small programming language. Reading a program of
python language feels almost like reading simple English. This is the main fact the
greatest strength of python which allows the programmer to concentrate on the solution
to the problem rather than the language itself.
Open Source: Python is an open-source software. Anyone can freely distribute it, read
the source code, and edit it easily.
12
High-level Language: When writing programs in python, the programmers don’t have to
worry about the low-level details like managing the memory used by the program. Python
is a High-level language that needed to concentrate on writing solutions to problems.
Interactive: Python programs work in an interactive mode which allows us interactive
testing and debugging of a piece of code. Most Programmers can easily interact with the
interpreter directly.
Object-Oriented: Python supports object-oriented as well as procedure-oriented
programming language. In Python, the OOP technique encapsulates data and
functionalities within objects.
Dynamic: Python executes dynamically, programs written in python can be copied.
Python used for the flexible development of applications.
Secure: Python language environment is much more secure than other languages like
C++ and Java. In Python, Modules can distribute to prevent altering the source code,
Apart from this, additional security checks can easily add to implement additional
security features.
Interpreted: Python is processed at run-time by the interpreter. So, there is no need to
compile a program before executing it. You can easily run the program. Generally,
Python converts the source code into an intermediate code that says called Bytecode.
Then it translated into the native language of your computer so that it can be executed.
Multi-threaded: Python supports multi-threading which is executing more than one
process of a program simultaneously. So, it allows programmers to perform process
management tasks.
Garbage Collection: Python run-time environment handles garbage collection of all
python objects.
Portable: Python is a portable language and the programs behave the same on a wide
variety of hardware platforms it has the same interface on all platforms. The programs
work on any operating system like Linux, Windows, MAC, Solaris etc.
Applications of Python:
Python is a high-level programming language that used to develop a wide range of
applications including image processing, text processing, enterprise-level applications,
web etc. The features and applications of python:
13
Example : World Best Search engine Google has been built using Python, World Best
Video Sharing site YouTube developed using Python, The front page of
internet reddit written in Python.
2. Embedded Scripting Language: Python is used as an embedded scripting language
for various types of testing, building, deployment, monitoring frameworks, scientific
apps, etc.
3. Image Processing: Python is used to make 2D imaging software such as GIMP, Paint
Shop Pro, etc.
Python also used in 3D to make 3D animation software packages such as 3Ds Max,
Maya, Blender, etc.
4. GUI-Based Applications: Python has a simple syntax, rich text processing, modular
architecture and the ability to work on multiple operating systems makes Python a
preferred choice for developers. Python is a GUI-based application so, it has various GUI
tool-kits are available like PyQt, wxPython, PyGtk. This tool kit helps developers to
create high function Graphical User Interface (GUI).
Python Keywords:
and assert break class continue def del elif else except
14
Python - Environment Setup
First step in the journey of learning Python is to install it on your machine. Today most computer
machines, especially having Linux OS, have Python pre-installed. However, it may not be the
latest version.
Python is available on a wide variety of platforms including Linux and Mac OS X. Let's
understand how to set up our Python environment.
Python has also been ported to the Java and .NET virtual machines
$ python
Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
15
You can download Python documentation from https://www.python.org/doc/. The
documentation is available in HTML, PDF, and PostScript formats.
Python distribution is available for a wide variety of platforms. You need to download only the
binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the source
code manually. Compiling the source code offers more flexibility in terms of choice of features
that you require in your installation.
$ python3.11 --version
In Ubuntu Linux, the easiest way to install Python is to use apt – Advanced Packaging Tool. It
is always recommended to update the list of packages in all the configured repositories.
Even after the update, the latest version of Python may not be available for install, depending
upon the version of Ubuntu you are using. To overcome this, add the deadsnakes repository.
To install the latest Python 3.11 version, enter the following command in the terminal −
$ python3
Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
16
>>> print ("Hello World")
Hello World
>>>
Red Hat Enterprise Linux (RHEL 8) does not install Python 3 by default. We usually use yum
command on CentOS and other related variants. The procedure for installing Python-3 on RHEL
8 is as follows:
The recommended way to install Python is to use the official installer. A link to the latest stable
version is given on the home page itself. It is also found
at https://www.python.org/downloads/windows/.
You can find embeddable packages and installers for 32 as well as 64-bit architecture.
17
Let us download 64-bit Windows installer −
(https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe)
Double click on the file where it has been downloaded to start the installation.
Although you can straight away proceed by clicking the Install Now button, it is advised to
choose the installation folder with a relatively shorter path, and tick the second check box to
update the PATH variable.
18
Accept defaults for rest of the steps in this installation wizard to complete the installation.
Open the Window Command Prompt terminal and run Python to check the success of
installation.
C:\Users\Acer>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Python's standard library has an executable module called IDLE – short for Integrated
Development and Learning Environment. Find it from Window start menu and launch.
19
IDLE contains Python shell (interactive interpreter) and a customizable multi-window text editor
with features such as syntax highlighting, smart indent, auto completion etc. It is cross-platform
so works the same on Windows, MacOS and Linux. It also has a debugger with provision to set
breakpoints, stepping, and viewing of global and local namespaces.
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date.
See http://www.python.org/download/mac/ for instructions on getting the current version along
with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3
(released in 2003), MacPython is available.
Jack Jansen maintains it and you can have full access to the entire documentation at his website
− http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac
OS installation.
20
Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a
search path that lists the directories that the OS searches for executables.
The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and other
programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive;
Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter from any
particular directory, you must add the Python directory to your path.
To add the Python directory to the path for a particular session in Unix −
In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.
In the bash shell (Linux) − type export PATH="$PATH:/usr/local/bin/python" and
press Enter.
In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter.
Note − /usr/local/bin/python is the path of the Python directory
PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where
1 to locate the module files imported into a program. It should include the
Python source library directory and the directories containing Python source
code. PYTHONPATH is sometimes preset by the Python installer.
21
PYTHONSTARTUP
2 It contains the path of an initialization file containing Python source code. It is
executed every time you start the interpreter. It is named as .pythonrc.py in
Unix and it contains commands that load utilities or modify PYTHONPATH.
PYTHONCASEOK
3 It is used in Windows to instruct Python to find the first case-insensitive match
in an import statement. Set this variable to any value to activate it.
PYTHONHOME
4 It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make switching
module libraries easy.
Running Python
There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line
interpreter or shell window.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
1 -d
It provides debug output.
2 -O
It generates optimized bytecode (resulting in .pyo files).
22
3 -S
Do not run import site to look for Python paths on startup.
4 -v
verbose output (detailed trace on import statements).
-X
5 disable class-based built-in exceptions (just use strings); obsolete starting with
version 1.6.
6 -c cmd
run Python script sent in as cmd string
7 file
run Python script from given file
If you are not able to set up the environment properly, then you can take help from your system
admin. Make sure the Python environment is properly set up and working perfectly fine.
23
BASIC SYNTAX OF PYTHON PROGRAMMING
Here's a basic overview of Python's syntax:
Comments: Comments start with the # character and are used to add explanations or
notes to your code. They are ignored by the interpreter.
# This is a comment
Variables: Variables are used to store data. You don't need to declare a variable's type
explicitly; Python infers it automatically.
x = 10 # Integer
Print: You can use the print() function to display data on the screen.
print("Hello, World!")
if x > 5:
else:
24
Conditional Statements: Python uses if, elif (else if), and else for conditional branching.
if condition:
elif another_condition:
else:
Loops: Python provides for and while loops for iterative operations.
for i in range(5):
print(i)
while x > 0:
print(x)
x -= 1
Data Structures: Python includes various data structures, such as lists, tuples,
dictionaries, and sets.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_set = {1, 2, 3}
25
Functions: Functions are defined using the def keyword.
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Classes and Objects: You can create classes and objects for object-oriented
programming.
class Person:
self.name = name
self.age = age
26
These are some of the fundamental elements of Python syntax. Python is a versatile language
used in web development, data analysis, machine learning, and more. Learning Python involves
exploring these concepts in more detail and building practical programs.
VARIABLES
What are Python Variables?
Python variables are the reserved memory locations used to store values with in a Python
Program. This means that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, Python interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to Python
variables, you can store integers, decimals or characters in these variables.
Data items belonging to different data types are stored in computer's memory. Computer's
memory locations are having a number or address, internally represented in binary form. Data is
also stored in binary form as the computer works on the principle of binary representation. In the
following diagram, a string May and a number 18 is shown as stored in memory locations.
If you know the assembly language, you will covert these data items and the memory address,
and give a machine language instruction. However, it is not easy
for everybody. Language translator such as Python interpreter performs this type of conversion.
It stores the object in a randomly chosen memory location. Python's built-in id() function returns
the address where the object is stored.
>>> "May"
May
>>> id("May")
2167264641264
>>> 18
27
18
>>> id(18)
140714055169352
Once the data is stored in the memory, it should be accessed repeatedly for performing a certain
process. Obviously, fetching the data from its ID is cumbersome. High level languages like
Python make it possible to give a suitable alias or a label to refer to the memory location.
In the above example, let us label the location of May as month, and location in which 18 is
stored as age. Python uses the assignment operator (=) to bind an object with the label.
>>> month="May"
>>> age=18
The data object (May) and its name (month) have the same id(). The id() of 18 and age are also
same.
>>> id(month)
2167264641264
>>> id(age)
140714055169352
The label is an identifier. It is usually called as a variable. A Python variable is a symbolic name
that is a reference or pointer to an object.
The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator is the value stored in the variable. For example −
28
Printing Python Variables
Once we create a Python variable and assign a value to it, we can print it using print() function.
Following is the extension of previous example and shows how to print different variables in
Python:
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles, and name variables,
respectively. When running the above Python program, this produces the following result –
100
1000.0
Zara Ali
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Example
Following examples shows how we can delete a variable and if we try to use a deleted variable
then Python interpreter will throw an error:
counter = 100
print (counter)
29
del counter
print (counter)
100
Traceback (most recent call last):
File "main.py", line 7, in <module>
print (counter)
NameError: name 'counter' is not defined
>>> a=10
>>> b=10
>>> c=10
>>> a=b=c=10
>>> print (a,b,c)
10 10 10
>>> a=10
>>> b=20
>>> c=30
These separate assignment statements can be combined in one. You need to give comma
separated variable names on left, and comma separated values on the right of = operator.
30
a = b = c = 100
print (a)
print (b)
print (c)
100
100
100
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For example
−
print (a)
print (b)
print (c)
1
2
Zara Ali
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "Zara Ali" is assigned to the variable c.
31
Python variable names are case-sensitive which means Name and NAME are two
different variables in Python.
Python reserved keywords cannot be used naming the variable.
If the name of variable contains multiple words, we should use these naming patterns −
Camel case − First letter is a lowercase, but first letter of each subsequent word is in
uppercase. For example: kmPerHour, pricePerLitre
Pascal case − First letter of each word is in uppercase. For example: KmPerHour,
PricePerLitre
Snake case − Use single underscore (_) character to separate words. For example:
km_per_hour, price_per_litre
Example
counter = 100
_count = 100
name1 = "Zara"
name2 = "Nuha"
Age = 20
zara_salary = 100000
print (counter)
print (_count)
print (name1)
print (name2)
print (Age)
print (zara_salary)
100
100
Zara
Nuha
20
100000
Example
32
Following are invalid Python variable names:
1counter = 100
$_count = 100
zara-salary = 100000
print (1counter)
print ($count)
print (zara-salary)
Example
Once you use a variable to identify a data object, it can be used repeatedly without its id() value.
Here, we have a variables height and width of a rectangle. We can compute the area and
perimeter with these variables.
>>> width=10
>>> height=20
>>> area=width*height
>>> area
200
>>> perimeter=2*(width+height)
>>> perimeter
60
Use of variables is especially advantageous when writing scripts or programs. Following script
also uses the above variables.
#! /usr/bin/python3
width = 10
height = 20
33
area = width*height
perimeter = 2*(width+height)
print ("Area = ", area)
print ("Perimeter = ", perimeter)
Save the above script with .py extension and execute from command-line. The result would be −
Area = 200
Perimeter = 60
Constants in Python
Python doesn't have any formally defined constants, However you can indicate a variable to be
treated as a constant by using all-caps names with underscores. For example, the name
PI_VALUE indicates that you don't want the variable redefined or changed in any way.
The naming convention using all-caps is sometimes referred to as screaming snake case - where
the all-caps (screaming) and the underscores (snakes).
The concept of variable works differently in Python than in C/C++. In C/C++, a variable is a
named memory location. If a=10 and also b=10, both are two different memory locations. Let us
assume their memory address is 100 and 200 respectively.
If a different value is assigned to "a" - say 50, 10 in the address 100 is overwritten.
34
A Python variable refers to the object and not the memory location. An object is stored in
memory only once. Multiple variables are really the multiple labels to the same object.
The statement a=50 creates a new int object 50 in the memory at some other location, leaving the
Further, if you assign some other value to b, the object 10 remains unreferred.
Python's garbage collector mechanism releases the memory occupied by any unreferred object.
Python's identity operator is returns True if both the operands have same id() value.
>>> a=b=10
>>> a is b
True
>>> id(a), id(b)
(140731955278920, 140731955278920)
35
Python - Data Types
Computer is a data processing device. Computer stores the data in its memory and
processes it as per the given program. Data is a representation of facts about a certain
object.
Data of books in library − title, author, publisher, price, pages, year of publication etc.
Data type represents a kind of value and determines what operations can be done
on it. Numeric, non-numeric and Boolean (true/false) data are the most obvious data
types. However, each programming language has its own classification largely reflecting
its programming philosophy.
Python Data Types are used to define the type of a variable. It defines what type
of data we are going to store in a variable. The data stored in memory can be of many
types. For example, a person's age is stored as a numeric value and his or her address is
stored as alphanumeric characters.
Python has various built-in data types which we will discuss with in this tutorial:
String - str
Mapping - dict
36
Boolean - bool
None - NoneType
data_types
Python numeric data types store numeric values. Number objects are created when you
assign a value to them. For example −
Python supports four different numerical types and each of them have built-in classes in
Python library, called int, bool, float and complex respectively −
Python's standard library has a built-in function type(), which returns the class of the
given object. Here, it is used to check the type of an integer and floating point number.
>>> type(123)
<class 'int'>
>>> type(9.99)
37
<class 'float'>
A complex number is made up of two parts - real and imaginary. They are separated by
'+' or '-' signs. The imaginary part is suffixed by 'j' which is the imaginary number. The
square root of -1 (−1−−−√), is defined as imaginary number. Complex number in Python
is represented as x+yj, where x is the real part, and y is the imaginary part. So, 5+6j is a
complex number.
>>> type(5+6j)
<class 'complex'>
A Boolean number has only two possible values, as represented by the keywords, True
and False. They correspond to integer 1 and 0 respectively.
<class 'bool'>
>>> type(False)
<class 'bool'>
Examples
38
Example
Following is an example to show the usage of Integer, Float and Complex numbers:
# integer variable.
a=100
# boolean variable.
b=True
# float variable.
c=20.345
# complex variable.
d=10+3j
39
Python sequences are bounded and iterable - Whenever we say an iterable in Python, it
means a sequence data type (for example, a list).
>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'
A string in Python is an object of str class. It can be verified with type() function.
<class 'str'>
40
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator in Python. For example −
Hello World!
llo
llo World!
Hello World!TEST
Python Lists are the most versatile compound data types. A Python list contains items
separated by commas and enclosed within square brackets ([]). To some extent, Python
lists are similar to arrays in C. One difference between them is that all the items
belonging to a Python list can be of different data type where as C array can store
elements related to a particular data type.
41
>>> [2023, "Python", 3.11, 5+6j, 1.23E-4]
A list in Python is an object of list class. We can check it with type() function.
<class 'list'>
As mentioned, an item in the list may be of any data type. It means that a list object can
also be an item in another list. In that case, it becomes a nested list.
A list can have items which are simple numbers, strings, tuple, dictionary, set or object of
user defined class also.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. For example −
42
This produce the following result −
abcd
[786, 2.23]
Python tuple is another sequence data type that is similar to a list. A Python tuple consists
of a number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses (...).
A tuple is also a sequence, hence each item in the tuple has an index referring to its
position in the collection. The index starts from 0.
In Python, a tuple is an object of tuple class. We can check it with the type() function.
<class 'tuple'>
As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any
other Python class.
To form a tuple, use of parentheses is optional. Data items separated by comma without
any enclosing symbols are treated as a tuple by default.
43
>>> 2023, "Python", 3.11, 5+6j, 1.23E-4
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed .ie lists are mutable, while tuples are enclosed
in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can be thought of as
read-only lists. For example −
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
abcd
(786, 2.23)
44
The following code is invalid with tuple, because we attempted to update a tuple, which
is not allowed. Similar case is possible with lists −
We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:
Examples
for i in range(5):
print(i)
45
This produce the following result −
Now let's modify above program to print the number starting from 1 instead of 0:
Again, let's modify the program to print the number starting from 1 but with an increment
of 2 instead of 1:
print(i)
46
Python Dictionary Data Type
Python dictionaries are kind of hash table type. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Python dictionary is like associative arrays or hashes found in Perl and consist of
key:value pairs. The pairs are separated by comma and put inside curly brackets {}. To
establish mapping between key and value, the semicolon':' symbol is put between the
two.
In Python, dictionary is an object of the built-in dict class. We can check it with the
type() function.
<class 'dict'>
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]). For example −
dict = {}
47
print (tinydict.values()) # Prints all the values
This is one
This is two
Python's dictionary is not a sequence. It is a collection of items but each item (key:value
pair) is not identified by positional index as in string, list or tuple. Hence, slicing
operation cannot be done on a dictionary. Dictionary is a mutable object, so it is possible
to perform add, modify or delete actions with corresponding functionality defined in dict
class. These operations will be explained in a subsequent chapter.
Comma separated items in a set are put inside curly brackets or braces {}. Items in the set
collection can be of different data types.
Note that items in the set collection may not follow the same order in which they are
entered. The position of items is optimized by Python to perform operations over set as
defined in mathematics.
48
Python’s Set is an object of built-in set class, as can be checked with the type()
function.
<class 'set'>
A set can store only immutable objects such as number (int, float, complex or bool),
string or tuple. If you try to put a list or a dictionary in the set collection, Python raises a
TypeError.
Even if a set doesn't allow mutable items, the set itself is mutable. Hence,
add/delete/update operations are permitted on a set object, using the methods in built-in
set class. Python also has a set of operators to perform set manipulation. The methods and
operators are explained in latter chapters
Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows you to evaluate the value of any
expression and returns either True or False based on the expression.
Examples
49
a = True
print(a)
print(type(a))
true
<class 'bool'>
Following is another program which evaluates the expressions and prints the return
values:
a=2
b=4
print(bool(a==b))
print(a==b)
a = None
print(bool(a))
50
a = ()
print(bool(a))
# Returns false as a is 0
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))
False
False
False
False
False
True
Python Keywords
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any Python
program are Python keywords.
This tutorial will give you a basic overview of all Python keywords and a detailed discussion of
some important keywords that are frequently used.
51
Introducing Python Keywords
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions. You'll never need to import any keyword into your program
because they're permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as keywords.
Assigning a particular meaning to Python keywords means you can't use them for other purposes
in our code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to
assign anything to a built-in method or type, you will not receive a SyntaxError message;
however, it is still not a smart idea.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.
In distinct versions of Python, the preceding keywords might be changed. Some extras may be
introduced, while others may be deleted. By writing the following statement into the coding
window, you can anytime retrieve the collection of keywords in the version you are working on.
Code
52
Output:
Code
help("keywords")
53
how keywords are employed and will assist you in arranging the huge collection of Python
keywords.
o A few terms mentioned in the segment following may be unfamiliar to you. They're
explained here, and you must understand what they mean before moving on:
o The Boolean assessment of a variable is referred to as truthfulness. A value's truthfulness
reveals if the value of the variable is true or false.
In the Boolean paradigm, truth refers to any variable that evaluates to true. Pass an item as an
input to bool() to see if it is true. If True is returned, the value of the item is true. Strings and lists
which are not empty, non-zero numbers, and many other objects are illustrations of true values.
False refers to any item in a Boolean expression that returns false. Pass an item as an input to
bool() to see if it is false. If False is returned, the value of the item is false. Examples of false
values are " ", 0, { }, and [ ].
These keywords are typed in lowercase in conventional computer languages (true and false);
however, they are typed in uppercase in Python every time. In Python script, the True Python
keyword represents the Boolean true state. False is a keyword equivalent to True, except it has
the negative Boolean state of false.
True and False are those keywords that can be allocated to variables or parameters and are
compared directly.
Code
print( 4 == 4 )
print( 6 > 9 )
print( True or False )
print( 9 <= 28 )
print( 6 > 9 )
print( True and False )
Output:
54
True
False
True
True
False
False
Because the first, third, and fourth statements are true, the interpreter gives True for those and
False for other statements. True and False are the equivalent in Python as 1 & 0. We can use the
accompanying illustration to support this claim:
Code
print( True == 3 )
print( False == 0 )
print( True + True + True)
Output:
False
True
3
None is a Python keyword that means "nothing." None is known as nil, null, or undefined in
different computer languages.
If a function does not have a return clause, it will give None as the default output:
Code
print( None == 0 )
print( None == " " )
print( None == False )
A = None
B = None
print( A == B )
Output:
False
False
False
True
55
If a no_return_function returns nothing, it will simply return a None value. None is delivered by
functions that do not meet a return expression in the program flow. Consider the following
scenario:
Code
def no_return_function():
num1 = 10
num2 = 20
addition = num1 + num2
number = no_return_function()
print( number )
Output:
This program has a function with_return that performs multiple operations and contains a return
expression. As a result, if we display a number, we get None, which is given by default when
there is no return statement. Here's an example showing this:
Code
number = with_return( 67 )
print( number )
Output:
56
OR, ∨ || or
NOT, ¬ ! not
CONTAINS, ∈ in
IDENTITY === is
Writers created Python programming with clarity in mind. As a result, many operators in other
computer languages that employ characters in Python are English words called keywords.
The Python keyword and determines whether both the left-hand side and right-hand side
operands and are true or false. The outcome will be True if both components are true. If one is
false, the outcome will also be False:
X Y X and Y
It's worth noting that the outcomes of an and statement aren't always True or False. Due to and's
peculiar behavior, this is the case. Instead of processing the inputs to corresponding Boolean
values, it just gives <component1> if it is false or <component2> if it is true. The outputs of a
and expression could be utilized with a conditional if clause or provided to bool() to acquire an
obvious True or False answer.
The or Keyword
The or keyword in Python is utilized to check if, at minimum, 1 of the inputs is true. If the first
argument is true, the or operation yields it; otherwise, the second argument is returned:
<component1> or <component2>
57
Similarly to the and keyword, the or keyword does not change its inputs to corresponding
Boolean values. Instead, the outcomes are determined based on whether they are true or false.
X Y X or Y
The not keyword in Python is utilized to acquire a variable's contrary Boolean value:
The not keyword is employed to switch the Boolean interpretation or outcome in conditional
sentences or other Boolean equations. Not, unlike and, and or, determines the specific Boolean
state, True or False, afterward returns the inverse.
X not X
True False
False True
Code
Output:
False
True
False
58
The in Keyword
<an_element> in <a_container>
Testing for a certain character in a string is a nice illustration of how to use the in keyword:
Code
container = "Javatpoint"
print( "p" in container )
print( "P" in container )
Output:
True
False
Lists, dictionaries, tuples, strings, or any data type with the method __contains__(), or we can
iterate over it will work with the in keyword.
The is Keyword
In Python, it's used to check the identification of objects. The == operation is used to determine
whether two arguments are identical. It also determines whether two arguments relate to the
unique object.
When the objects are the same, it gives True; otherwise, it gives False.
Code
Output:
True
False
False
59
True
True, False, and None are all the same in Python since there is just one version.
Code
print( [] == [] )
print( [] is [] )
print( {} == {} )
print( {} is {} )
Output:
True
False
True
False
A blank dictionary or list is the same as another blank one. However, they aren't identical entities
because they are stored independently in memory. This is because both the list and the dictionary
are changeable.
Code
Output:
True
True
Strings and tuples, unlike lists and dictionaries, are unchangeable. As a result, two equal strings
or tuples are also identical. They're both referring to the unique memory region.
Code
60
def the_outer_function():
var = 10
def the_inner_function():
nonlocal var
var = 14
print("The value inside the inner function: ", var)
the_inner_function()
print("The value inside the outer function: ", var)
the_outer_function()
Output:
The the_outer_function has a variable named var. Var is not a global variable, as you may have
noticed. As a result, if we wish to change it inside the the_inner_function(), we should declare it
using nonlocal.As a result, the variable was effectively updated within the nested
the_inner_function, as evidenced by the results. The following is what happens if you don't use
the nonlocal keyword:
Code
def the_outer_function():
var = 10
def the_inner_function():
var = 14
print("Value inside the inner function: ", var)
the_inner_function()
print("Value inside the outer function: ", var)
the_outer_function()
Output:
61
Iteration Keywords: for, while, break, continue
The iterative process and looping are essential programming fundamentals. To generate and
operate with loops, Python has multiple keywords. These would be utilized and observed in
almost every Python program. Knowing how to use them correctly can assist you in becoming a
better Python developer.
The for loop is by far the most popular loop in Python. It's built by blending two Python
keywords. They are for and in, as previously explained.
Python's while loop employs the term while and functions similarly to other computer languages'
while loops. The block after the while phrase will be repeated repeatedly until the condition
following the while keyword is false.
If you want to quickly break out of a loop, employ the break keyword. We can use this keyword
in both for and while loops.
You can use the continue Python keyword if you wish to jump to the subsequent loop iteration.
The continue keyword, as in many other computer languages, enables you to quit performing the
present loop iteration and go on to the subsequent one.
Code
# looping from 1 to 15
62
i = 0 # initial condition
while i < 15:
# When i has value 9, loop will jump to next iteration using continue. It will not print
if i == 9:
i += 3
continue
else:
# when i is not equal to 9, adding 2 and printing the value
print( i + 2, end = " ")
i += 1
Output:
4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 14 15 16
except: As previously stated, this operates in conjunction with "try" to handle exceptions.
finally: Whatever the outcome of the "try" section, the "finally" box is implemented every time.
assert: This method is used to help in troubleshooting. Often used to ensure that code is correct.
Nothing occurs if an expression is interpreted as true; however, if it is false, "AssertionError" is
raised. An output with the error, followed by a comma, can also be printed.
Code
63
# Exception raised in the try section
try:
d = var1 // var2 # this will raise a "divide by zero" exception.
print( d )
# this section will handle exception raised in try block
except ZeroDivisionError:
print("We cannot divide by zero")
finally:
# If exception is raised or not, this block will be executed every time
print("This is inside finally block")
# by using assert keyword we will check if var2 is 0
print ("The value of var1 / var2 is : ")
assert var2 != 0, "Divide by 0 error"
print (var1 / var2)
Output:
Let's say we possess a function that has not been coded yet however we wish to do so in the long
term. If we write just this in the middle of code,
Code
Output:
64
def function_pass( arguments ):
^
IndentationError: expected an indented block after function definition on line 1
as shown, IndentationError will be thrown. Rather, we use the pass command to create a blank
container.
Code
Code
class passed_class:
pass
The None keyword is returned by default if we don't specifically return a value. The
accompanying example demonstrates this.
Code
def func_with_return():
var = 13
return var
def func_with_no_return():
var = 10
print( func_with_return() )
print( func_with_no_return() )
Output:
13
None
65
The del Keyword
The del keyword is used to remove any reference to an object. In Python, every entity is an
object. We can use the del command to remove a variable reference.
Code
var1 = var2 = 5
del var1
print( var2 )
print( var1 )
Output:
5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [42], in ()
2 del var1
3 print( var2 )
----> 4 print( var1 )
We can notice that the variable var1's reference has been removed. As a result, it's no longer
recognized. However, var2 still exists.
Deleting entries from a collection like a list or a dictionary is also possible with del:
Code
list_ = ['A','B','C']
del list_[2]
print(list_)
Output:
['A', 'B']
66
Input and Output in Python
Sometimes a developer might want to take user input at some point in the program. To do
this Python provides an input() function.
Syntax:
input('prompt')
where prompt is an optional string that is displayed on the string at the time of taking
input.
# Output
print(type(name))
Output:
Hello, GFG
<class 'str'>
Note: Python takes all the input as a string input by default. To convert it to any other
data type we have to convert the input explicitly. For example, to convert the input to int
or float we have to use the int() and float() method respectively.
67
Example 2: Integer input in Python
add = num + 1
# Output
print(add)
Output:
Enter a number: 25
26
we can take multiple inputs of the same data type at a time in python, using map()
method in python.
print(a, b, c)
Output :
How take inputs for the Sequence Data Types like List, Set, Tuple, etc.
In the case of List and Set the input can be taken from the user in two ways.
68
Taking List/Set elements one by one by using the append()/add() methods.
Take the elements of the List/Set one by one and use the append() method in the case of
List, and add() method in the case of a Set, to add the elements to the List / Set.
List = list()
Set = set()
List.append(int(input()))
Set.add(int(input()))
print(List)
print(Set)
69
Enter the List elements :
[9, 0, 1, 3]
{9, 2, 1}
print(List)
print(Set)
Output :
[3, 4, 8, 9, 0, 11]
70
{34, 230, 234, 88, 123}
We know that tuples are immutable, there are no methods available to add elements to
tuples. To add a new element to a tuple, first type cast the tuple to the list, later append
the element to the list, and again type cast list back to a tuple.
T = (2, 3, 4, 5, 6)
print(T)
L = list(T)
T = tuple(L)
print(T)
Output :
(2, 3, 4, 5, 6)
(2, 3, 4, 5, 6, 35)
Python provides the print() function to display output to the standard output devices.
71
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
# print() method
print("GFG")
Output
GFG
GFG
In the above example, we can see that in the case of the 2nd print statement there is a
space between every letter and the print statement always add a new line character at the
72
end of the string. This is because after every character the sep parameter is printed and at
the end of the string the end parameter is printed. Let’s try to change this sep and end
parameter.
Example: Python Print output with custom sep and end parameter
# print() method
Output
GFG@G#F#G
Formatting Output
Formatting output in Python can be done in many ways. Let’s discuss them below
We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python expressions
between { and } that can refer to a variable or any literal value.
# Declaring a variable
name = "Gfg"
# Output
73
print(f'Hello {name}! How are you?')
Output:
Using format()
We can also use format() function to format our output to make it look presentable. The
curly braces { } work as placeholders. We can specify the order in which variables occur
in the output.
# Initializing variables
a = 20
b = 10
# addition
sum = a + b
# subtraction
sub = a- b
# Output
Output:
74
The value of a is 20 and b is 10
Using % Operator
We can use ‘%’ operator. % values are replaced with zero or more value of elements. The
formatting using % is similar to that of ‘printf’ in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
Example:
add = num + 5
# Output
Output:
Enter a value: 50
The sum is 55
75
Indentation in Python
Indentation is a very important concept of Python because without properly indenting the
Python code, you will end up seeing IndentationError and the code will not get compiled.
Python Indentation
Python indentation refers to adding white space before a statement to a particular block of
code. In another word, all the statements with the same space to the right, belong to
the same code block.Indentation-python
Statement (line 1), if condition (line 2), and statement (last line) belongs to the same
block which means that after statement 1, if condition will be executed. and suppose the
if condition becomes False then the Python will jump to the last statement for execution.
The nested if-else belongs to block 2 which means that if nested if becomes False, then
Python will execute the statements inside the else condition.
Statements inside nested if-else belong to block 3 and only one statement will be
executed depending on the if-else condition.
Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code. A block is a combination of all these statements.
Block can be regarded as the grouping of statements for a specific purpose. Most
programming languages like C, C++, and Java use braces { } to define a block of code.
Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the
same block of code. If a block has to be more deeply nested, it is simply indented further
to the right. You can understand it better by looking at the following lines of code.
Example 1
The lines print(‘Logging on to geeksforgeeks…’) and print(‘retype the URL.’) are two
separate code blocks. The two blocks of code in our example if-statement are both
76
indented four spaces. The final print(‘All set!’) is not indented, so it does not belong to
the else block.
# indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
Output:
Logging on to geeksforgeeks...
All set !
Example 2
To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is
required for indicating what block of code a statement belongs to. For example, j=1 and
while(j<=5): is not indented, and so it is not within the Python while block. So, Python
code structures by indentation.
j=1
while(j<= 5):
print(j)
77
j=j+1
Output:
Note: Python uses 4 spaces as indentation by default. However, the number of spaces is
up to you, but a minimum of 1 space has to be used.
SCRIPT STRUCTURE
Python is a high-level, interpreted programming language that is easy to learn and use. It
has a simple and easy-to-understand syntax that emphasizes readability and reduces the
cost of program maintenance. The basic structure of a Python program consists of the
following components:
Comments: Comments are used to explain the purpose of the code or to make notes for
other programmers. They start with a ‘#’ symbol and are ignored by the interpreter.
Import Statements: Import statements are used to import modules or libraries into the
program. These modules contain predefined functions that can be used to accomplish
tasks.
Variables: Variables are used to store data in memory for later use. In Python, variables
do not need to be declared with a specific type.
Data Types: Python supports several built-in data types including integers, floats,
strings, booleans, and lists.
78
Operators: Operators are used to perform operations on variables and data. Python
supports arithmetic, comparison, and logical operators.
Control Structures: Control structures are used to control the flow of a program. Python
supports if-else statements, for loops, and while loops.
Functions: Functions are used to group a set of related statements together and give them
a name. They can be reused throughout a program.
Classes: Classes are used to define objects that have specific attributes and methods.
They are used to create more complex data structures and encapsulate code.
Exceptions: Exceptions are used to handle errors that may occur during the execution of
a program.
Overall, the basic structure of a Python program consists of these components working
together to accomplish a specific task or solve a particular problem.
Here’s an example of a simple Python program that demonstrates the basic structure of
Python:
# This is a comment
# Defining variables
x = 10
y = "Hello, World!"
z = True
result = x + 5
79
if z:
print(y)
else:
print(result)
# Defining a function
def greet(name):
greet("Alice")
In this example, we start with a comment that explains the purpose of the code. Then, we
import the random module to generate random numbers later in the program.
Next, we define three variables with different data types: x is an integer, y is a string, and
z is a boolean. We then perform an arithmetic operation on x and store the result in the
result variable.
We use an if-else statement to check the value of z. If z is True, we print the string stored
in y, otherwise, we print the value of result.
Finally, we define a function called greet() that takes a parameter called name and prints
a greeting message. We call the function with the argument "Alice" to print "Hello,
Alice!" to the console.
80
RUNNING PYTHON SCRIPTS
Python is a well-known high-level programming language. The Python script is basically
a file containing code written in Python. The file containing Python script has the
extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a Windows
machine. In this article, we will learn how to run a Python program. To run a Python
script, we need a Python interpreter that needs to be downloaded and installed.
Here are the ways using which we can run a Python script.
Interactive Mode
Command Line
IDE (PyCharm)
print('Hello World!')
Here, the print() function is to print out any text written within the parenthesis. We can
write the text that we want to be printed using either a single quote as shown in the above
script or a double quote.
If you are coming from any other language then you will also notice that there is no
semicolon at the end of the statement as, with Python, you do not need to specify a
semicolon at the end of the line. And also we don’t need to include or import any files to
run a simple Python script.
There are various ways to run a Python script but before going toward the different ways
to run a Python script, we first have to check whether a Python interpreter is installed on
the system or not. So in Windows, open ‘cmd’ (Command Prompt) and type the
following command.
81
python -V
This command will give the version number of the Python interpreter installed or will
display an error if otherwise.
In Python Interactive Mode, you can run your script line by line in a sequence. To enter
an interactive mode, you will have to open Command Prompt on your Windows machine
and type ‘python’ and press Enter.
Output:
82
Example 2: Run the following lines one by one in the interactive mode.
name = "Aakash"
Output:
Example 3: Run the following line one by one in the interactive mode.
a=1
b=3
if a > b:
print("a is Greater")
else:
print("b is Greater")
83
Output:
Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and
then press Enter.
To run a Python script store in a ‘.py’ file in the command line, we have to write ‘python’
keyword before the file name in the command prompt.
python hello.py
Output:
84
Running Python Scripts using a Text Editor
To run Python script on a text editor like VS Code (Visual Studio Code) then you will
have to do the following:
Go to the extension section or press ‘Ctrl+Shift+X’ on Windows, then search and install
the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that.
Now, create a new file with the name ‘hello.py’ and write the below code in it:
print('Hello World!')
Then, right-click anywhere in the text area and select the option that says ‘Run Code’ or
press ‘Ctrl+Alt+N’ to run the code.
Output:
Select the root directory with the project name we specified in the last step. Right-click
on it, go to New, anto, and click on the ‘Python file’ option. Then give the name of the
file as ‘hello’ (you can specify any name as per your project requirement). This will
create a ‘hello.py’ file in the project root directory.
85
Note: You don’t have to specify the extension as it will take it automatically.
To run this Python script, Right click and select the ‘Run File in Python Console’ option.
This will open a console box at the bottom and show the output there. We can also run
using the Green Play Button at the top right corner of the IDE.
Output:
86