Python Introduction New 2021-22 - Odd

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 120

PROGRAMMING

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

• Python is Beginner's Language: Python is a great language for the


beginner programmers and supports the development of a wide range
simple text processing to
of applications, from WWW browsers
applications

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

• Python is Interactive: Means that you can actually sit at a Python


prompt and interact with the interpreter directly to write your
programs

• Python is Object-Oriented: Means that Python supports Object-


Oriented style or technique of programming that encapsulates code
within objects
3
Compiling and interpreting
• Many languages require you to compile (translate) your program into a
form that themachine understands .
compile execute
source code byte code output
Hello.java Hello.class

• Python is instead directlyinterpreted intomachine instructions .

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.

• Actual DOB of Python language: 20 th Feb 1991

• Python is derived from many other languages,including ABC, Modula-3, C,


C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
• Python is copyrighted, Like other languages/scriptsPerl ,Python source code
is now available under the GNU General Public License (GPL).

1-6
Python’s Benevolent Dictator For Life

Python isnow maintained by a core


development team at theinstitute

Guido van Rossum is still holding a


vital role in directing it's progress

“Python is an experimental program in


showing how much freedom the
programmers need.
Guido Van Rossum
1-7
Why the name Python?
• When he began implementing Python. He was also reading

the published scripts from “Monty Python's Flying

Circus”, a BBC comedy series from the 1970s.

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:

• “Python has been an important part of Google


since the beginning, and remains so as the system
grows and evolves. Today dozens of Google
engineers use Python, and we’re looking for more
people with skills in this language.”

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 read: Python code is much more clearly written by usingEnglish


likewords (High Level Programming Language)

• Easy to maintain: Python's success is that its source code is fairly easy-to-
maintain.

• Platform Independent: Python program can run on any


– Write Once Run Anywhere ( WORA )

• 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.

• Interactive Mode: Support for aninteractive mode in whichyou can enter


results from a terminal right to the language, allowing interactive testing
debugging of snippets of code
and .

• 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.
1-18
Python Features (cont…)
• 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 advanced
programs than shell scripting.

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)

• Download from http://python.org/download/

• Python comes with a large library of standard modules


• There are several options for an IDLE

– IDLE – works well with Windows


– Emacs with python-mode or your favorite text editor

