You are on page 1of 95

PYTHON PROGRAMMING

by
K. KUMARASWMY
C. RAJEEV
Assistant Professor,
Assist. Prof.
Department of CSE,
Dept. of. CSE,
MRECW MRECW.
Course Objectives:
 
This course will enable students to


Learn Syntax and Semantics and create Functions in
Python.

Handle Strings and Files in Python.

Understand Lists, Dictionaries and Regular
expressions in Python.

Implement Object Oriented Programming concepts in
Python.

Build GUI Programming in Python.
Course Outcomes:
 
The students should be able to
 Examine Python syntax and semantics and be fluent in the use

of Python flow control and functions.


 Demonstrate proficiency in handling Strings and File Systems.

 Create, run and manipulate Python Programs using core data

structures like Lists, Dictionaries and use Regular Expressions.


 Interpret the concepts of Object-Oriented Programming as used

in Python.
 Implement exemplary applications related to Graphical User

Interface (GUI) in Python.


UNIT I
PYTHON Programming Introduction, History of Python, Python is Derived from?, Python

Features, Python Applications, Why Python is Becoming Popular Now a Day?, Existing

Programming Vs Python Programming, Writing Programs in Python, Top Companies Using

Python, Python Programming Modes, Interactive Mode Programming, Scripting Mode

Programming, Flavors in Python, Python Versions, Download & Install the Python in

Windows & Linux, How to set Python Environment in the System?, Anaconda - Data Science

Distributor, Downloading and Installing Anaconda, Jupyter Notebook & Spyder, Python IDE -

Jupyter Notebook Environment, Python IDE – Spyder Environment,

Python Identifiers(Literals), Reserved Keywords, Variables, Comments, Lines and

Indentations, Quotations, Assigning Values to Variables


UNIT II
Data Types in Python, Mutable Vs Immutable, Fundamental Data Types: int, float, complex,

bool, str, Number Data Types: Decimal, Binary, Octal, Hexa Decimal & Number Conversions,

Inbuilt Functions in Python, Data Type Conversions, Priorities of Data Types in Python,

Python Operators, Arithmetic Operators, Comparison (Relational) Operators, Assignment

Operators, Logical Operators, Bitwise Operators, Membership Operators, Identity Operators,

Slicing & Indexing, Forward Direction Slicing with +ve Step, Backward Direction Slicing

with -ve Step, Decision Making Statements, if Statement, if-else Statement, elif Statement,

Looping Statements, Why we use Loops in python?, Advantages of Loops for Loop, Nested for

Loop, Using else Statement with for Loop, while Loop, Infinite while Loop, Using else with

Python while Loop, Conditional Statements, break Statement, continue Statement, Pass

Statement
UNIT III

Advanced Data Types: List, Tuple, Set, Frozenset, Dictionary, Range, Bytes & Bytearray,

None, List Data Structure, List indexing and splitting Updating List values, List Operations,

Iterating a List, Adding Elements to the List, Removing Elements from the List, List Built-in

Functions, List Built-in Methods, Tuple Data Structure, Tuple Indexing and Splitting, Tuple

Operations, Tuple Inbuilt Functions, Where use Tuple, List Vs Tuple, Nesting List and Tuple,

Set Data Structure, Creating a Set, Set Operations, Adding Items to the Set, Removing Items

from the Set, Difference Between discard() and remove(), Union of Two Sets, Intersection of

Two Sets, Difference of Two Sets, Set Comparisons, Frozenset Data Structure, Dictionary Data

Structure, Creating the Dictionary, Accessing the Dictionary Values, Updating Dictionary

Values, Deleting Elements Using del Keyword, Iterating Dictionary, Properties of Dictionary

Keys, Built-in Dictionary Functions, Built-in Dictionary Methods, List Vs Tuple Vs Set Vs
UNIT IV

Python Functions, Advantage of Functions in Python, Creating a Function, Function Calling,

Parameters in Function, Call by Reference in Python, Types of Arguments, Required Arguments,

Keyword Arguments, Default Arguments, Variable-Length Arguments, Scope of Variables,

