Python Introduction New 2021-22 - Odd
Python Introduction New 2021-22 - Odd
WITH
PYTHON
1. Python Overview
• Python is ahigh-level ,interpreted, interactive andobject oriented-
scripting language
• Python was designed to be highly readable which usesEnglish words
frequently
• Python hasfewer syntactical constructions thanother languages
2
Cont…
• Python is Interpreted: It isprocessed at runtime by the interpreter and
you do not need to compile your program before executing it. This is
similar to PERL and PHP
interpret
source code output
Hello.py
1-4
Can you Name this person?
1-5
History of Python:
• Python was developed in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the
Netherlands.
1-6
Python’s Benevolent Dictator For Life
1-8
Monty Python's Flying Circus (1969 – 1974)
1-9
The name Python
• Van Rossum thought he needed a name that was short,
unique, and slightly mysterious, so he decided to call
the language
• Python…
1-10
• To top it all off, Peter Norvig said:
1-11
1-12
1-13
1-14
1-15
Real-world Applications of Python
– 1. Web Development
– 2. Game Development
– 3. Scientific and Numeric Applications
– 4. Artificial Intelligence and Machine Learning
– 5. Desktop GUI
– 6. Software Development
– 7. Enterprise-level/Business Applications
– 8. Education programs and training courses
– 9. Language Development
– 10. Operating Systems
– 11. Web Scraping Applications
– 12. Image Processing and Graphic Design Applications:
1-16
Python Features
• Simple and Easy to learn: Python hasrelatively few keywords, simple
structure , and aclearly defined syntax .
• Easy to maintain: Python's success is that its source code is fairly easy-to-
maintain.
• Portable : Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.
1-17
Python Features
• A broad standard library: One of Python'sgreatest strengths is the bulk of
the library isvery portable andcross-platform compatible on UNIX,
Windows.
1-19
Python Environment
• Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.)
• Win 9x/NT/2000
• Macintosh (PPC, 68K)
• OS/2
• DOS (multiple versions)
• PalmOS
• Nokia mobile phones
• Windows CE
• Acorn/RISC OS
• BeOS
• Amiga
• VMS/OpenVMS
• QNX
• VxWorks
• Psion
• Python has also been ported to the Java and .NET virtual machines.
1-20
Installing Python:
• Python is pre-installed on most Unix systems, including Linux and
MAC OS X
• The pre-installed version may not be the most recent one (2.6.2 and
3.1.1 as of Sept 09)
1-22
2. Python - Basic Syntax
• How to display “Hello, Python!” in Python programming language?
• How to find the sum of the expression 3+4*5
• Interactive Mode Programming:
Hello, Python!
>>> 3+4*5;
23
1-23
Script Mode Programming
• Script Mode Programming :
print("Hello, Python!”);
Hello, Python!
I love Python
1-24
Keywords/Reserved Words:
Keywords/Reserved words contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield 1-25
Lines and Indentation:
• One of the first caveats programmers encounter when learning Python is
the fact thatthere are no braces to indicate blocks of
code for class function definitions or
and flow control . Blocks of code
denoted
are line
by indentation , which is rigidly enforced .
• The number of spaces in the indentation is variable ,but all statements
within the block must be indented the same column . Both blocks in this
example are fine:
if(number % 2 == 0):
print("Answer")
print("Even")
else:
print("Answer")
print("Odd")
1-26
Multi-Line Statements:
• Statements in Python typically end with a new line. Python does, however,
allow the use of theline continuation character (\) to denote that the line
total = item_one + \
item_two + \
item_three
• Statements contained within the [], {}, or () brackets do not need to use
the line continuation character.
• For example:
word = 'word'
1-29
Comments in Python:
1-30
Using Blank Lines:
1-31
Multiple Statements on a Single Line:
1-32
Python Identifiers:
• APython identifier is aname used toidentify a variable ,function ,class ,
module , orother object . Anidentifier starts witha letter A to Z or a to z or
an underscore (_) followed by zero or more letters, underscores, and
digits (0 to 9).
• Pythondoes not allow punctuation characters such as @, $, and % within
identifiers . Python is acase sensitive programming language . Thus
Manpower andmanpower aretwo different identifiers in Python.
1-33
Python Identifiers (cont’d)
• Here are following identifier naming convention for Python :
1-34
Variables
• No need to declare
• Need to assign (initialize)
• use of uninitialized variable raises exception
• Not typed
if friendly:
greeting = "hello world"
else:
greeting = 12**2
print(greeting)
• Everything is a "variable":
• Even functions, classes, modules
Reference Semantics
• Assignment manipulates references
• x = y does not make a copy of y
• x = y makes x reference the object y references
• Very useful; but beware!
• Example:
>>> a = [1, 2, 3]
>>> b = a
>>> a.append(4)
>>> print b
[1, 2, 3, 4]
Changing a Shared List
a = [1, 2, 3] a 1 2 3
a
b=a 1 2 3
b
a
a.append(4) 1 2 3 4
b
Changing an Integer
a=1 a 1
a
b=a 1
b new int object created
by add operator (1+1)
a 2
a = a+1 old reference deleted
by assignment (a=...)
b 1
3. Python - Variable Types
• Variables are nothing but reserved memory locations tostore values .
This means that when you create a variable you reserve some space
in memory.
• Based on the data type of avariable , the interpreter allocates memory
anddecides what can be stored in the reserved memory .
• Therefore,by assigning different data types tovariables , youcan store
integers decimals
, , orcharacters inthese variables .
1-39
Assigning Values to Variables:
• Python variables do not have to be explicitly declared to reserve
memory space .
1-40
Multiple Assignment:
• You can also assign a single value to several variables
simultaneously. For example:
a=b=c=1
a, b, c = 1, 2, "john"
1-41
List of Operators:
A less common operator is the Modulo operator (%), which gives the
remainder of an integer division.
operand1 + operand2, or 3 + 5
Others are followed by one or more operands until the end of the line,
43
Example Expression Evaluations
An expression is any set of values and operators that will
produce a new value when evaluated. Here are some
examples, along with the new value they produce when
evaluated:
5 + 10 produces 15
“Hi” + “ “ + “Jay!” produces “Hi Jay!”
10 / (2+3) produces 2
10 > 5 produces True
10 < 5 produces False
10 / 3.5 produces 2.8571428571
10 / 3 produces 3.3333
10 % 3 produces 1
10 // 3 produces 3 44
Augmented Assignment Symbols
45
Augmented Assignment Symbols
46
Operator Overloading!
NOTE! Some operators will work in a different way depending upon what
their operands are.
For example, when you add two numbers you get the expected result: 3 + 3
produces 6.
But if you “add” two or more strings, the + operator produces a
47
Operator Overloading!
The modulo operator also works differently with strings:
“test %f” % 34 produces “test 34.000”
49
Effect of Data Types on Operator Results
10 / 3 produces 3.3333333
50
Simple Data types in Python
Numbers
51
Type Conversion
Data can sometimes be converted from one type to another. For example,
the string “3.0” is equivalent to the floating point number 3.0, which is
equivalent to the integer number 3
Functions exist which will take data in one type and return data in another
type.
52
Type Conversion
int() - Converts compatible data into an integer. This function will
truncate floating point numbers
53
Control Structures
• 3 control structures
1. Sequential structure
• Built into Python
2. Selection structure
• The if statement (Simple if statement)
• The if/else statement (Two-Way if statement)
• The if/else if/else if/else statement (Nested if statement)
• The if/elif/else statement (Multi-way if statement)
3. Repetition structure
• The while repetition structure
• The for repetition structure
54
Sequence Control Structure
55
if Selection Structure
true
false
56
Simple if statement
1-57
Simple if statement…
1-58
if/else Structure
false true
Grade >= 60
59
Two-Way if statement
Two-Way if statement Syntax:
friendly = ‘hi’
if friendly:
greeting = "hello world"
else:
greeting = 12**2
print(greeting)
1-61
if/else if/else if/else –
Nested if – else if – else if – else Structure
if condition :
statement
else: true
if condition : condition a case a action(s)
statement false
else:
if condition : true
statement condition b case b action(s)
else: false
if condition :
statement .
.
..
.
true
. z
condition case z action(s)
false
default action(s)
else:
statement 62
Nested if – else if – else if – else Structure
if condition :
statements
else :
if condition :
statements
else :
if condition :
statements
else :
if condition :
statements
else :
if condition :
statements
else :
statements 1-63
Nested if – else if – else if – else Structure
if(condition):
#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
else:
#Statements to execute if condition is false
else:
#Statements to execute if condition is false
true
if statement condition a case a action(s)
false
. .
.
.
true
last elif condition z case z action(s)
statemen false
t default action(s)
else
stateme
nt
if/elif/else multiple-selection structure.
65
Multi-way if statements - Syntax
if condition :
statements
elif condition :
statements
elif condition :
statements
elif condition :
statements
elif condition :
statements
.
.
.
else :
statements
1-66
Output:
true
num = 5 num = 10
if (num < 10): if (num < 10):
print(“Num is smaller than 10”) print(“Num is smaller than 10”)
print(“This statement will always be executed”) print(“This statement will always be executed”)
Output: Output:
Num is smaller than 10 This statement will always be
This statement will always be executed
executed
Output:
true
1-67
Nested if statements…
1-68
Example of Nested if statements…
num = 7
if (num != 0):
if (num > 0): Output:
print(“Number is greater than Zero”) Number is greater than Zero
i = 10
if (i = = 10):
if (i < 20):
print (i, "is smaller than 20")
if (i < 21):
print (i, "is smaller than 21")
Output:
10 is smaller than 20
10 is smaller than 21 1-69
Example with Python code
# get price from user and convert it into a float:
price = float( input(“Enter the price of one tomato: “))
if price < 1:
s = “That’s cheap, buy a lot!”
else:
s = “Too much, buy some carrots instead”
print(s)
70
Expression values?
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> if 0:
... print("0 is true“)
... else:
... print("0 is false“)
0 is false
>>> if 1:
... print("non-zero is true“)
non-zero is true
>>> if -1:
... print("non-zero is true“)
non-zero is true
>>> print 2 < 3
Syntax:
if (condition): statement 1; statement 2; statement 3;…;statement n
If the condition is true, then execute statement 1, statement 2 and so on
up to statement n.
In case if the condition is false then none of the statements will be
executed. 1-72
What is the expected output?
1-73
What is the expected output?
Output:
No fruits available
1-74
Logical Operators
• Operators
and
• Binary. Evaluates to true if both expressions are true
or
• Binary. Evaluates to true if at least one expression is true
not
• Unary. Returns true if the expression is false
75
Logical operatorsand, or, not
if gender == “female” and age >= 65:
seniorfemales = seniorfemales + 1
if not(found_what_we_need):
print(“didn’t find the item what we needed”)
1-79
Frequently Asked Questions
• Q #2) How do you write if-else statements in Python?
• Answer: Python has some conditional statements about
which two are if and else. Without any doubt, if we talk about
the large programs then, these two statements are most
commonly used in all the programming languages. Basically,
using “ if “ and “ else “ we set some conditional in our
program.
Basic syntax:
• if (condition):
// Body of “ if ”
• else: 1-80
What does Python “pass” do?
• Answer: The “pass” keyword will act as a space for future
code in the program. If it gets executed, nothing will happen
and will give no output. It is used because empty functions,
loops, and classes are not allowed in the programming. For
this Python develops the keyword which we can use if we
don’t know what to write in the particle function or class but
can be used for future use.
• For example:
• def demo( ):
pass
>>> if 1 < 2:
... pass
...
print ( n ) n=5
while ( n > 0 ) :
n = n -1 Output:
print (n)
n=n–1 5
4
print (‘Welcome!‘)
3
Print( ‘Welcome’ )
print (n ) 2
1
Welcome!
0
n=5 AN INFINITE LOOP
No Yes
n>0? n=5
No Yes
n>0? n=0
....
while True:
line = input( ‘ >>> ')
if line == 'done' : break
break
print ( line )
print ( 'Done!‘) ...
print 'Done'
FINISHING AN ITERATION WITH CONTINUE
• The continue statement ends the current iteration
and jumps to the top of the loop and starts the next
iteration
while True:
line = input('> ')
> hello there
if line[0] == '#': hello there
continue > # don't print this
> print this!
if line == 'done': print this!
break > done
Done!
print ( line )
print ( 'Done!‘)
No
True ? Yes
while True:
....
line = input('> ’)
if line[0] == '#' :
continue
if line == 'done' : continue
break
print line
print 'Done!' ...
print 'Done'
DEFINITE LOOPS
• Quite often we have a list of items of the lines in a
file - effectively a finite set of things
• We can write a loop to run the loop once for each
of the items in a set using the Python for construct
• These loops are called "definite loops" because
they execute an exact number of times
• We say that "definite loops iterate through the
members of a set"
INFINITE LOOPS
• range characteristics:
• One argument: used as ending limit
• Two arguments: starting value and ending limit
• Three arguments: starting value, ending limit and third
argument is step value
LETTING THE USER CONTROL THE LOOP
ITERATIONS
• Anaccumulator variable
3 41 12 9 74 15
9 41 12 3 74 15
smallest_so_far None9 3
FINDING THE
SMALLEST VALUE
smallest = None
$ python smallest.py
print ('Before the loop:')
Before the loop:
for value in [9, 41, 12, 3, 74, 15] :
99
if smallestis None :
9 41
smallest = value
9 12
elif value < smallest :
33
smallest = value
3 74
print (smallest, value)
3 15
print ('After the loop exe: ', smallest)
After the loop exe: 3