SlideShare a Scribd company logo
Python Programming
• Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
• It was created by Guido van Rossum during 1985- 1990 at National Research
Institute for Mathematics and Computer Science in the Netherlands.
• Python is designed to be highly readable.
• It uses English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.
• Python is Interpreted − Python is processed at runtime by the interpreter. You
do not need to compile your 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 supports Object-Oriented style or
technique of programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the beginner-
level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
INTRODUCTION
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
Python Features
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt −
$ pythonPython 2.4.3 (#1, Nov 11 2010, 13:34:43) [GCC 4.1.2 20080704 (Red Hat
4.1.2-48)] on linux2 Type "help", "copyright", "credits" or "license" for more
information.>>>
Type the following text at the Python prompt and press the Enter −
>>> print "Hello, Python!“
If you are running new version of Python, then you would need to use print
statement with parenthesis as in print ("Hello, Python!")
However in Python version 2.4.3, this produces the following result −
Hello, Python!
First Python Program
• A Python identifier is a name used to identify a variable, function, class, module or
other object.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
Python Identifiers
Reserved Words
• These are reserved words and you cannot use them as constant or variable or
any other identifier names.
• All the Python keywords contain lowercase letters only.
• Eg: and , assert , break , class, continue
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string. The triple
quotes are used to span the string across multiple lines. For example, all the
following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them. Following triple-quoted string is also ignored by
Python interpreter and can be used as a multiline comments:
'''
This is a multiline
comment.
'''
Python - Variable Types
• Variables are nothing but reserved memory locations to store values.
• This means that when you create a variable you reserve some space in
memory. Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.
• Therefore, by assigning different data types to variables, you can store integers,
decimals or characters in these variables.
Assigning Values to Variables
• Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal
sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable and the operand
to the right of the = operator is the value stored in the variable.
Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously. For
example − a = b = c = 1
• Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple
variables. For example − a,b,c = 1,2,"john"
• Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Standard Data Types
Python has five standard data types −
1) Numbers
2) String
3) List
4) Tuple
5) Dictionary
Python Numbers
• Number data types store numeric values. Number objects are created when you
assign a value to them. For example : var1 = 1var2 = 10
• You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is: del var1[,var2[,var3[....,varN]]]]
• You can delete a single object or multiple objects by using the del statement. For
example : del var
del var_a, var_b
Python supports four different numerical types −
1. int (signed integers)
2. long (long integers, they can also be represented in octal and hexadecimal)
3. float (floating point real values)
4. complex (complex numbers)
 Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
 Python allows for either pairs of single or double quotes.
 Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the end.
 The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
For example:
str = 'Hello World!‘
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
Print( str[2:5]) # Prints characters starting from 3rd to 5th
Print( str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
Print( str + "TEST”) # Prints concatenated string
Output
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Strings
 Lists are the most versatile of Python's compound data types.
 A list contains items separated by commas and enclosed within square brackets
([]).
 To some extent, lists are similar to arrays in C.
 One difference between them is that all the items belonging to a list can be of
different data type.
 The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1.
 The plus (+) sign is the list concatenation operator, and the asterisk (*) is the
repetition operator.
Python Lists
For Eg:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print(list) # Prints complete list
print (list[0]) # Prints first element of the list
Print( list[1:3] # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Lists
• A tuple is another sequence data type that is similar to the list.
• A tuple consists of a number of values separated by commas.
• Unlike lists, however, tuples are enclosed within parentheses.
• The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ]
) and their elements and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated.
• Tuples can be thought of as read-only lists.
Python Tuples
For example :
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
Print(tuple) # Prints complete list
print (tuple[0]) # Prints first element of the list
Print( tuple[1:3]) # Prints elements starting from 2nd till 3rd
Print( tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints list two times
Print( tuple + tinytuple ) # Prints concatenated lists
Output:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Python Tuples
• Python's dictionaries are kind of hash table type.
• They work like associative arrays or hashes found in Perl and consist of key-value
pairs. A dictionary key can be of any data type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.
• Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).
• Dictionaries are simply unordered.
Python Dictionary
For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print(dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
This produce the following result −
This is one
This is two
{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])
Python Dictionary
Operators are the constructs which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operators
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Python - Basic Operators
Python - Basic Operators
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand
operand.
a – b = -10
*
Multiplication
Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b / a = 2
% Modulus Divides left hand operand by right hand operand and
returns remainder
b % a = 0
** Exponent Performs exponential (power) calculation on
operators
a**b =10 to the power
20
// Floor Division - The division of operands where the
result is the quotient in which the digits after the
decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity)
−
9//2 = 4 and 9.0//2.0 =
4.0, -11//3 = -4, -
11.0//3 = -4.0
 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.