Python Built-in Functions, Python Lambda Functions, String with Functions, Strings Indexing

and Splitting String Operators, Python Formatting Operator, Built-in String Functions, Python

File Handling, Opening a File, Reading the File, Read Lines of the File, Looping through the

File, Writing the File, Creating a New File Using with Statement with Files, File Pointer

Position, Modifying File Pointer Position Renaming the File & Removing the File, Writing

Python Output to the Files File Related Methods, Python Exceptions, Common Exceptions,

Problem without Handling Exceptions, except Statement with no Exception, Declaring Multiple

Exceptions, Finally Block, Raising Exceptions, Custom Exception,


UNIT V

Python Packages, Python Libraries, Python Modules, Collection Module, Math Module, OS

Module, Random Module, Statistics Module, Sys Module, Date & Time Module, Loading the

Module in our Python Code, import Statement, from-import Statement, Renaming a Module,

Regular Expressions, Command Line Arguments, Object Oriented Programming (OOPs),

Object-oriented vs Procedure-oriented Programming languages, Object, Class, Method,

Inheritance, Polymorphism, Data Abstraction, Encapsulation, Python Class and Objects, Creating

Classes in Python, Creating an Instance of the Class, Python Constructor, Creating the,

Constructor in Python, Parameterized Constructor, Non-Parameterized Constructor, In- built

Class Functions, In-built Class Attributes, Python Inheritance, Python Multi-Level Inheritance,

Python Multiple Inheritance, Method Overriding, Data Abstraction in Python,

Graphical User Interface (GUI) Programming, Python Tkinter, Tkinter Geometry, pack()
TEXT BOOK:
 
1. Core Python Programming, Wesley J. Chun, Second Edition, Pearson
 
REFERENCE BOOK:
1. Programming Languages, A.B. Tucker, R.E. Noonan, TMH.
2. Programming Languages, K. C. Louden and K A Lambert., 3rd
edition, Cengage Learning.
3. Programming Language Concepts, C Ghezzi and M Jazayeri, Wiley
India.
4. Programming Languages 2nd Edition Ravi Sethi Pearson.
5. Introduction to Programming Languages Arvind Kumar Bansal CRC
Press.
UNIT I
PYTHON Programming Introduction, History of Python, Python is Derived from?, Python

Features, Python Applications, Why Python is Becoming Popular Now a Day?, Existing

Programming Vs Python Programming, Writing Programs in Python, Top Companies Using

Python, Python Programming Modes, Interactive Mode Programming, Scripting Mode

Programming, Flavors in Python, Python Versions, Download & Install the Python in

Windows & Linux, How to set Python Environment in the System?, Anaconda - Data Science

Distributor, Downloading and Installing Anaconda, Jupyter Notebook & Spyder, Python IDE -

Jupyter Notebook Environment, Python IDE – Spyder Environment,

Python Identifiers(Literals), Reserved Keywords, Variables, Comments, Lines and

Indentations, Quotations, Assigning Values to Variables


1. INTRODUCTION TO PYTHON
What is PYTHON?
Python is a high-level, interpreted, interactive and object-oriented, scripting language.
 Python is a high-level
It is a language that enables a programmer to write programs that are more or less
independent of a particular type of computer. Such languages are considered as closer
to human languages and further from machine languages.
 Python is Interpreted:
 Python is processed at runtime by the interpreter. We do not need to compile our
program before executing it. This is similar to PERL and PHP.
 Python is Interactive:
You can actually sit at a Python prompt and interact with the interpreter directly to
write your programs.
 Python is Object-Oriented:
 Python is an object-oriented language .It allows us to develop applications using an
Object-Oriented approach. In Python, we can easily create and use classes and objects.
Python is scripting language:
A scripting language is used to write scripts. These contain a series of commands that are
interpreted one by one at runtime unlike programming languages that are compiled first before
running
Programming languages based applications are run by compiler
Programming languages based applications are required explicit compilation
Programming languages based applications can’t run directly without
compilation.
Ex: C,C++,JAVA .NET
These languages are run by compiler

