Python Programming
Python is an easy,general purpose, object-oriented, high level, and
interpreted programming [Link] is used to develop console based,GUI
based, Audio/Vedio based,Web based and many [Link] also used in Data
Science, Machine Learning and etc,..
Content/Topics of Python Programming :
PYTHON BASICS
Introduction to Python
Python Installation
Comments in Python
IO Operations in Python
Variables in Python
Data Types in Python
Typecasting in Python
Operators in Python
ConditionalStatements in Python
Loop Statements in Python
Break & Continue statements in Python
PYTHON SEQUENCES
Strings in in Python
Lists in Python
Tuples in Python
Sets in Python
Dictionarys in Python
FILES IN PYTHON
Files: Built-in Function & Methods
Command-Line Arguments
File System
EXCEPTIONS IN PYTHON
Exceptions
Exception handling
Raise & Assert Statement
MODULES IN PYTHON
Functions
Modules
Namespaces
Packages
REGULAR EXPRESSIONS IN PYTHON
Regular Expressions
RegEx Module
Introduction to Pyhton
Python is a general purpose, high-level, interpreted programming language developed
by Guido van Rossum in the late 1980s at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
Python is one of the most popular and widely used programming language used for set
of tasks including console based, GUI based, web programming and data analysis.
Python is a easy to learn and simple programming language so even if you are new to
programming, you can learn python without facing any problems.
Fact: Python is named after the comedy television show Monty Python's Flying Circus.
Python Applications
Start Programming with Python
Installation of Python
Features of Python
Python provides lots of features that are listed below.
Easy to Learn and Use
Python is easy to learn and use compared with other programming languages. It is
developer-friendly and high level programming language.
Interpreted Language
Python is an interpreted language because no need of compilation. This makes
debugging easy and thus suitable for beginners.
Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and
Macintosh etc. So, we can say that Python is a portable language.
Free and Open Source
The Python interpreter is developed under an open-source license, making it free to
install, use, and distribute.
Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come
into existence.
GUI Programming Support
Graphical user interfaces can be developed using Python.
Integrated
It can be easily integrated with languages like C, C++, and JAVA etc.
Python Applications
Python is a general purpose programming language that makes it applicable in almost all domains of software
development. Python as a whole can be used to develop any type of applications.
Here, we are providing some specific application areas where python can be applied.
Web Applications
Desktop GUI Applications
Software Development
Scientific and Numeric
Business Applications
Console Based Application
Audio or Video based Applications
Strat Programming with Python
To start programming with python, we have to know some more information. I.e, installation of python software
and execution procedure of python program or script.
There are two major Python versions, those are Python 2 and Python 3. Python 2 and 3 are quite different. This
tutorial uses Python 3, because it more semantically correct and supports newer features.
For installation of python software procedure go through ✍ Python Installation Tutorial
After successful installation of python software we can able interpret or execute python script / program.
Python provides us the two ways to run a python script:
Using Interactive interpreter prompt
Using a script file
⇨Using Interactive interpreter prompt:
Python provides us the feature to execute the python statement one by one at the interactive prompt. It is
preferable in the case where we are concerned about the output of each line of our python program.
To open the interactive mode, open the terminal (or command prompt) and type python (python3 in case if you
have python2 and python3 both installed on your system).
Through Command Prompt :
(or)
In windows, search for python IDLE in all programs and then click on python IDLE, then the python interpreter
prompt will open.
The Python interpreter prompt look like this
⇨Using Script File :
Interpreter prompt is good to run the individual statements of the code. However if we want to execute multiple
python statements at a time instead of executing one by one, then we can use script file.
We need to write our script into a file which can be executed later. For this purpose, open an editor like
notepad, create a file named [Link] (python used .py extension) and write the python script in it.
Example: "[Link]"
print("Hello !")
print("Welcome to Python Programming")
Output: $python3 [Link]
Hello !
Welcome to Python Programming
nstallation of Pyhton
To start programming with python, we have to install python software. There are two
major Python versions, those are Python 2 and Python 3. Python 2 and 3 are quite
different. In this tutorial we are going to use Python 3, because it more semantically
correct and supports newer features.
In this tutorial we are going to learn about installation of Python3
on ✍ Windows and ✍Linux (Ubuntu)
✍ Python3 installation procedure in Windows :
To install Python3 in windows, we have to download Python3 software pack from official website of Python
Software Foundation.
1. Go to [Link]
The following page will displayed on your web browser.
2. Go to Downloads
The following page will displayed on your web browser.
3. Download the latest version of python(now latest version:python 3.8.3) for windows
The following page will displayed on your web browser.
4. After the successful completion of download,we need to run [Link] file
It asks the permission to run this file as shown in below.
5. Click on Run button
After click on Run button, the Python setup window will be displayed as shown in below.
6. Click on Install Now
First we need to check Add Python 3.8 to PATH, And then click on Install Now, the Python setup
progress window will be displayed as shown in below.
7. Setup was Successful
The Python setup will take 2 to 3 minutes of [Link] successful installation the following window will
be displayed
8. Click on Close button
That's it, Python Setup was Successful
✍ Python3 installation procedure in Linux (Ubuntu) :
All most all Linux (Ubuntu) operating systems came up with python 2. 7. To check the python version in your
Linux (Ubuntu) system, open terminal by pressing Ctrl + ALT + T and then type following command press
enter.
$ python --version (or) $ python -V
Then we get version of python i.e. Python 2.7.12
In this tutorial we are going to install Python 3 on Linux (Ubuntu) Operating System.
To install Python 3
1. To update software packages on your system, execute the following command in terminal
2. $ sudo apt-get update
3. After successful updating of software packages, To install python3, execute the following command in
terminal
4. $ sudo apt-get install python3
5. To check if python is install properlyor not, we will check the version of python
6. $ python3 --version (or) $ python3 -V
Then we get version of python3 i.e. Python 3.7.x i.e, Python3 setup successful in Linux (Ubuntu)
operating system.
Comments in Python
In general, Comments are used in a programming language to describe the program or
to hide the some part of code from the interpreter.
Comments in Python can be used to explain any program code. It can also be used to
hide the code as well.
Comment is not a part of the program, but it enhances the interactivity of the program
and makes the program readable.
Python supports two types of comments:
Single Line Comments
Multi Line Comments
1. Single Line Comments in Python:
In case user wants to specify a single line comment, then comment must start with ‘#’
format:
# This is single line comment
Example: "[Link]"
# This is single line comment.
print("Hello Python")
This site uses Google AdSense ad intent links. AdSense automatically generates these links and they may help creators
earn money.
Output: $python3 [Link]
Hello Python
2. Multi Line Comments in Python
Multi lined comment can be given inside triple [Link] must start at begining of the
line.
format:
''' This
Is
Multiline comment'''
Example: "[Link]"
'''This
is
Multi line comment'''
print("Hello Python")
Output: $python3 [Link]
Hello Python
⛳ Python Example Program: Demonstrates usage of Comments
in Python
Example: "[Link]"
# This example demonstrates usage of Comments
''' print() used to
print/display
text on screen '''
print("Welcome to Python")
#Assign value to variables
a=20
b=30
#print sum of two numbers
print("Sum is")
print(a+b)
Input-Output Operations in Python
Input and Output operations are performed using two built-in functions
print( ) - Used for output operation.
input( ) - Used for input operations.
1. print()
The print() function prints the specified message to the screen, or other standard output
device.
The message can be a string, or any other object, the object will be converted into a
string before written to the screen.
Syntax:
print(object(s), separator=separator, end=end, file=file, flush=flush)
When we use the print( ) function to display a message, the string can be enclosed
either in the single quotation or double quotation.
format:
print('how are you?')
print("have fun with python")
function is also used to display variables value. The following example shows that how
to display the combination of message and variable value
format:
x = 10
print('The value of variable num1 is ' + x)
In Python, we can use the formatted string that is prefixed with character "f". In the
formatted string, the variable values are included using curly braces ({ }). Return value
of print( ) function is default None.
format:
x = 10
print(f"The value of variable num1 is {x}")
However, it turns out that this function can accept any number of positional arguments,
including zero, one, or more arguments. That’s very handy in a common case of
message formatting, where you’d want to join a few elements together.
format:
a=10
b=20
print("a= ",a,"b= ",b)
integer and String objects have a built-in operation using the % operator, which you can
use to format strings.
format:
a=10
b='python'
print("a= %d b= %s" %(a,b))
By default, python's print() function ends with a newline. This function comes with a
parameter called 'end.' The default value of this parameter is '\n,' i.e., the new line
character. You can end a print statement with any character or string using this
parameter. This is available in only in Python 3+
format:
print ("Welcome to", end = ' ')
print ("python", end = '!')
2. input()
The Python provides a built-in function input( ) to perform input operations.
Syntax:
input(prompt)
Use the prompt parameter to write a message before the input.
format:
x = input('Enter your name:')
print('Hello, ' + x)
The Python does not provide any direct function to read a single character as input. But
we can use the index value to extract a single character from the user entered input
value. Let's look at the following Python code.
format:
x = input('Enter your name:')[0]
print('Hello, ' + x)
Always the input( ) function reads input value as string value only. To read the value of
any other data type, there is no input function in Python. Explicitly we need to convert to
the required data type using type casing.
format:
x = int(input('Enter a value:'))
print('The value is : ', x)
Next Topic : Variables in Python
Variables in Python
A variable is a named memory location in which we can store values for the particular
[Link] other words, Variable is a name which is used to refer memory location.
Variable also known as identifier and used to hold value.
Creating Variables in Python
In Python, We don't need to declare explicitly variable in Python. When we assign any
value to the variable that variable is declared automatically.
In Python, We don't need to specify the type of variable because Python is a loosely
typed language. I.e. In loosely typed language no need to specify the type of variable
because the variable automatically changes it's datatype based on assigned value.
For Example:
Where variable a=10 a is an integer datatype.
Where variable b="Glance" b is string datatype.
Rules for naming variable:
Variable names can be a group of both letters and digits, but they have to begin with a
letter or an underscore.
It is recommended to use lowercase letters for variable name. ‘SUM’ and ‘sum’ both are
two different variables.
⛳ Python Example Program - Variables in Python
Example: "[Link]"
a=10 #integer
b="StudyGlance" #string
c=12.5 #float
print(a)
print(b)
print(c)
This site uses Google AdSense ad intent links. AdSense automatically generates these links and they may help creators
earn money.
Output: $python3 [Link]
10
StudyGlance
12.5
Assign Value to Multiple Variables
Python allows us to assign a value to multiple variables and multiple values to multiple
variables in a single statement which is also known as multiple assignment.
Assign single value to multiple variables :
Example: "[Link]"
x=y=z=50
print x
print y
print z
Output: $python3 [Link]
50
50
50
Assign multiple values to multiple variables :
Example: "[Link]"
a,b,c=5,10,15
print a
print b
print c
Output: $python3 [Link]
5
10
15
Next Topic : Data Types in Python
Data Types in Python
In general, Data Types specifies what type of data will be stored in variables. Variables
can hold values of different data types. Python is a dynamically typed or loosely typed
language, hence we need not define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.
I.e. In loosely typed language no need to specify the type of variable because the
variable automatically changes it's datatype based on assigned value.
Python provides the type() function which enables us to check the type of the variable.
Python provides following standard data types, those are
1. Numbers
2. String
1. Numbers
Number stores numeric values. Python creates Number type variable when a number is
assigned to a variable.
There are three numeric types in Python:
a. int
b. float
c. complex
a. int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
format:
a = 10
b = -12
c = 123456789
b. float
Float or "floating point number" is a number, positive or negative, containing one or
more decimals.
format:
X = 1.0
Y = 12.3
Z = -13.4
c. complex
Complex numbers are written with a "j" as the imaginary part.
format:
A = 2+5j
B = -3+4j
C = -6j
⛳ Python Example Program - Number Datatypes in Python
Example: "[Link]"
a = 10
b = 10.5
c = 2.14j
print("Datatype of Variable a :",type(a))
print("Datatype of Variable b :",type(b))
print("Datatype of Variable c :",type(c))
This site uses Google AdSense ad intent links. AdSense automatically generates these links and they may help creators
earn money.
Output: $python3 [Link]
Datatype of Variable a : <class ‘int’>
Datatype of Variable b : <class ‘float’>
Datatype of Variable c : <class ‘complex’>
2. String
The string can be defined as the sequence of characters represented in the quotation
marks. In python, we can use single, double, or triple quotes to define a string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
format:
S1='Welcome'
S2="to Python"
S3='''world'''
⛳ Python Example Program - String Datatypes in Python
Example:
a = "Welcome" #using double quotes
b ='Python' #using single quotes
c = '''World''' #using triple quotes
print("Datatype of Variable a :",type(a))
print(a+b) #to concatenate two strings
Output:
Datatype of Variable a : <class ‘str’>
Welcome Python
Next Topic : Typecasting in Python
Type Conversion & Type Casting in Python
Type Conversion & Casting
The Type Conversion is the process of converting the value of one data type to another
data type. In general, Type Conversion classified into two types
Implicit Type Conversion
Explicit Type Conversion( Type Casting )
Implicit Type Conversion :
In Implicit type conversion, Python interpreter automatically converts one data type to
another data [Link] this Type Conversion the python interpreter converts lower
datatype to higher datatype to avoid data loss.
⛳ Python Example Program - Implicit Type Conversion in Python
Example: "[Link]"
num1 = 15 #int
num2 = 4.5 #float
num3 = num1 + num2
print("Value of num3:",num3)
print("Datatype of num3:",type(num3))
This site uses Google AdSense ad intent links. AdSense automatically generates these links and they may help creators
earn money.
Output: $python3 [Link]
Value of num3: 19.5
datatype of num3: <class 'float'>
In the above example, we are trying to add two variable values(num1 is integer datatype
& num2 is folat datatype),but resultant variable(num3) is float datatype, because python
interpreter converts lower datatype(integer) to higher datatype(float) to avoid data loss.
Explicit Type Conversion ( Type Casting ) :
In Explicit type conversion, The user converts one data type to another data [Link] this
Type Conversion the user converts higher datatype to lower datatype or lower datatype
to higher datatype.
An Explicit type conversion is also called as Type Casting in Python
Python supports following functions to perform Type Casting in Python,
Those are
int () : This function converts any data type to integer.
float() : This function is used to convert any data type to a floating point number.
str() : This function is used to convert any data type to a string.
⛳ Python Example Programs - Explicit Type Conversion in
Python
Example: "[Link]"
a = int(2) # returns 2
b = int(3.2) # returns 3
c = int("6") # returns 6
d = int("11010",2) # returns base 2 value
print(a)
print(b)
print(c)
print(d)
Output: $python3 [Link]
2
3
6
26
Example: "[Link]"
a = float(2) # returns 2.0
b = float(3.2) # returns 3.2
c = float("6") # returns 6.0
d = float("6.2") # returns 6.2
print(a)
print(b)
print(c)
print(d)
Output: $python3 [Link]
2.0
3.2
6.0
6.2
Example: "[Link]"
a = str("abc") # returns 'abc'
b = str(3.2) # returns '3.2'
c = str(6) # returns '6'
print(a)
print(b)
print(c)
Output: $python3 [Link]
abc
3.2
6
Note: In Python, when an integer value is cast to float value, then it is appended with
the fractional part containing zeros (0) and when a float value is cast to an integer it
rounding down to the previous whole number.
Next Topic : Operators in Python