print()
Eg:
x = ("apple", "banana", "cherry")
print(x)
O/p: ('apple', 'banana', 'cherry')
print("Hello", "how are you?", sep=" --- ")
O/p: Hello --- how are you?
 This function first takes the input from the user and then evaluates the
expression, which means Python automatically identifies whether user entered
a string or a number or list.
 If the input provided is not correct then either syntax error or exception is
raised by python.
input()
Eg:
val = input("Enter your value: ")
print(val)
O/p:
Decision-Making In Python
• Decisions are questions with answers that are
either true or false (Boolean) e.g., Is it true that
the variable ‘num’ is positive?
• The program branches one way or another
depending upon the answer to the question (the
result of the Boolean expression).
• Decision making/branching constructs
(mechanisms) in Python:
– If
– If-else
– If-elif-else
Decision Making With An ‘If’
Question? Execute a statement
or statements
True
False
Remainder of
the program
The ‘If’ Construct
• Decision making: checking if a condition is
true (in which case something should be done).
• Format:
(General format)
if (Boolean expression):
body
(Specific structure)
if (operand relational operator operand):
body
Boolean expression
Note: Indenting the body
is mandatory!
• Body of the if consists of multiple statements
• Format:
if (Boolean expression):
s1
s2
:
sn
sn+1
Body
If (Compound Body)
End of the indenting denotes the end
of decision-making
• Decision making: checking if a condition is true (in which case something
should be done) but also reacting if the condition is not true (false).
• Format:
if (operand relational operator operand):
body of 'if'
else:
body of 'else'
additional statements
The If-Else Construct
If-Else Construct (2)
• Example:
if (age < 18):
print(“Not an adult”)
else:
print(“Adult”)
print(“Tell me more about yourself”)
Decision Making With If-Elif-Else
Question?
True Statement or
statements
False
Question?
Remainder of
the program
Statement or
statements
False
True Statement or
statements
Multiple If-Elif-Else: Mutually
Exclusive Conditions
• Format:
if (Boolean expression 1):
body 1
elif (Boolean expression 2):
body 2
:
else
body n
statements after the conditions
Programs using if statement
• Program to check for an even number
• Program to check eligibility to vote
• Program to display biggest of 3 numbers
• Program to check whether the accepted
number is a +ve , -ve or zero
• Program to check whether a number is
divisible by 5 and 7 or not.
Iteration
• Iteration allows us to write programs that
repeat some code over and over again
• The easiest form of iteration is using a while
loop
• While loops read a lot like English (like almost
everything in Python)
– While counter is greater than 0, execute some
code
– While user guess does not equal my number, keep
asking for a new number
While Loop
• While loops are like if, elif, and else statements
in that only the indented code is part of the
loop
– Be careful with indentation
• Like if and elif statements, while loops must
check to see if some condition is true
– While it’s true, execute some code
– When it’s not true, exit the loop
Simple While Loop Example
• Let’s write a while loop that prints the
numbers from 1 to 10
i = 1 #initialize i 1
while i<=10: #execute the code in the loop
print(i) #until i >10
i = i +1 #increment i
print("all done!")
Another While Loop Example
count =1
num =3
while count<5:
print(num*count)
count = count+1
*this prints 3, 6, 9, 12
Programs using While Loop
• Program to display numbers from 1 to n
• Program to display the even numbers till n
• Program to display factorial of a number
• Program to check for a prime number
• Program to find the sum of squares of
numbers till n
The for Loop
for name in range(max):
statements
– Repeats for values 0 (inclusive) to max (exclusive)
for i in range(5):
print(i)
0
1
2
3
4
for Loop Variations
for name in range(min, max):
statements
for name in range(min, max, step):
statements
– Can specify a minimum other than 0, and a step
other than 1 for i in range(2, 6):
print(i)
2
3
4
5
for i in range(15, 0, -5):
print(i)
15
10
5

More Related Content

What's hot (20)

PPT
Introduction to Python
amiable_indian
 
PPTX
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
DOCX
PYTHON NOTES
Ni
 
PDF
Python basic
Saifuddin Kaijar
 
ODP
Python slide.1
Aswin Krishnamoorthy
 
PDF
Zero to Hero - Introduction to Python3
Chariza Pladin
 
PPSX
Programming with Python
Rasan Samarasinghe
 