Scripting language based applications are run by interpreter.


Scripting language based applications are not required explicit compilation
Ex: shellscript, python , perl, Ruby, PowerShell
These languages are run by interpreter.
 Python is a dynamic programming language which supports several different
programming paradigms:
Procedural programming(C)
Object oriented programming(C++,java)
Functional programming(LISP, Erlang…..)
Scripting languages(shell script, PERL, Ruby, Powershell)
Modular programming(Modula-3)

 Python= powerful programming language + powerful scripting language


2. History of Python, Python is Derived from?,:
Python was developed by Guido van Rossum, a Dutch computer programmer in December
1989 at the National Research Institute for Mathematics and Computer Science (NRIMCS)in the
Netherlands.

Python is said to have succeeded is ABC Programming Language, which had the interfacing
with the Amoeba Operating System.

Python is derived from many other languages, including ABC, Modula-3, C, C++,Algol-68,
SmallTalk, and Unix shell and other scripting languages
 Here interesting fact is- Python is named after the BBC TV comedy show Monty

Python’s Flying Circus.

 It is not named after the Python snake.


3. Features of Python Programming:

1. Easy to code and Easy to read


2. Free and Open-Source
3. High- Level
4. Portable
5. Interpreted
6. Object-Oriented
7. Embeddable
8. Large Standard Library
9. GUI Programming
10.Dynamically Typed
1. Easy:
a. Easy to code:
Python is very easy to code. Compared to other popular languages like Java and
C++ . Anyone can learn python syntax in just a few hours.
b. Easy to read:
Being a high-level language, Python code is quite like English. Looking at it, you
can tell what the code is supposed to do.
2. Free and Open-Source
Firstly, Python is freely available. You can download it from the following link
https://www.python.org/downloads/.

Secondly, it is open-source. This means that its source code is available to the public.
You can download it, change it, use it, and distribute it. This is called FLOSS(Free/Libre
and Open Source Software).
3. High- Level
It is a high-level language. This means that as programmers, we don’t need to
remember the system architecture. Nor do we need to manage the memory. This
makes it more programmer-friendly.

4. Portable
We can take one code and run it on any machine, there is no need to write different
code for different machines. This makes Python a portable language. However, you
must avoid any system-dependent features in this case.
5. Interpreted:
If you’re any familiar with languages like C++ or Java, you must first compile it, and
then run it. But in Python, there is no need to compile it. Internally, its source code is
converted into an immediate form called bytecode.

So, all you need to do is to run your Python code without worrying about linking to
libraries, and a few other things.

By interpreted, we mean the source code is executed line by line, and not all at once.
Because of this, it is easier to debug your code.
6. Object-Oriented
Python allows us to develop applications using an Object-Oriented approach.

Object-oriented programming (OOP) is nothing but that which allows the writing
of programs with the help of certain classes and real-time objects

Python supports object-oriented programming concepts like


 Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation

It also supports multiple inheritance, unlike Java


7. Embeddable
 We can put our Python code in a source code in a different language like C++.
 We can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
CPython is a python integrated with C/C++ language.
Similarly JPython is a purely integrated language.

8. Large Standard Library


Python downloads with a large library that you can use so you don’t have to write
your own code for every single thing.

There are libraries for regular expressions, documentation-generation, unit-testing,


web browsers, threading, databases, CGI, email, image manipulation, and a lot of
other functionality.
9.GUI Programming
You can use Tk or Tkinter to create basic GUIs
.

10. Dynamically Typed


Python is dynamically-typed. This means that the type for a value is decided at runtime,
not in advance. This is why we don’t need to specify the type of data while declaring it.
4. Python Applications
1) Web Applications

2) Desktop GUI Applications

3) Scientific and Numeric

4) Business Applications

5) Console Based Application

6) Audio or Video based Applications

7) 3D CAD Applications

8) Enterprise Applications

9) Image applications
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser etc.

It also provides Frameworks such as Django, Pyramid, Flask etc to design and develop
web based applications. Some important developments are: PythonWikiEngines, Pocoo,
PythonBlogSoftware etc.