– Eclipse with Pydev (http://pydev.sourceforge.net/)


1-21
IDLE Development Environment
• IDLE is an Integrated DeveLopment Environ-ment for Python, typically
used on Windows
• Multi-window text editor with syntax highlighting, auto-completion, smart
indent and other.

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:

>>> print("Hello, Python!“);

Hello, Python!

>>> 3+4*5;

23

1-23
Script Mode Programming
• Script Mode Programming :

Invoking the interpreter with a script parameter begins execution of the


script and continues until the script is finished. When the script is
finished, the interpreter is no longer active.

For example, put the following in one hello.py, and run,

print("Hello, Python!”);

print("I love Python”)

The output will be:

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

should continue. For example:

total = item_one + \

item_two + \
item_three
• Statements contained within the [], {}, or () brackets do not need to use
the line continuation character.
• For example:

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']


1-27
1-28
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 can be 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."""

1-29
Comments in Python:

• A hash sign (#) that is not inside a string literal begins a

comment. All characters after the # and up to


the physical line end are part of the comment, and
the Python interpreter ignores them.

1-30
Using Blank Lines:

• Aline containing only whitespace ,possibly with a comment , isknown


as ablank line , andPython totally ignores it .

• In aninteractive interpreter session , you must enter an empty


physical line toterminate amultiline statement .

1-31
Multiple Statements on a Single Line:

• The semicolon ( ; ) allowsmultiple statements on the single line given


that neither statement starts a new code block.

• Here is asample snip using the semicolon :

import math; inputNumber = int(input()); sqrtOfANumber = math.


sqrt(inputNumber);

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 :

– Class names start with anuppercase letter andall other identifiers


with alowercase letter .
– Starting an identifier witha single leading underscore indicates by
convention that theidentifier is meant to beprivate .

– Starting an identifier withtwo leading underscores (__)


indicates astrongly private identifier .
– If the identifier also ends with two trailing underscores , the
identifier is alanguage-defined special name .

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 .

• The declaration happens automatically when youassign a value to a


variable . The equal sign (=) is used to assign values to variables.

• counter = 100 # An integer assignment


• miles = 1000.0 # A floating point
• name = "John" # A string
• print(counter)
• print(miles)
• print(name)

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:

Some operators should be familiar from the world of mathematics such


as Addition (+), Subtraction (-), Multiplication (*), and Division (/),
Modulo/Remainder Division (%), Floor Division (//).

Python also has comparison operators, such as Less-Than (<), Greater-


Than (>), Less-Than-or-Equal(<=), Greater-Than-or-Equal (>=), and

Equality-Test (==). These operators produce a True or False


value.

A less common operator is the Modulo operator (%), which gives the
remainder of an integer division.

10 divided by 3 is 9 with a remainder of 1:

10 / 3 produces 3, while 10 % 3 produces 1 42


Operators

Python has many operators. Some examples are:

+, -, *, /, %, //, >, <, ==, <=, >=, !=


Operators perform an action on one or more operands. Some operators
accept operands before and after themselves:

operand1 + operand2, or 3 + 5
Others are followed by one or more operands until the end of the line,

such as: print( “Hi!” , 32, 48)

When operators are evaluated, they perform action on their operands,


and produce a new value.

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

• Augmented addition assignment symbols


– x = x + 5 is the same as x += 5

– Can’t use ++ like in c, c++ and Java!

• Other math signs


– The same rule applies to any other mathematical symbol
*, ** ( power of) , /, %

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

concatenated version of the strings: “Hi” + “Jay” produces “HiJay”


Multiplying strings by a number repeats the string!

“Hi Jay” * 3 produces “Hi JayHi JayHiJay”


The modulo operator also works differently with strings:
“test %f” % 34 produces “test 34.000”

47
Operator Overloading!
The modulo operator also works differently with strings:
“test %f” % 34 produces “test 34.000”

>>> "test %f" % 34


'test 34.000000'

>>> "test %f" 34


SyntaxError: invalid syntax
>>> "test %f" , 34
('test %f', 34)
48
Data Types

In Python, all data has an associated data “Type”.


You can find the “Type” of any piece of data by using the type() function:

type( “Hi!”) produces <type 'str'>


type( True ) produces <type 'bool'>
type( 5) produces <type 'int'>
type(5.0) produces <type 'float'>
Note that python supports two different types of numbers, Integers (int)
and Floating point numbers (float). Floating Point numbers have a
fractional part (digits after the decimal place), while Integers do not!

49
Effect of Data Types on Operator Results

Math operators work differently on Floats and ints:

int + int produces an int

int + float or float + int produces a float

This is especially important for division, as integer division produces a


different result from floating point division:

10 / 3 produces 3.3333333

10 / 3.0 produces 3.3333333

Other operators work differently on different data types: + (addition) will


add two numbers, but concatenate strings.

50
Simple Data types in Python

• The simple data types in Python are:

Numbers

int – Integer: -5, 10, 77

float – Floating Point numbers: 3.1457, 0.34

bool – Booleans (True or False)

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.

int() - Converts compatible data into an integer. This function will


truncate floating point numbers

float() - Converts compatible data into a float.

str() - Converts compatible data into a string.

52
Type Conversion
int() - Converts compatible data into an integer. This function will
truncate floating point numbers

float() - Converts compatible data into a float.

str() - Converts compatible data into a string.


Examples:
int(3.3) produces 3
float(“3.5”) produces 3.5
int(“7”) produces 7
int(“7.1”) throws an ERROR!
float(“Test”) Throws an ERROR!
str(3.3) produces “3.3”
float(3) produces 3.0

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

add grade to total total = total + grade;

add 1 to counter counter = counter + 1;

Sequence structure flowchart with pseudo


code.

55
if Selection Structure

true

Grade >= 60 print “Passed”

false

if single-selection structure flowchart.

56
Simple if statement

Simple if statement Syntax:


number = int(input("Enter the number to find odd or even"))
if (condition) :
statement
if(number % 2 == 0):
statement
print("Answer")
statement
print("Even")
if(number % 2 != 0):
print("Answer")
print("Odd")

1-57
Simple if statement…

1-58
if/else Structure

false true
Grade >= 60

print “Failed” print “Passed”

if/else double-selection structure flowchart.

59
Two-Way if statement
Two-Way if statement Syntax:

number = int(input("Enter the number to


if (condition) :
statement find odd or even"))
statement
else : if(number % 2 == 0):
statement
print("Answer")
statement
print("Even")
else:
print("Answer")
print("Odd")
1-60
What will be the output

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

Nested if-else Syntax:


Here we have includedto
           #Statements the “if-else”if block
execute inside
condition an if block, you
is false
can also include an “if-else” block inside “else” block. 1-64
if/elif/else Selection Structure

true
if statement condition a case a action(s)
false

first elif condition b


true
case b action(s)
statement 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

What is the expected output?

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

if (‘Python’ in [‘Java', ‘Python’, ‘C#’]):


     print(“true”)

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!”

elif price < 3:


s = “Okay, buy a few”

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

True Expressions have integer values.


0 is False,
non-0 is True. 71
Python If Statement/(s) In One Line

In Python, we can write


“if” statements,
“if-else” statements and
“elif” statements

in one line without worrying about the indentation.

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?

if (‘a’ in ‘fruits’): print(“Apple”); print(“Orange”)


else: print(“Mango”); print(“Grapes”)
Output:
Mango
Grapes

1-73
What is the expected output?

if (‘a’ in ‘fruits’): print(“Apple”); print(“Orange”)


elif (‘e’ in ‘fruits’): print(“Mango”); print(“Grapes”)
else: print(“No fruits available”)

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 iq > 250 or iq < 20:


strangevalues = strangevalues + 1

if not(found_what_we_need):
print(“didn’t find the item what we needed”)

# NB: can also use !=


if i != j:
print(“Both “,I,“and “,j,“are Different values!!!”)
76
Multiple Conditions In If Statements
• It’s not that you can only write one condition inside an “if”
statement, we can also evaluate multiple conditions in an “if”
statement like below.
• Example: 1
• num1 = 10
• num2 = 20
• num3 = 30
• if (num1 == 10 and num2 == 20 and num3 == 30):
•              print(“All the conditions are true”)
• Output:
• All the conditions are true
1-77
What is the expected output?
currentYear = int(input (" Enter the year: " ) )
month = int(input("Enter the month: " ) )
if ((currentYear % 4 ) == 0 and (currentYear % 100 ) != 0 or (currentYear % 400 ) == 0 ):
 print("Leap Year")
 if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
•                print("There are 31 days in this month " )
•  elif ( month == 4 or month == 6 or month == 9 or month == 11 ):
•        print("There are 30 days in this month " )
•  elif ( month == 2 ):
•        print("There are 29 days in this month " )
•  else:
•        print("Invalid month ")
elif ( ( currentYear % 4 ) != 0 or ( currentYear % 100 ) != 0 or ( currentYear % 400 ) != 0 ):
•  print("Non Leap Year " )
•  if ( month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 ):
•        print("There are 31 days in this month" )
• elif ( month == 4 or month == 6 or month == 9 or month == 11 ):
•        print("There are 30 days in this month " )
• elif ( month == 2 ):
•        print("There are 28 days in this month ")
• else:
•        print("Invalid month " )
else:
•        print( " Invalid Year " )
1-78
Frequently Asked Questions
• Q #1) Can we write else if statements in one line Python?
• Answer: Yes, we can use if-else in one line. In Python, we
can convert if-else into one conditional statement.

• Refer to the example below:


num = 7
output = ‘Greater than 0’ if num > 0 else ‘Smaller than 0’
print(output)

• The output will be:


• Greater than 0

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

• The output will be nothing. 1-81


keyword pass : do nothing
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 1 < 2:
... pass
...

Sometimes useful, e.g. during development:


if a <= 5 and c <= 5:
print(“Oh no, both below 5! Fix problem”)
if a > 5 and c <= 5:
pass # figure out what to do later
if a <= 5 and c > 5:
pass # figure out what to do later
if a > 5 and c > 5:
pass # figure out what to do later
Program 82
n=5 REPEATED STEPS
No Yes syntax:
n>0?
while ( condition ) :
print ( n ) statements
else :
n = n -1 statements
Loops (repeated steps) have iteration
variables that change each time through a
Print( ‘Welcome’ ) loop. Often these iteration variables go
through a sequence of numbers.
n=5
REPEATED STEPS
No Yes Program:
n>0?

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

print ( ‘Lather’ ) while n > 0 :


print ( 'Lather’ )
print ( ‘Rinse’ ) print ( 'Rinse‘)
print ( 'Dry off!‘)

Print( ‘ Dry off ’ ) What is wrong with this loop?


n=0
ANOTHER LOOP

No Yes
n>0? n=0

print ( ‘Lather’ ) while n > 0 :


print ( 'Lather’ )
print ( ‘Rinse’ ) print ( 'Rinse‘)
print ( 'Dry off!‘)

print( ‘ Dry off’ ) What does this loop do?


BREAKING OUT OF A LOOP?
• The break statement ends the current loop and jumps
to the statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of
the loop

while True: >>> hello there


line = input( ‘ ’ ) hello there
if line == 'done' : >>> finished
break finished
print ( line ) >>> done
print ( 'Done!‘) Done!
No Yes
True ?

....
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

• Loops must contain within themselves a way to


terminate
• Something inside a while loop must eventually
make the condition false
• Infinite loop: loop that does not have a way of
stopping
• Repeats until program is interrupted
• Occurs when programmer forgets to include
stopping code in the loop
INDEFINITE LOOPS
• While loops are called "indefinite loops" because
they keep going until a logical condition becomes
False
• The loops we have seen so far are pretty easy to
examine to see if they will terminate or if they will
be "infinite loops"
• Sometimes it is a little harder to be sure if a loop
will terminate
FOR LOOP: A COUNT-CONTROLLED LOOP
• Count-Controlled loop: iterates a specific number of times

Use a for statement to write count-controlled loop


• Designed to work with sequence of data items
– Iterates once for each item in the sequence
• General format:

for variable in sequence:


statements
• Target variable: the variable which is the target of the
assignment at the beginning of each iteration
USING THE TARGET VARIABLE INSIDE THE
LOOP

• Purpose of target variable is to reference each item in a


sequence as the loop iterates
• Target variable can be used in calculations or tasks in
the body of the loop

Example: calculate square root of each number in a range


USING THE RANGE FUNCTION WITH THE
FOR LOOP
• The range function simplifies the process of writing a for
loop
• range returns an iterable object
• Iterable: contains a sequence of values that can be
iterated over

• 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

• Sometimes the programmer does not know exactly how


many times the loop will execute
• Can receive range inputs from the user, place them in

variables, and call the range function in the for clause


using these variables

Be sure to consider the end cases: range does not


include the ending limit
GENERATING AN ITERABLE SEQUENCE
THAT RANGES FROM HIGHEST TO LOWEST

• The range() function can be used to generate a

sequence with numbers in descending order


Make sure starting number is larger than end limit, and
step value is negative

Example: range( 10, 0, -1 )


CALCULATING A RUNNING TOTAL
• Programs often need to calculate a total of a series of
numbers
• Typically include two elements:
• A loop that reads each number in series

• Anaccumulator variable

• Known as program that keeps a running total: accumulates total


and reads in series
• At end of loop, accumulator will reference the total
CALCULATING A RUNNING TOTAL (CONT’D.)
THE AUGMENTED ASSIGNMENT OPERATORS

• In many assignment statements, the variable on the left


side of the = operator also appears on the right side of
the = operator
• Augmented assignment operators: special set of
operators designed for this type of job
• Shorthand operators
THE AUGMENTED ASSIGNMENT OPERATORS
(CONT’D.)
INPUT VALIDATION LOOPS

• Computer cannot tell the difference between good data


and bad data
If user provides bad input, program will produce bad
output
GIGO: garbage in, garbage out
It is important to design program such that bad input
is never accepted
INPUT VALIDATION LOOPS (CONT’D.)
• Input validation: inspecting input before it is processed
by the program
If input is invalid, prompt user to enter correct data

Commonly accomplished using a while loop which repeats as


long as the input is bad
• If input is bad, display error message and receive another set of data

• If input is good, continue to process the input


INPUT VALIDATION LOOPS (CONT’D.)
NESTED LOOPS
• Nested loop: loop that is contained inside another loop

Example: analog clock works like a nested loop


• Hours hand moves once for every twelve movements of
the minutes hand: for each iteration of the “hours,” do
twelve iterations of “minutes”
• Seconds hand moves 60 times for each movement of
the minutes hand: for each iteration of “minutes,” do 60
iterations of “seconds”
WHAT IS THE LARGEST NUMBER?
myList = [ 3, 41, 12, 9, 74, 15 ]
WHAT IS THE LARGEST NUMBER?

3 41 12 9 74 15

largest_so_far -13 4174


COUNTING IN A LOOP

count = 0 $ python countloop.py


print 'Before', count Before 0
for thing in [9, 41, 12, 3, 74, 15] : 19
count = count + 1 2 41
print count , thing 3 12
print 'After', count 43
5 74
6 15
After 6
To count how many times we execute a loop we introduce
a counter variable that starts at 0 and we add one to it
each time through the loop.
FINDING THE AVERAGE IN A LOOP

count = 0 $ python averageloop.py


sum = 0 Before 0 0
print 'Before', count, sum 199
for value in [9, 41, 12, 3, 74, 15] : 2 50 41
count = count + 1 3 62 12
sum = sum + value 4 65 3
print count, sum, value 5 139 74
print 'After', count, sum, sum / count6 154 15
After 6 154 25

An average just combines the counting and


sum patterns and divides when the loop is
done.
FILTERING IN A LOOP
print ('Before‘)
for value in [9, 41, 12, 3, 74, 15] :
if value > 20:
$ python search1.py
print ('Large number‘ , value) Before
print ('After‘) Large number 41
Large number 74
After

We use an if statement in the loop to catch / filter the


values/elements that we are looking for.
SEARCH
found = False
USING A BOOLEAN VARIABLE
print (‘found value Before the
loop', found) $ python search1.py
found value Before the loop
for value in [9, 41, 12, 3, 74, 15] False 9
: False 41
False 12
if value == 3 : True 3
True 74
found = True True 15
After True
print (found, value)
print ('After', found)
If we just want to search and know if a value was found - we use
a variable that starts at False and is set to True as soon as we
find what we are looking for.
WHICH IS THE SMALLEST NUMBER?
myList = [ 3, 41, 12, 9, 74, 15 ]
WHICH IS THE SMALLEST NUMBER?

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

We still have a variable that is the smallest so far. The first


time through the loop smallest is None so we take the first
THE "IS" AND "IS NOT" OPERATORS

• Python has an "is"


operator that can be
smallest = None used in logical
print 'Before’ expressions
for value in [3, 41, 12, 9, 74, 15] :
• Implies 'is the same as'
if smallest is None :
smallest = value • Similar to, but stronger
elif value < smallest : than ==
smallest = value • 'is not' also is a logical
print smallest, value operator
print 'After', smallest
ASSIGNMENT #1
1. Write a while loop statement to print the following series 100, 95, 90 ………5
2. Write a program to print table of a number entered from the user.
3. Write a program to check whether a number is prime or not using while
loop.
4. Write a program to find the sum of the digits of a number accepted from
the user.
5. Write a program to find the product of the digits of a number accepted
from the user.
6. Write a program to check whether a number is Armstrong or not.
7. Write a program to add first n terms of the following series using a for
loop: 1/1! + 1/2! + 1/3! + …….. + 1/n!
8. Write a program to enter the numbers till the user wants and at the end it
should display the sum of all the numbers entered
9. Write a program to enter the numbers till the user enter ZERO and at the
end it should display the count of positive and negative numbers entered.
10. Write a program to accept 10 numbers from the user and display the
largest & smallest numbers.
1-119
ASSIGNMENT #2
1. Write a program to print the following series till n terms:
7 , 77 , 777 , 7777 , 77777, _ _ _ _ _ n terms
2. Write a program to find the sum of the following series(accept values of x and
n from user)
1 + x/1! + x2/2! + ……….xn/n!
3. Write a program to find the sum of following series :
x + x2/2 + ……….xn/n
4. Write a program to find the sum of following series
1 + 8 + 27 …………n terms
5. Write a program to find the sum of following series:
1 + 2 + 6 + 24 + 120 . . . . . n terms
6. Write a program to find the sum of following series:
S = 1 + 4 – 9 + 16 – 25 + 36 – … … n terms
7. Write a program to print only odd numbers from the given list using while loop.
L = [43, -85, -22, 25, -76, 33, 71, -91]
8. Write a program to print only numbers that are greater than 25 along with
the count from the given list using while loop.
L = [23, 45, 32, 25, 46, 33, 71, 90]
1-120

You might also like