PDF
Python Tutorial
AkramWaseem
 
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
PDF
Python 3.x quick syntax guide
Universiti Technologi Malaysia (UTM)
 
ODP
Python Presentation
Narendra Sisodiya
 
PDF
Python programming msc(cs)
KALAISELVI P
 
PDF
Python Workshop
Saket Choudhary
 
PPTX
Programming in Python
Tiji Thomas
 
PDF
Python Basics
tusharpanda88
 
PPTX
Python training
Kunalchauhan76
 
PDF
Python made easy
Abhishek kumar
 
PPTX
Chapter 9 python fundamentals
Praveen M Jigajinni
 
PPTX
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Introduction to Python
amiable_indian
 
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
PYTHON NOTES
Ni
 
Python basic
Saifuddin Kaijar
 
Python slide.1
Aswin Krishnamoorthy
 
Zero to Hero - Introduction to Python3
Chariza Pladin
 
Programming with Python
Rasan Samarasinghe
 
Python Tutorial
AkramWaseem
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Python 3.x quick syntax guide
Universiti Technologi Malaysia (UTM)
 
Python Presentation
Narendra Sisodiya
 
Python programming msc(cs)
KALAISELVI P
 
Python Workshop
Saket Choudhary
 
Programming in Python
Tiji Thomas
 
Python Basics
tusharpanda88
 
Python training
Kunalchauhan76
 
Python made easy
Abhishek kumar
 
Chapter 9 python fundamentals
Praveen M Jigajinni
 
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 

Similar to 1. python programming (20)

PPTX
introduction to python programming concepts
GautamDharamrajChouh
 
PDF
Python quick guide
Hasan Bisri
 
PPTX
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
PPTX
Python unit 2 is added. Has python related programming content
swarna16
 
PPTX
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
PPTX
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
PPT
Unit 2 python
praveena p
 
PPT
Python - Module 1.ppt
jaba kumar
 
PPTX
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
PPTX
Python 01.pptx
AliMohammadAmiri
 
PPTX
Python-Basics.pptx
TamalSengupta8
 
PDF
Python Programming
Saravanan T.M
 
PPTX
Python
Gagandeep Nanda
 
PPTX
PYTHON PROGRAMMING.pptx
swarna627082
 
PPTX
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
PPTX
Python Programming 1.pptx
Francis Densil Raj
 
PDF
problem solving and python programming UNIT 2.pdf
rajesht522501
 
PDF
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
 
PPTX
Chapter1 python introduction syntax general
ssuser77162c
 
PPTX
Python Traning presentation
Nimrita Koul
 
introduction to python programming concepts
GautamDharamrajChouh
 
Python quick guide
Hasan Bisri
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
Python unit 2 is added. Has python related programming content
swarna16
 
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
Unit 2 python
praveena p
 
Python - Module 1.ppt
jaba kumar
 
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
Python 01.pptx
AliMohammadAmiri
 
Python-Basics.pptx
TamalSengupta8
 
Python Programming
Saravanan T.M
 
PYTHON PROGRAMMING.pptx
swarna627082
 
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
Python Programming 1.pptx
Francis Densil Raj
 
problem solving and python programming UNIT 2.pdf
rajesht522501
 
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
 
Chapter1 python introduction syntax general
ssuser77162c
 
Python Traning presentation
Nimrita Koul
 
Ad

More from sreeLekha51 (6)

DOCX
the same story in different tenses
sreeLekha51
 
DOCX
What is light
sreeLekha51
 
PPTX
Computer science and engineering
sreeLekha51
 
PPTX
MY FATHER
sreeLekha51
 
PPTX
My father
sreeLekha51
 
PPTX
Health education
sreeLekha51
 
the same story in different tenses
sreeLekha51
 
What is light
sreeLekha51
 
Computer science and engineering
sreeLekha51
 
MY FATHER
sreeLekha51
 
My father
sreeLekha51
 
Health education
sreeLekha51
 
Ad

Recently uploaded (20)

PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Human Resources Information System (HRIS)
Amity University, Patna
 