2) Desktop GUI Applications


Python provides Tk GUI library to develop user interface in python based application.

Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms.
The Kivy is popular for writing multitouch applications.
3) Software Development
Python is helpful for software development process. It works as a support language and
can be used for build control and management, testing etc.

4) Scientific and Numeric


Python is popular and widely used in scientific and numeric computing.
 Some useful library and package are SciPy, numpy, Pandas, IPython etc.
SciPy is group of packages of engineering, science and mathematics.

5) Business Applications
Python is used to build Business applications like ERP and e-commerce systems.
Tryton is a high level application platform.

6) Console Based Application


We can use Python to develop console based applications.
For example: IPython.
7) Audio or Video based Applications
Python is awesome to perform multiple tasks and can be used to develop multimedia
applications. Some of real applications are: TimPlayer, cplay etc.

8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of
CAD.

9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an
Organization.
Some real time applications are: OpenErp, Tryton, Picalo etc.

10) Applications for Images


Using Python several application can be developed for image.
 Applications developed are: VPython, Gogh, imgSeek etc.
5. Why Python?
Python is also a cross platform language which means that the code written for one operating
system like Windows ,will work equally well with Linux or MacOS without any changes to the
python code.

Python has a simple syntax similar to the English language. whereas the other languages use
punctuations.

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

Python is a programming language that allows you work quickly and integrate systems
more efficiently.

Python is a great language for the beginner level programmers and supports the
development of a wide range of applications.
6. Advantages of Python:
1. Freeware: Python is open source language. It doesn't require any activation key or
subscription to work on it. It is free to use software and all the tool available on python
are absolutely free.

2. Less Coding: The syntax written in python is very simple and use common English
language which makes it more user-friendly.

3. Efficient: Python relies on indentation, using white space, to define scope; such as the
scope of loops, functions, and classes. Other Programming Languages use curly-brackets
for this purpose.

4. Portability: Python can run any operating system. Also, we use the Python Code
written on one system onto another system without making any changes to the code.
Existing Programming Vs Python Programming:
C, c++ ,java , python program to find addition of two numbers

--------c program-------- --------c++ program--------


#include<stdio.h>  #include <iostream>
int main() using namespace std;
{ int main()
   int a, b, sum;  {

   printf("\nEnter two no: "); int firstNumber, secondNumber, sumOfTwoNumbers;

   scanf("%d %d", &a, &b);  cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
   sum = a + b; 
sumOfTwoNumbers = firstNumber + secondNumber;
   printf("Sum : %d", sum); 
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
   return(0);
return 0;
}
}

