SlideShare a Scribd company logo
1 of 131
Download to read offline
PYTHON PROGRAMMING
Python Basics
Dr.T.M.SARAVANAN
Associate Professor,
Department of Computer Applications,
Kongu Engineering College,
Perundurai – 638 060.
Fundamentals ofPython
Introduction to pythonprogramming
• High level, interpreted language
• Object-oriented
• General purpose
• Web development (like: Django, and
Bottle),
• Scientific and Mathematical Computing
(Orange, SciPy, NumPy)
• Desktop graphical user Interfaces
(Pygame, Panda3D).
Other features of python includes the following:
• Simple language which is easier to learn
• Free and open source
• Portability
• Extensible and embeddable
• Standard large library
• Created by Guido van Rossum in 1991
• Why the name Python?
• Not after a dangerous snake.
• Rossum was fan of a famous TV Show comedy
series from late Eighties.
• The name "Python" was adopted from the same
series "Monty Python's Flying Circus".
Python’s Benevolent Dictator For Life
“Python is an experiment in how
much freedom programmers
need. Too much freedom and
nobody can read another's code;
too little and expressiveness is
endangered.”
- Guido van Rossum
Reasons toChoose Python asFirstLanguage
• Simple Elegant Syntax
• Not overly strict
• Expressiveness of the language
• Great Community and Support
Installation of Python inWindows
• Go to Download Python page on the official
site (python.org/downloads/) and click
Download Python 3.9.4.
• When the download is completed, double-click
the file and follow the instructions to install it.
• When Python is installed, a program called
IDLE is also installed along with it. It provides
graphical user interface to work with Python.
08-04-2021
• Open IDLE, Write the following code below
and press enter.
print("Hello,W
orld!")
• To create a file in IDLE, go to File > New
Window (Shortcut: Ctrl+N).
• Write Python code and save (Shortcut: Ctrl+S)
with .py file extension like: hello.py or your-
first-program.py
print("Hello,World!")
• Go to Run > Run module (Shortcut: F5) and
you can see the output.
Python Code Execution
Python’s traditional runtime execution model: source code you
type is translated to byte code, which is then run by the Python
Virtual Machine. Your code is automatically compiled, but then
it is interpreted.
Source code extension is .py
Byte code extension is .pyc (compiled python code)
Difference Between Python 2.x & 3.x
Difference Between Python 2.x & 3.x
Difference Between Python 2.x & 3.x
First PythonProgram
SecondProgram
Few Important Things toRemember
• To represent a statement in Python, newline
(enter) is used.
• Use of semicolon at the end of the
statement is optional (unlike languages
like C/C++)
• In fact, it's recommended to omit
semicolon at the end of the statement
in Python
• Instead of curly braces { }, indentations are
used to represent a block
PythonKeywords
• Keywords are the reserved words(can not be
used as a identifier) in Python
• Are case sensitive
PythonIdentifiers
• Name given to entities like class, functions,
variables etc. in Python
• Rules for writing identifiers
• Can be a combination of letters in lowercase (a to
z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_)
• myClass, var_1 and print_this_to_screen, all are
valid examples
• Cannot start with a digit
• 1variable is invalid, but variable1 is perfectly fine
• Keywords cannot be used as identifiers
• Cannot use special symbols like !, @, #, $, % etc.
in our identifier
• Can be of any length.
Things to careabout
• Python is a case-sensitive language.
• Variable and variable are not the same.
• Multiple words can be separated
using an underscore,
this_is_a_long_variable
PythonStatement
• Instructions that a Python interpreter can
execute are called statements.
• Two types
• Single line statement:
• For example, a = 1 is an assignment statement
• Multiline statement:
• In Python, end of a statement is marked by a
newline character.
• So, how to make multiline statement?
• Technique1:
• make a statement extend over multiple lines
with the line continuation character ().
• For example:
a
=
1+
2+
3+

4+
5+
6+

7+8+9
• Technique2:
• make a statement extend over multiple lines
with the parentheses ( )
• For example:
a=(1+2+3+
4+5+6+
7+8+9)
• Technique3:
• make a statement extend over multiple lines with
the brackets [ ] and braces {
}.
• For example:
colors=['red',
'blue',
'green']
• We could also put multiple statements in a single
line using semicolons, as follows
a=1;b=2;c=3
PythonIndentation
• Most of the programming languages like C,
C++, Java use braces { } to define a block of
code
• Python uses indentation
• A code block (body of a function, loop etc.)
starts with indentation and ends with the
first un-indented line
Error due to incorrectindentation
PythonComments
• To make the code much more readable.
• Python Interpreter ignores comment.
• Two types of comment is possible in python:
• Single line comment and
• Multi-line comment
Single linecomment
• In Python, we use the hash (#) symbol to start
writing a comment.
• It extends up to the newline character
Multi-line comments
• Two way:
• By using # sign at the beginning of each line
• By using either ‘ ‘ ‘ or “ “ “ (most common)
PythonVariable
• a variable is a named location used to store data
in the memory.
• Alternatively, variables are container that hold
data which can be changed later throughout
programming
Declaring Variables
• In Python, variables do not need declaration to
reserve memory space.
• The "variable declaration" or "variable
initialization" happens automatically when
we assign a value to a variable.
• We use the assignment operator = to assign the
value to a variable.
Assigning Values tovariables
Changing value of avariable
Assigning same value to the multiplevariable
Assigning multiplevalues to multiplevariables
Constants
• Value that cannot be altered by the
program during normal execution.
• In Python, constants are usually declared and
assigned on a module
• And then imported to the file
Definingconstant Module
Rules and Naming convention for
variables and constants
• Create a name that makes sense. Suppose,
vowel makes more sense than v.
• Use camelCase notation to declare a variable
• For example: myName, myAge, myAddress
• Use capital letters where possible to declare a
constant
• For example: PI,G,MASS etc.
• Never use special symbols like !, @, #, $, %,
etc.
• Don't start name with a digit.
• Constants are put into Python modules
• Constant and variable names should have
combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an
underscore (_).
• For example: snake_case, MACRO_CASE,
camelCase, CapWords
Literals
Literal is a raw data given in a variable or constant.
In Python, there are various types of literals they
are as follows:
1. Numeric literals – Interger, Float, Complex
2. String literals – String, Character
3. Boolean literals – True or False
4. Special literals – None(Null Value)
5. Literal collections – List, Tuple, Dictionary and Set
Numeric Literals
String Literals
Docstrings
Using booleanliterals
Specialliteral(None)
LiteralsCollection
08-04-2021
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
08-04-2021
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Setting the Data Type
In Python, the data type is set when you assign a value to a
variable:
08-04-2021
Setting the Specific Data Type
If you want to specify the data type, you can use the following
constructor functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
DataTypes
• In python data types are classes and variables
are instance (object) of these classes
• Different types of data types in python are:
• Python numbers
• Python lists
• Python tuples
• Python strings
• Python sets
• Python dictionary
PythonNumbers
PythonList
• Ordered sequence of items
• Can contain heterogeneous data
• Syntax:
• Items separated by commas are
enclosed within brackets [ ]
• Example: a= [1,2.2,'python']
Extracting elements from thelist
• Note: Lists are mutable, meaning, value of
elements of a list can be altered.
PythonTuple
• Same as list but immutable.
• Used to write-protect the data
• Syntax:
• Items separated by commas are
enclosed within brackets ( )
• Example:
• t = (5,'program', 1+3j)
PythonStrings
• use single quotes or double quotes to represent strings.
• Multi-line strings can be denoted using triple quotes, ''' or """.
• Strings are also immutable.
PythonSet
• Unordered collection of unique items
• defined by values separated by comma inside
braces { }
• Set have unique values. They eliminate
duplicates.
• Example:
• Since, set are unordered collection, indexing has
no meaning.
• Hence the slicing operator [] does not work.
• Example:
PythonDictionary
• An unordered collection of key-value pairs.
• Must know the key to retrieve the value.
• Are defined within braces {} with each item
being a pair in the form key: value
• Key and value can be of any type
Conversion between datatypes
• Conversion can be done by using different
types of type conversion functions like:
• int(),
• float(),
• str() etc.
int tofloat
float toint
T
oand formstring
Convert one sequence toanother
• To convert to dictionary, each element must be a
pair:
Python TypeConversion and TypeCasting
• The process of converting the value of one data
type (integer, string, float, etc.) to another data
type is type conversion
• Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
• Type Conversion is the conversion of object
from one data type to another data type
• Implicit Type Conversion is automatically
performed by the Python interpreter
• Python avoids the loss of data in Implicit Type
Conversion
• Explicit Type Conversion is also called Type
Casting, the data types of object are
converted using predefined function by user
• In Type Casting loss of data may occur as
we enforce the object to specific data type
Implicit TypeConversion
• Automatically converts one data type to another
data type
• Always converts smaller data type to larger data
type to avoid the loss of data
Problem in implicit typeconversion
ExplicitTypeConversion
• Users convert the data type of an object to
required data type.
• Predefined functions like int(), float(), str(), etc.
are to perform explicit type conversion
• Is also called typecasting because the user
casts (change) the data type of the objects.
• Syntax :
• (required_datatype)(expression)
• Int(b)
Example
Python Input, Output andImport
• Widely used functions for standard input and
output operations are:
• print() and
• input()
Python Output Using print()function
Output formatting
• Can be done by using the str.format() method
• Is visible to any string object
• Here the curly braces {} are used as
placeholders. We can specify the order in which
it is printed by using numbers (tuple index).
Example
• We can even use keyword arguments to format
the string
• We can even format strings like the old printf()
style used in C
• We use the % operator to accomplish this
Input()function
• input() function to take the input from
the user.
• The syntax for input() is :
• input([prompt])
• where prompt is the string we wish to
display on the screen.
• It is optional
• Entered value 10 is a string, not a number.
• To convert this into a number we can use
int() or float() functions
• This same operation can be performed using the
eval(). It can evaluate expressions, provided the
input is a string.
PythonImport
• When our program grows bigger, it is a good
idea to break it into different modules.
• A module is a file containing Python definitions
and statements.
• Python modules have a filename and end with
the extension .py
• Definitions inside a module can be imported to
another module or the interactive interpreter in
Python
• We use the import keyword to do this
• import some specific attributes and functions
only, using the from keyword.
PythonOperators
• Operators are special symbols in Python that
carry out arithmetic or logical computation.
• The value that the operator operates on is
called the operand.
• For example:
>>> 2+3
5
• Here, + is the operator that performs addition.
• 2 and 3 are the operands and 5 is the output
of the operation.
Arithmetic operators
Example
Comparison operators
Logicaloperators
Bitwiseoperators
• Bitwise operators act on operands as if they
were string of binary digits. It operates bit by
bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in
binary) and y = 4 (0000 0100 in binary)
Assignmentoperators
• Assignment operators are used in
Python to assign values to variables.
• a = 5 is a simple assignment operator that
assigns the value 5 on the right to the
variable a on the left.
• There are various compound operators in
Python like a += 5 that adds to the variable
and later assigns the same.
• It is equivalent to a = a + 5.
Specialoperators
• identity
operator
• membership
operator
Identity operators
• is and is not are the identity operators in Python.
• They are used to check if two values (or variables)
are located on the same part of the memory.
• Two variables that are equal does not imply that
they are identical.
Membership operators
• in and not in are the membership operators in
Python
• They are used to test whether a value or
variable is found in a sequence (string, list,
tuple, set and dictionary).
• In a dictionary we can only test for presence of
key, not the value
ThankY
ou!

More Related Content

What's hot

Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python ProgrammingKamal Acharya
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Pythonjyostna bodapati
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slidesrfojdar
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaEdureka!
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
Python data type
Python data typePython data type
Python data typeJaya Kumari
 
Python programming
Python programmingPython programming
Python programmingKeshav Gupta
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 

What's hot (20)

Operators in python
Operators in pythonOperators in python
Operators in python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Python programming
Python  programmingPython  programming
Python programming
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Python
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Python libraries
Python librariesPython libraries
Python libraries
 
Python
PythonPython
Python
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python data type
Python data typePython data type
Python data type
 
Python programming
Python programmingPython programming
Python programming
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python ppt
Python pptPython ppt
Python ppt
 

Similar to Python Programming

modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptxYusuf Ayuba
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxNimrahafzal1
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1Elaf A.Saeed
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizeIruolagbePius
 
1. python programming
1. python programming1. python programming
1. python programmingsreeLekha51
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdfShivamKS4
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfshetoooelshitany74
 

Similar to Python Programming (20)

modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptx
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Python Programming 1.pptx
Python Programming 1.pptxPython Programming 1.pptx
Python Programming 1.pptx
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
 
Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
 
Python ppt
Python pptPython ppt
Python ppt
 
1. python programming
1. python programming1. python programming
1. python programming
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Unit -1 CAP.pptx
Unit -1 CAP.pptxUnit -1 CAP.pptx
Unit -1 CAP.pptx
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdf
 
bhaskars.pptx
bhaskars.pptxbhaskars.pptx
bhaskars.pptx
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Python Module-1.1.pdf
Python Module-1.1.pdfPython Module-1.1.pdf
Python Module-1.1.pdf
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Python Training
Python TrainingPython Training
Python Training
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
 

Recently uploaded

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

Python Programming

  • 1. PYTHON PROGRAMMING Python Basics Dr.T.M.SARAVANAN Associate Professor, Department of Computer Applications, Kongu Engineering College, Perundurai – 638 060.
  • 3. Introduction to pythonprogramming • High level, interpreted language • Object-oriented • General purpose • Web development (like: Django, and Bottle), • Scientific and Mathematical Computing (Orange, SciPy, NumPy) • Desktop graphical user Interfaces (Pygame, Panda3D).
  • 4. Other features of python includes the following: • Simple language which is easier to learn • Free and open source • Portability • Extensible and embeddable • Standard large library
  • 5. • Created by Guido van Rossum in 1991 • Why the name Python? • Not after a dangerous snake. • Rossum was fan of a famous TV Show comedy series from late Eighties. • The name "Python" was adopted from the same series "Monty Python's Flying Circus".
  • 6. Python’s Benevolent Dictator For Life “Python is an experiment in how much freedom programmers need. Too much freedom and nobody can read another's code; too little and expressiveness is endangered.” - Guido van Rossum
  • 7. Reasons toChoose Python asFirstLanguage • Simple Elegant Syntax • Not overly strict • Expressiveness of the language • Great Community and Support
  • 8. Installation of Python inWindows • Go to Download Python page on the official site (python.org/downloads/) and click Download Python 3.9.4. • When the download is completed, double-click the file and follow the instructions to install it. • When Python is installed, a program called IDLE is also installed along with it. It provides graphical user interface to work with Python.
  • 10. • Open IDLE, Write the following code below and press enter. print("Hello,W orld!") • To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N). • Write Python code and save (Shortcut: Ctrl+S) with .py file extension like: hello.py or your- first-program.py print("Hello,World!") • Go to Run > Run module (Shortcut: F5) and you can see the output.
  • 11. Python Code Execution Python’s traditional runtime execution model: source code you type is translated to byte code, which is then run by the Python Virtual Machine. Your code is automatically compiled, but then it is interpreted. Source code extension is .py Byte code extension is .pyc (compiled python code)
  • 16.
  • 18.
  • 19. Few Important Things toRemember • To represent a statement in Python, newline (enter) is used. • Use of semicolon at the end of the statement is optional (unlike languages like C/C++) • In fact, it's recommended to omit semicolon at the end of the statement in Python • Instead of curly braces { }, indentations are used to represent a block
  • 20. PythonKeywords • Keywords are the reserved words(can not be used as a identifier) in Python • Are case sensitive
  • 21. PythonIdentifiers • Name given to entities like class, functions, variables etc. in Python • Rules for writing identifiers • Can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_) • myClass, var_1 and print_this_to_screen, all are valid examples • Cannot start with a digit • 1variable is invalid, but variable1 is perfectly fine • Keywords cannot be used as identifiers • Cannot use special symbols like !, @, #, $, % etc. in our identifier • Can be of any length.
  • 22. Things to careabout • Python is a case-sensitive language. • Variable and variable are not the same. • Multiple words can be separated using an underscore, this_is_a_long_variable
  • 23. PythonStatement • Instructions that a Python interpreter can execute are called statements. • Two types • Single line statement: • For example, a = 1 is an assignment statement • Multiline statement: • In Python, end of a statement is marked by a newline character. • So, how to make multiline statement?
  • 24. • Technique1: • make a statement extend over multiple lines with the line continuation character (). • For example: a = 1+ 2+ 3+ 4+ 5+ 6+ 7+8+9
  • 25. • Technique2: • make a statement extend over multiple lines with the parentheses ( ) • For example: a=(1+2+3+ 4+5+6+ 7+8+9)
  • 26. • Technique3: • make a statement extend over multiple lines with the brackets [ ] and braces { }. • For example: colors=['red', 'blue', 'green']
  • 27. • We could also put multiple statements in a single line using semicolons, as follows a=1;b=2;c=3
  • 28. PythonIndentation • Most of the programming languages like C, C++, Java use braces { } to define a block of code • Python uses indentation • A code block (body of a function, loop etc.) starts with indentation and ends with the first un-indented line
  • 29.
  • 30.
  • 31. Error due to incorrectindentation
  • 32. PythonComments • To make the code much more readable. • Python Interpreter ignores comment. • Two types of comment is possible in python: • Single line comment and • Multi-line comment
  • 33. Single linecomment • In Python, we use the hash (#) symbol to start writing a comment. • It extends up to the newline character
  • 34. Multi-line comments • Two way: • By using # sign at the beginning of each line • By using either ‘ ‘ ‘ or “ “ “ (most common)
  • 35. PythonVariable • a variable is a named location used to store data in the memory. • Alternatively, variables are container that hold data which can be changed later throughout programming
  • 36. Declaring Variables • In Python, variables do not need declaration to reserve memory space. • The "variable declaration" or "variable initialization" happens automatically when we assign a value to a variable. • We use the assignment operator = to assign the value to a variable.
  • 38.
  • 39. Changing value of avariable
  • 40.
  • 41. Assigning same value to the multiplevariable
  • 42.
  • 43. Assigning multiplevalues to multiplevariables
  • 44.
  • 45. Constants • Value that cannot be altered by the program during normal execution. • In Python, constants are usually declared and assigned on a module • And then imported to the file
  • 47.
  • 48.
  • 49. Rules and Naming convention for variables and constants • Create a name that makes sense. Suppose, vowel makes more sense than v. • Use camelCase notation to declare a variable • For example: myName, myAge, myAddress • Use capital letters where possible to declare a constant • For example: PI,G,MASS etc.
  • 50. • Never use special symbols like !, @, #, $, %, etc. • Don't start name with a digit. • Constants are put into Python modules • Constant and variable names should have combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). • For example: snake_case, MACRO_CASE, camelCase, CapWords
  • 51. Literals Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as follows: 1. Numeric literals – Interger, Float, Complex 2. String literals – String, Character 3. Boolean literals – True or False 4. Special literals – None(Null Value) 5. Literal collections – List, Tuple, Dictionary and Set
  • 53.
  • 55.
  • 57.
  • 59.
  • 61.
  • 63.
  • 64. 08-04-2021 Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview Built-in Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories:
  • 65. 08-04-2021 Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range x = {"name" : "John", "age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset({"apple", "banana", "cherry"}) frozenset x = True bool x = b"Hello" bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview Setting the Data Type In Python, the data type is set when you assign a value to a variable:
  • 66. 08-04-2021 Setting the Specific Data Type If you want to specify the data type, you can use the following constructor functions: Example Data Type x = str("Hello World") str x = int(20) int x = float(20.5) float x = complex(1j) complex x = list(("apple", "banana", "cherry")) list x = tuple(("apple", "banana", "cherry")) tuple x = range(6) range x = dict(name="John", age=36) dict x = set(("apple", "banana", "cherry")) set x = frozenset(("apple", "banana", "cherry")) frozenset x = bool(5) bool x = bytes(5) bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview
  • 67. DataTypes • In python data types are classes and variables are instance (object) of these classes • Different types of data types in python are: • Python numbers • Python lists • Python tuples • Python strings • Python sets • Python dictionary
  • 69.
  • 70. PythonList • Ordered sequence of items • Can contain heterogeneous data • Syntax: • Items separated by commas are enclosed within brackets [ ] • Example: a= [1,2.2,'python']
  • 72.
  • 73. • Note: Lists are mutable, meaning, value of elements of a list can be altered.
  • 74. PythonTuple • Same as list but immutable. • Used to write-protect the data • Syntax: • Items separated by commas are enclosed within brackets ( ) • Example: • t = (5,'program', 1+3j)
  • 75.
  • 76.
  • 77.
  • 78.
  • 79. PythonStrings • use single quotes or double quotes to represent strings. • Multi-line strings can be denoted using triple quotes, ''' or """. • Strings are also immutable.
  • 80.
  • 81.
  • 82. PythonSet • Unordered collection of unique items • defined by values separated by comma inside braces { }
  • 83.
  • 84. • Set have unique values. They eliminate duplicates. • Example:
  • 85. • Since, set are unordered collection, indexing has no meaning. • Hence the slicing operator [] does not work. • Example:
  • 86. PythonDictionary • An unordered collection of key-value pairs. • Must know the key to retrieve the value. • Are defined within braces {} with each item being a pair in the form key: value • Key and value can be of any type
  • 87.
  • 88.
  • 89. Conversion between datatypes • Conversion can be done by using different types of type conversion functions like: • int(), • float(), • str() etc.
  • 93. Convert one sequence toanother
  • 94. • To convert to dictionary, each element must be a pair:
  • 95. Python TypeConversion and TypeCasting • The process of converting the value of one data type (integer, string, float, etc.) to another data type is type conversion • Python has two types of type conversion. • Implicit Type Conversion • Explicit Type Conversion
  • 96. • Type Conversion is the conversion of object from one data type to another data type • Implicit Type Conversion is automatically performed by the Python interpreter • Python avoids the loss of data in Implicit Type Conversion • Explicit Type Conversion is also called Type Casting, the data types of object are converted using predefined function by user • In Type Casting loss of data may occur as we enforce the object to specific data type
  • 97. Implicit TypeConversion • Automatically converts one data type to another data type • Always converts smaller data type to larger data type to avoid the loss of data
  • 98.
  • 99. Problem in implicit typeconversion
  • 100.
  • 101. ExplicitTypeConversion • Users convert the data type of an object to required data type. • Predefined functions like int(), float(), str(), etc. are to perform explicit type conversion • Is also called typecasting because the user casts (change) the data type of the objects. • Syntax : • (required_datatype)(expression) • Int(b)
  • 103.
  • 104. Python Input, Output andImport • Widely used functions for standard input and output operations are: • print() and • input()
  • 105. Python Output Using print()function
  • 106. Output formatting • Can be done by using the str.format() method • Is visible to any string object • Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by using numbers (tuple index).
  • 108. • We can even use keyword arguments to format the string
  • 109. • We can even format strings like the old printf() style used in C • We use the % operator to accomplish this
  • 110. Input()function • input() function to take the input from the user. • The syntax for input() is : • input([prompt]) • where prompt is the string we wish to display on the screen. • It is optional
  • 111. • Entered value 10 is a string, not a number. • To convert this into a number we can use int() or float() functions • This same operation can be performed using the eval(). It can evaluate expressions, provided the input is a string.
  • 112. PythonImport • When our program grows bigger, it is a good idea to break it into different modules. • A module is a file containing Python definitions and statements. • Python modules have a filename and end with the extension .py • Definitions inside a module can be imported to another module or the interactive interpreter in Python • We use the import keyword to do this
  • 113.
  • 114. • import some specific attributes and functions only, using the from keyword.
  • 115. PythonOperators • Operators are special symbols in Python that carry out arithmetic or logical computation. • The value that the operator operates on is called the operand. • For example: >>> 2+3 5 • Here, + is the operator that performs addition. • 2 and 3 are the operands and 5 is the output of the operation.
  • 119.
  • 121.
  • 122. Bitwiseoperators • Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. • For example, 2 is 10 in binary and 7 is 111. • In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
  • 123.
  • 124. Assignmentoperators • Assignment operators are used in Python to assign values to variables. • a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. • There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. • It is equivalent to a = a + 5.
  • 125.
  • 127. Identity operators • is and is not are the identity operators in Python. • They are used to check if two values (or variables) are located on the same part of the memory. • Two variables that are equal does not imply that they are identical.
  • 128.
  • 129. Membership operators • in and not in are the membership operators in Python • They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary). • In a dictionary we can only test for presence of key, not the value
  • 130.