1. python programming

  • 2. • Python is a general-purpose interpreted, interactive, object-oriented, and high- level programming language. • It was created by Guido van Rossum during 1985- 1990 at National Research Institute for Mathematics and Computer Science in the Netherlands. • Python is designed to be highly readable. • It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages. • Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your 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 supports Object-Oriented style or technique of programming that encapsulates code within objects. • Python is a Beginner's Language − Python is a great language for the beginner- level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. INTRODUCTION
  • 3. Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. Easy-to-read − Python code is more clearly defined and visible to the eyes. Easy-to-maintain − Python's source code is fairly easy-to-maintain. A broad standard library − Python's bulk of the library is very portable and cross- platform compatible on UNIX, Windows, and Macintosh. Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code. Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases − Python provides interfaces to all major commercial databases. GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable − Python provides a better structure and support for large programs than shell scripting. Python Features
  • 4. Invoking the interpreter without passing a script file as a parameter brings up the following prompt − $ pythonPython 2.4.3 (#1, Nov 11 2010, 13:34:43) [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 Type "help", "copyright", "credits" or "license" for more information.>>> Type the following text at the Python prompt and press the Enter − >>> print "Hello, Python!“ If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello, Python!") However in Python version 2.4.3, this produces the following result − Hello, Python! First Python Program
  • 5. • A Python identifier is a name used to identify a variable, function, class, module or other object. • An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). • Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python. Python Identifiers Reserved Words • These are reserved words and you cannot use them as constant or variable or any other identifier names. • All the Python keywords contain lowercase letters only. • Eg: and , assert , break , class, continue
  • 6. Quotation in Python Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal − word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" Comments in Python A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments: ''' This is a multiline comment. '''
  • 7. Python - Variable Types • Variables are nothing but reserved memory locations to store values. • This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. • Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables. Assigning Values to Variables • Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. • The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. Multiple Assignment • Python allows you to assign a single value to several variables simultaneously. For example − a = b = c = 1 • Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example − a,b,c = 1,2,"john" • Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c.
  • 8. Standard Data Types Python has five standard data types − 1) Numbers 2) String 3) List 4) Tuple 5) Dictionary Python Numbers • Number data types store numeric values. Number objects are created when you assign a value to them. For example : var1 = 1var2 = 10 • You can also delete the reference to a number object by using the del statement. The syntax of the del statement is: del var1[,var2[,var3[....,varN]]]] • You can delete a single object or multiple objects by using the del statement. For example : del var del var_a, var_b Python supports four different numerical types − 1. int (signed integers) 2. long (long integers, they can also be represented in octal and hexadecimal) 3. float (floating point real values) 4. complex (complex numbers)
  • 9.  Strings in Python are identified as a contiguous set of characters represented in the quotation marks.  Python allows for either pairs of single or double quotes.  Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.  The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example: str = 'Hello World!‘ print (str) # Prints complete string print (str[0]) # Prints first character of the string Print( str[2:5]) # Prints characters starting from 3rd to 5th Print( str[2:]) # Prints string starting from 3rd character print (str * 2) # Prints string two times Print( str + "TEST”) # Prints concatenated string Output Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST Python Strings
  • 10.  Lists are the most versatile of Python's compound data types.  A list contains items separated by commas and enclosed within square brackets ([]).  To some extent, lists are similar to arrays in C.  One difference between them is that all the items belonging to a list can be of different data type.  The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1.  The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. Python Lists
  • 11. For Eg: list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print(list) # Prints complete list print (list[0]) # Prints first element of the list Print( list[1:3] # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting from 3rd element print (tinylist * 2) # Prints list two times print (list + tinylist) # Prints concatenated lists Output: ['abcd', 786, 2.23, 'john', 70.2] abcd [786, 2.23] [2.23, 'john', 70.2] [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] Python Lists
  • 12. • A tuple is another sequence data type that is similar to the list. • A tuple consists of a number of values separated by commas. • Unlike lists, however, tuples are enclosed within parentheses. • The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. • Tuples can be thought of as read-only lists. Python Tuples
  • 13. For example : tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') Print(tuple) # Prints complete list print (tuple[0]) # Prints first element of the list Print( tuple[1:3]) # Prints elements starting from 2nd till 3rd Print( tuple[2:]) # Prints elements starting from 3rd element print (tinytuple * 2) # Prints list two times Print( tuple + tinytuple ) # Prints concatenated lists Output: ('abcd', 786, 2.23, 'john', 70.2) abcd (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john') Python Tuples
  • 14. • Python's dictionaries are kind of hash table type. • They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be of any data type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). • Dictionaries are simply unordered. Python Dictionary
  • 15. For example − dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print(dict['one']) # Prints value for 'one' key print (dict[2]) # Prints value for 2 key print (tinydict) # Prints complete dictionary print (tinydict.keys()) # Prints all the keys print (tinydict.values()) # Prints all the values This produce the following result − This is one This is two {'name': 'john', 'code': 6734, 'dept': 'sales'} dict_keys(['name', 'code', 'dept']) dict_values(['john', 6734, 'sales']) Python Dictionary
  • 16. Operators are the constructs which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Operators Python language supports the following types of operators.  Arithmetic Operators  Comparison (Relational) Operators  Assignment Operators  Logical Operators  Bitwise Operators  Membership Operators  Identity Operators Python - Basic Operators
  • 17. Python - Basic Operators Operator Description Example + Addition Adds values on either side of the operator. a + b = 30 - Subtraction Subtracts right hand operand from left hand operand. a – b = -10 * Multiplication Multiplies values on either side of the operator a * b = 200 / Division Divides left hand operand by right hand operand b / a = 2 % Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0 ** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20 // Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) − 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, - 11.0//3 = -4.0
  • 18.  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. print() Eg: x = ("apple", "banana", "cherry") print(x) O/p: ('apple', 'banana', 'cherry') print("Hello", "how are you?", sep=" --- ") O/p: Hello --- how are you?
  • 19.  This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list.  If the input provided is not correct then either syntax error or exception is raised by python. input() Eg: val = input("Enter your value: ") print(val) O/p:
  • 20. Decision-Making In Python • Decisions are questions with answers that are either true or false (Boolean) e.g., Is it true that the variable ‘num’ is positive? • The program branches one way or another depending upon the answer to the question (the result of the Boolean expression). • Decision making/branching constructs (mechanisms) in Python: – If – If-else – If-elif-else
  • 21. Decision Making With An ‘If’ Question? Execute a statement or statements True False Remainder of the program
  • 22. The ‘If’ Construct • Decision making: checking if a condition is true (in which case something should be done). • Format: (General format) if (Boolean expression): body (Specific structure) if (operand relational operator operand): body Boolean expression Note: Indenting the body is mandatory!
  • 23. • Body of the if consists of multiple statements • Format: if (Boolean expression): s1 s2 : sn sn+1 Body If (Compound Body) End of the indenting denotes the end of decision-making
  • 24. • Decision making: checking if a condition is true (in which case something should be done) but also reacting if the condition is not true (false). • Format: if (operand relational operator operand): body of 'if' else: body of 'else' additional statements The If-Else Construct
  • 25. If-Else Construct (2) • Example: if (age < 18): print(“Not an adult”) else: print(“Adult”) print(“Tell me more about yourself”)
  • 26. Decision Making With If-Elif-Else Question? True Statement or statements False Question? Remainder of the program Statement or statements False True Statement or statements
  • 27. Multiple If-Elif-Else: Mutually Exclusive Conditions • Format: if (Boolean expression 1): body 1 elif (Boolean expression 2): body 2 : else body n statements after the conditions
  • 28. Programs using if statement • Program to check for an even number • Program to check eligibility to vote • Program to display biggest of 3 numbers • Program to check whether the accepted number is a +ve , -ve or zero • Program to check whether a number is divisible by 5 and 7 or not.
  • 29. Iteration • Iteration allows us to write programs that repeat some code over and over again • The easiest form of iteration is using a while loop • While loops read a lot like English (like almost everything in Python) – While counter is greater than 0, execute some code – While user guess does not equal my number, keep asking for a new number
  • 30. While Loop • While loops are like if, elif, and else statements in that only the indented code is part of the loop – Be careful with indentation • Like if and elif statements, while loops must check to see if some condition is true – While it’s true, execute some code – When it’s not true, exit the loop
  • 31. Simple While Loop Example • Let’s write a while loop that prints the numbers from 1 to 10 i = 1 #initialize i 1 while i<=10: #execute the code in the loop print(i) #until i >10 i = i +1 #increment i print("all done!")
  • 32. Another While Loop Example count =1 num =3 while count<5: print(num*count) count = count+1 *this prints 3, 6, 9, 12
  • 33. Programs using While Loop • Program to display numbers from 1 to n • Program to display the even numbers till n • Program to display factorial of a number • Program to check for a prime number • Program to find the sum of squares of numbers till n
  • 34. The for Loop for name in range(max): statements – Repeats for values 0 (inclusive) to max (exclusive) for i in range(5): print(i) 0 1 2 3 4
  • 35. for Loop Variations for name in range(min, max): statements for name in range(min, max, step): statements – Can specify a minimum other than 0, and a step other than 1 for i in range(2, 6): print(i) 2 3 4 5 for i in range(15, 0, -5): print(i) 15 10 5