--------java program--------
--------python program--------
public class AddTwoNumbers {
num1 = 1.5; num2 = 6.3
public static void main(String[] args) {
sum = num1 + num2
int num1 = 5, num2 = 15, sum;
print('The sum of two numbers”, sum))
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
7. Python Versions:
The implementation of Python was started in December 1989.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources.

Python 1.0 - January 1994


Python 1.0 was released with new features like lambda, map, filter, and reduce.
Python 1.5 - December 31, 1997
Python 1.6 - September 5, 2000
Python 2.0 - October 16, 2000
Python 2.0 added new features such as list comprehensions, garbage collection systems.
Python 2.1 - April 17, 2001
Python 2.2 - December 21, 2001
Python 2.3 - July 29, 2003
Python 2.4 - November 30, 2004
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010
 Python 3.0 - On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.

Python 3.1 - June 27, 2009


Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
Python 3.7.0 - June 27, 2018
Python 3.7.1 - October 13, 2018
Python 3.7.2 - December 24, 2015
Python 3 is not backward
Python 3.7.3 - March 25, 2019 compatible with Python 2.
Python 3.7.4 - July 8, 2019
Python 3.9 is latest version of python 3
Python 3.8.3 -oct-14,2019
8. Top Companies using Python :
1. Google -  Python is in their top 3 alongside C++ and Java

2. Amazon -   the machine learning engine is powered by Python

3. Microsoft -  Python used for data science and analytics

4. Facebook -  Python helps in maintaining and managing FB infrastructure

5. Instagram -  CPython as the main tool to execute the code

6. Spotify -  Python used for backend and data analysis

7. Netflix -  Python used for machine learning and marketing recommendations

8. Uber -  at the lower level backend, the engineers work mostly in Python,
Node.js, Go and Java .
9. Yahoo(Maps)
10. YouTube
11. Mozilla
12. Dropbox
8. Installing Python(in ubuntu)
1. Open terminal via Ctrl+Alt+T or searching for “Terminal” from app launcher.

2. Ubuntu 16.04 comes with both Python 2 and Python 3 by default.


3. If it is not there, install Python use following command :
sudo apt-get install python3.9

4. To check updates use following command


sudo apt-get update
5. To know the versions of the python type following command:
How to Install Python on windows
We can install Python on windows go to link https://www.python.org/downloads/
.
After downloading we are getting python-3.7.4. exe file. Install it and click next.
In window search button, type IDLE python, we are getting version of python we installed
Then we can execute our python programs in python interpreter. (Immediate mode)
To know the versions of the python in windows ,type following command:

>python --version
9. How to execute python program:
By using Python Interpreter, we can execute python programs in 2 modes .they
are:
1. Immediate mode
2. Script mode
1. Immediate mode: (in windows)
In the mode, you type Python expressions into the Python Interpreter window,
and the interpreter immediately shows the results.

The >>> is called the Python prompt..


Immediate mode: (in ubuntu)
In ubuntu ,we can open command prompt and type python or python2 or python3 and it
is enter into interpreter mode.
2. Script mode (in windows)
we can open IDLE python then click on file, open new file and we can write python program and
save as filename.py. After that ,to run this program press F5 button or click run button click Run
module.

Script mode(in ubuntu):


Alternatively, You can write a program in a file and use the interpreter to execute the contents
of the file. Such a file is called a script.
How to set Python Environment in the System?
If you’ve installed Python in Windows using the default installation options, the path to
the Python executable wasn’t added to the Windows Path variable.
The Path variable lists the directories that will be searched for executables when you
type a command in the command prompt. By adding the path to the Python executable,
you will be able to access python.exe by typing the python keyword (you won’t need to
specify the full path to the program).
Consider what happens if we enter the python command in the command prompt and
the path to that executable is not added to the Path variable:

C:\>python
'python' is not recognized as an internal or external command, operable program or
batch file.
As you can see from the output above, the command was not found.
To run python.exe, you need to specify the full path to the executable:

To add the path to the python.exe file to the Path variable, start the Run box and enter sysdm.cpl:
This should open up the System Properties window. Go to the Advanced tab and click
the Environment Variables button:
In the System variable window, find the Path variable and click Edit:
Position your cursor at the end of the Variable value line and add the path to the python.exe file,
preceeded with the semicolon character (;). In our example, we have added the following value: ;

Close all windows. Now you can run python.exe without specifying the full path to the file:
10. How to install Anaconda software in ubuntu

1.Download Anaconda from the following link:


https://www.anaconda.com/distribution/
2. After downloading we are getting “ Anaconda3-2019.03-Linux-x86_64.sh “ file
3. Open terminal type $ cd downloads where .sh file is present

4. Run the Anaconda Script:


Type $ bash Anaconda3-2019.03-Linux-x86_64.sh
and press enter finally type yes and enter
5. Use the conda command to test the installation and activation:
$conda list

6. Activate Installation
We can now activate the installation with the following command:
Source ~/.bashrc
7. if you want to add Anaconda to your PATH use command:
$ export PATH=/usr/bin/anaconda/bin:$PATH
8. To launch application use following command:
$ anaconda -navigator
9. After launching, the following applications are available by default in Navigator:
1.JupyterLab
2.Jupyter Notebook
3.QTConsole
4.Spyder
5.VSCode
6.Glueviz
7.Orange 3 App
8.Rodeo
9.RStudi0
8. From the Navigator Home tab, click the launch button in Spyder, and it is open
editor to write and execute our code.
In ubuntu, Immediate mode and scripting mode of Anaconda
How to install Anaconda software in windows

1.Download Anaconda from the following link:


https://www.anaconda.com/distribution/
2. After downloading we are getting Anaconda3-2019.03-Windows-x86_64.exe file in
downloads
3. Click on Anaconda3-2019.03-Windows-x86_64.exe file and click next…
4. After finishing, open anaconda navigator in windows search.
5. Click on launch button on spyder application
In windows, Immediate mode and Scripting mode of Anaconda
How to install jupyter notebook :
Note: before installing jupyter , install python 3.7 or above
1. Open a "Command Prompt“ and enter into path where python 3.7 is installed
2. Type  python -m pip install jupyter

3. To open jupyter notebook, then Type jupyter notebook

4. After that jupyter notebook


will open in browser
How to use jupyter notebook and execute program
1. Select—new- python3

2. We can write and execute program in cell

NOTE: To run program click on run or press shift+enter button


8. How to install jupyter notebook in ubuntu:
Note: before installing jupyter , to check or install python 3.7 or above
1. Open terminal via Ctrl+Alt+T or searching for “Terminal” from app launcher.

2. Ubuntu 16.04 comes with both Python 2 and Python 3 by default.


3. To check whether jupyter notebook are installed or not
Type jupyter notebook in terminal

4. In terminal , type : $ sudo apt install jupyter-notebook.


5. After finishing installing , run the notebook with $ jupyter-notebook
6. When you execute the command above a Jupyter interface will load in your browser with the
notebook.
7. Select—new- python3

8. We can write and execute program in cell

NOTE: To run program click on run or press shift+enter button


Flavors of Python(Emeddable languages):
Flavors of Python refer to the different types of Python compilers. These flavors are
useful to integrate various programming languages into Python. The following are
some of them:
1. Cpython
2. Jython
3. IronPython
4. PyPy
5. RubyPython
Statements and Syntax:
1. Python Statement
By default, the Python interpreter treats a piece of text terminated by hard
carriage return (new line character) as one statement.
It means each line in a Python script is a statement. (Just as in C/C++/C#, a
semicolon ; denotes the end of a statement).
Example: simple statement
>>> msg="Hello World"
msg="Hello World"
>>> msg
code=123
'Hello World'
name= 20.5
>>> code=123
>>> code
123
>>> name= 20.5
>>> name
20.5
Output:
Hello world! Welcome to Python Programming I am simple than other languages

We can also do Multi-line statements with implicit line continuation.


line continuation is implied inside parentheses ( ), brackets [ ], and braces { }.
Ex:
colors = ['red',
Output:
'blue',
['red', 'blue', 'green']
'green']
2.2 Multiple Statements in Single Line ( ; )

If you want to write multiple statements in a single line. Use semicolon(;)

Ex: >>msg="Hello World"; code=123; name="Steve"

Output:
>>> msg
'Hello World'
>>> code
123
3.Comments in Python
In a Python script, the symbol # indicates the start of a comment line. It is effective
till the end of the line in the editor.

It can be used also in the middle of a line. The text before it is a valid Python
expression, while the text following is treated as a comment.
Example:
# this is a comment
print ("Hello World")
print ("Welcome to Python Tutorial") #this is also a comment but after a
statement
In Python, there is no provision to write multi-line comments, or a block comment.
(As in C#/C/C++, where multiple lines inside /* .. */ are treated as a multi-line
comment).
Then how to represent Multi Line Comments:
Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line.
Ex:
#This is a comment
#written in
#more than just one line
print("Hello, World!")

We can also represent Multi Line Comments using a multiline string(triple quotes).
Ex:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
4.Indentation:
One of the most distinctive features of python is use of indentation to mark blocks of
code.

Generally, in C,C++,java languages ,we use curly brackets { } to indicate block of code
for class ,function definition or flow of control. but where as in python curly braces are
not allowed.
Then, what is indentation?
So, in python block of code are denoted by indentation.

Indentation refers to the whitespaces(spaces and tabs) at the beginning of a code line.

Using this whitespaces, we are defining program blocks

 Where in other programming languages the indentation in code is for readability only.

How to use this: When a block is to be started, type the exclamation symbol (:) and
press Enter. Then follow indentation Ex:
test=5
if test<10:
print(“A”)
else:
print(“C”)
In the following program, the block statements have no indentation.

This is a program with single space indentation.


The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all
statements within the block must be the indented same amount.
This is a program with single tab indentation.

In order to signal the end of a block, the whitespace is de-dented by pressing the backspace key

Instructions:
Use 4 spaces per indentation and no tabs.
Do not mix tabs and spaces. Tabs create confusion and it is recommended to use
only spaces.
Python will give you an error if you skip the indentation, so use the same number of
spaces in the same block of code,
5. Python identifiers:
A identifier is a name used to identify a variable, function, class, module or other
object.
An identifier start with a letter A t o Z (or) a to z an underscore(_) followed by zero
or more letters, underscores and digits(0-9).
Python doesn’t allows punctuation characters such as @,$,% with identifiers.

1.An identifier should not start with digit but it can contains digit.
Ex:
>>> 12ab=20 syntax error: invalid syntax
>>> ab12=20 20
2. An identifier can contain underscores (single, double, and also triple)
Ex:
>>> _a=10
>>> _a
10
>>> a_b=20
>>> a_b
20
>>> ab_=30 >>> __ab__cd=90
>>> ab_ >>> __ab__cd
30 90

>>> _a_b=40 >>> ___a=100


>>> _a_b >>> ___a
40 100

>>> ab__=50 >>> _=110


>>> ab__ >>> _
50 110

>>> a__b=60 >>> __=120


>>> a__b >>> __
60 120

>>> __ab=80 >>> ___=130


>>> __ab >>> ___
80 130

Note: In python, underscore (_) has special meaning in the interactive interpreter: the last
evaluated expression.
>>> _
3. An identifier must not contain special characters except underscores .
>>> @a=20
SyntaxError: invalid syntax >>> a*b=20
>>> a@b=20 SyntaxError: can't assign to operator
SyntaxError: can't assign to operator >>> &a=20
>>> $b=10 SyntaxError: invalid syntax
SyntaxError: invalid syntax >>> a&b=20
>>> a$b=20 SyntaxError: can't assign to operator
SyntaxError: invalid syntax
>>> !a=20 >>> a_b=20
SyntaxError: invalid syntax >>> a_b
>>> a!b=20 20
SyntaxError: invalid syntax
>>> *a=20
SyntaxError: starred assignment target must be in a list or tuple
4. Identifiers are case sensitive, so python is a case sensitive language.
>>> a=100
>>> A=200
>>> print(a)
100
>>> print(A)
200

>>> b=100 >>> var='python'


>>> print(B) >>> print(Var)
Traceback (most recent call last): Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module> File "<stdin>", line 1, in <module>
print(B) NameError: name 'Var' is not defined
NameError: name 'B' is not defined
5. Keywords or reserved words can’t be used as identifiers

Ex:1
>>> if=100
File "<stdin>", line 1
if=100
^
SyntaxError: invalid syntax
Ex:2
>>> return=10
File "<stdin>", line 1
return=10
^
SyntaxError: invalid syntax
6.Keywords:
Computer programming language comprises of a set of predefined words which are called
keywords.
Similarly, Python 3.x interpreter has 35 keywords defined in it.(In C, 32 keywords)
They cannot be used for any other purpose like constants or variable or identifier names.

>>> help("keywords“)
Here is a list of the Python keywords.
False class from or
None continue global pass
True def if raise
and del import return
Note: only False, None,
as elif in try
True are capitalized
assert else is while
async except lambda with
await finally nonlocal yield
break for not
>>> import keyword
>>> keyword.kwlist

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

To check whether given keyword is present or not


>>> keyword.iskeyword('for')
True
>>> keyword.iskeyword('False')
True
>>> keyword.iskeyword('false')
False
7.Python variable:
Variables are containers for storing data values. Unlike other programming languages,
Python has no command for declaring a variable.

Just we declare variable has a name that is used to refer to memory location. Python
variable is also known as an identifier and used to hold value.

In python, we don't need to declare explicitly variable i.e., variables need not be
declared or defined in advance.

For example, >>> n = 10 >>m=20.5 >>>p=‘python’


>>>n >>>m >>>p
10 20.5 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.


How the Python interpreter works when we declare a variable.
 The process of treating variables is somewhat different from many other programming
languages.

 In C, it actually creates a block of memory In Python, variables work more like tags,
space so that it can hold the value for that When you do an assignment in Python, it tags
variable. the value with the variable name.
int a=1; a=1

In python, everything is considered as an object.


When we declare a name/variable it stores the name in the memory. Every python
name/variable points to its reference in the memory and reference points to the object.

Ex: Let's consider the example code "a = 1" , "a" is name and it's points to the reference
"258041008" and the reference points to the object "1" which is in binary format.
We can get this reference object, with python built-in function id( )
So that, a name is just a label for an object.

In C, if you change the value of the variable, In Python. if you change the value of the
the box will be updated with the new value. variable, it just changes the tag to the new
int a = 2; value in memory.
a=2
In C, if we assign one variable to another In Python, Assigning one variable to another
makes a copy of the value and put that value in makes a new tag bound to the same value:
the new box. a=2
int a=2; b=a
int b = a;

In python each object can have lots of names.

In python, we don’t need to do the housekeeping job of freeing the memory here. Python's

Automatic Garbage Collection does it for you. When a value is without


names/tags it is automatically removed from memory.
What is difference between identifier and varaible in python?
An identifier is a “name given to an entity”, which distinctly identifies an entity(a
variable, function, class, module or any other object.) in a program at the time of its
execution. 

whereas, a variable is a “name given to memory location”, that is used to hold value,
which may get modified during program execution.
1. Assigning single value to single variable:
 The operand to the left of the = operator is the variable and the right of the =operator is
the value stored in the variable
For example, >>> n = 10 >>m=20.5 >>>p=‘python’
>>>n >>>m >>>p
10 20.5 python

2. Assigning multiple values to multiple variables: ("Multuple" Assignment)


>>> a,b,c=10,20.5,'python'
>>> a,b,c
(10, 20.5, 'python‘)
Swapping of 2 numbers using "multuple" assignment in python:
If you have ever needed to swap values in other languages like C, you will be reminded
that a temporary variable, i.e., tmp, is required to hold one value while the other is being
exchanged:
/* swapping variables in C */
tmp = x;
x = y;
y = tmp;
One interesting side effect of Python's "multuple" assignment is that we no longer
need a temporary variable to swap the values of two variables.
# swapping variables in Python
>>> x, y = 1, 2
>>> x
1
>>> y
2
>>> x, y = y, x
>>> x
2
>>> y
1
3. Assigning same values to multiple variable:

>>> x=y=z=50
>>> id(x)
>>> x
1372546288
50
>>> id(y)
>>> y
1372546288
50
>>> id(z)
>>> z
1372546288
50
>>>
4. Tuple assignment :
x, y = 50, 100
X,
5. List assignment:
[x, y] = [2, 4]   
print('x = ', x)
print('y = ', y)
6. Sequence assignment:
a, b, c = 'HEY’  
print('a = ', a)
print('b = ', b)
print('c = ', c)
7. To check the data type of specific variable we can use type( ) function.

>>> a,b,c=10, 20.5, 'python'


>>> a,b,c
(10, 20.5, 'python')
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> type(c)
<class 'str‘>
Quotations:
Quotation symbols are used to create string object in Python. Python recognizes single,
double and triple quoted strings. String literals are written by enclosing a sequence of
characters in single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or
"""hello""").
Ex:
>>> var1='hello'
>>> var1
'hello'
>>> var2="hello"
>>> var2
'hello'
>>> var3='''hello'''
>>> var3
'hello'
>>> var4
>>> var4="""hello"""
'hello’

You might also like