0% found this document useful (0 votes)
2 views

unit 1 python

Python is a high-level, interpreted, interactive, and object-oriented programming language designed for readability and ease of use, making it suitable for beginners. It features a broad standard library, supports interactive and script modes, and uses indentation to define code blocks instead of braces. Python allows for dynamic typing, reference semantics, and various data types, including integers, floats, and strings, with operators that behave differently based on the data types involved.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 1 python

Python is a high-level, interpreted, interactive, and object-oriented programming language designed for readability and ease of use, making it suitable for beginners. It features a broad standard library, supports interactive and script modes, and uses indentation to define code blocks instead of braces. Python allows for dynamic typing, reference semantics, and various data types, including integers, floats, and strings, with operators that behave differently based on the data types involved.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Unit-1: Python Basics

Python is a high-level, interpreted, interactive and object oriented-scripting language

Python was designed to be highly readable which uses English keywords frequently
where as other languages use punctuation and it has fewer syntactical constructions
than other languages

Python is Beginner's Language: Python is a language for the beginner programmers


and supports the development of a wide range of applications, from simple text
processing to WWW browsers applications
Introduction to Python Programming 1
Unit-1: Python Basics
Python is Interpreted: This means that it is processed 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: This means that you can actually sit at a Python prompt and
interact with the interpreter directly to write your programs

Python is Object-Oriented: This means that Python supports Object-Oriented style or


technique of programming that encapsulates code within objects
Introduction to Python Programming 2
Compiling and interpreting
Many languages require you to compile (translate) your program into a form that the
machine understands.
compile execute
source code byte code output
Hello.java Hello.class

Python is instead directly interpreted into machine instructions.


interpret
source code output
Hello.py

Introduction to Python Programming 1-3 3


Writer: Guido Van Rossum
The Python programming language has a wide range of syntactical
constructions, standard library functions, and interactive
development environment features.

“Python is an experiment in how


much freedom programmers need.
Too much freedom and nobody can
read another's code; too little and
expressive-ness is endangered.”

Introduction to Python Programming Guido Van Rossum 4


Python Features
The Python programming language has a wide range of syntactical
constructions, standard library functions, and interactive development
environment features.
Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly
defined syntax.
Easy-to-read: Python code is much more clearly defined and visible to the eyes.

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

A broad standard library: One of Python's greatest strengths is the bulk of the library is
very portable and cross-platform compatible on UNIX, Windows.

Interactive Mode: Support for an interactive mode in which you can enter results from
a terminal right to the language, allowing interactive testing and debugging of
snippets of code.

Introduction to Python Programming 5


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.

Introduction to Python Programming 1-6 6


Python Basics : 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

Introduction to Python Programming 7


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
Introduction to Python Programming 8
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


Introduction to Python Programming 9
Lines and Indentation:
• One of the first caveats programmers encounter when learning Python is the fact that
there are no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line 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")

Introduction to Python Programming 10


Multi-Line Statements:

Introduction to Python Programming 11


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

Introduction to Python Programming 12


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.

Introduction to Python Programming 13


Using Blank Lines:
• A line containing only whitespace, possibly with a comment, is known
as a blank line, and Python totally ignores it.

• In an interactive interpreter session, you must enter an empty physical


line to terminate a multiline statement.

Introduction to Python Programming 14


Multiple Statements on a Single Line:

• The semicolon ( ; ) allows multiple statements on the single


line given that neither statement starts a new code block.

• Here is a sample snip using the semicolon:

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Introduction to Python Programming 15


Python Identifiers:
• 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.

Introduction to Python Programming 16


Python Identifiers:
• 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.

Introduction to Python Programming 17


Python Identifiers (cont’d)
• Here are following identifier naming convention for Python:

– Class names start with an uppercase letter and all other identifiers with a lowercase
letter.
– Starting an identifier with a single leading underscore indicates by convention that
the identifier is meant to be private.

– Starting an identifier with two leading underscores (__) indicates a strongly


private identifier.
– If the identifier also ends with two trailing underscores, the identifier is
a language-defined special name.

Introduction to Python Programming 18


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

Introduction to Python Programming 19


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]
Introduction to Python Programming 20
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
Introduction to Python Programming 21
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.

Introduction to Python Programming 22


Assigning Values to Variables:
• Python variables do not have to be explicitly declared 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.

• counter = 100 # An integer assignment


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

Introduction to Python Programming 23


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"

Introduction to Python Programming 24


Entering Expressions into the Interactive Shell
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.


Introduction to Python Programming 25
Entering Expressions into the Interactive Shell
List of Operators: ..continued
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

Python has many operators. Some examples are:

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

Introduction to Python Programming 26


Entering Expressions into the Interactive Shell
List of Operators: ..continued
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.

Introduction to Python Programming 27


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

Introduction to Python Programming 28


The order of operations (also called precedence)
Python math operators is similar to that of mathematics.
• The ** operator is evaluated first.
• The *, /, //, and % operators are evaluated next, from left to right.
• The + and - operators are evaluated last (also from left to right). You
can use parentheses to override the usual precedence if you need to.
Enter the following expressions into the interactive shell:
>>> 2 + 3 * 6 >>> 23 // 7
20 3
>>> (2 + 3) * 6 >>> 23 % 7
30 2
>>> 48565878 * 578453 >>> 2 + 2
28093077826734 4
>>> 2 ** 8 >>> (5 - 1) * ((7 + 1) / (3 - 1))
256 16.0
>>> 23 / 7
3.2857142857142856 Introduction to Python Programming 29
Data Types: The Integer, Floating-Point, and String 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!

Introduction to Python Programming 30


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.

Introduction to Python Programming 31


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)

Strings are a more complicated data type (called Sequences) that we will
discuss more later. They are made up of individual letters (strings of
length 1)

Introduction to Python Programming 32


String Concatenation
The meaning of an operator may change based on the data types of the values next to it.
For example:
+ is the addition operator when it operates on two integers or floating-point values.
When + is used on two string values, it joins the strings as the string concatenation
operator.
Enter the following into the interactive shell:
>>> 'Alice' + 'Bob’
'AliceBob'

Introduction to Python Programming 33


String Concatenation
However, if you try to use the + operator on a string and an integer value, Python will not
know how to handle this, and it will display an error message.
>>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
'Alice' + 42
TypeError: Can't convert 'int' object to str implicitly

Introduction to Python Programming 34


String Replication
The * operator is used for multiplication on two integer or floating-point values.
When the * operator is used on one string value and one integer value, it becomes the
string replication operator.
Example-1: >>> 'Alice' * 5
'AliceAliceAliceAliceAlice’
Example-2: >>> 'Alice' * 'Bob’
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
'Alice' * 'Bob’
TypeError: can't multiply sequence by non-int of type 'str’
Example-3: >>> 'Alice' * 5.0
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
'Alice' * 5.0
TypeError: can't multiply sequence by non-int of type 'float’
Introduction to Python Programming
35
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.


Introduction to Python Programming
36
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

Introduction to Python Programming


37
Print() function
The print() function displays the string value inside the parentheses on the screen.
print('Hello world!’)
The line print('Hello world!') means “Print out the text in the string 'Hello world!’.”
input() function:
The input() function waits for the user to type some text on the keyboard and press enter.
myName = input()
This function call evaluates to a string equal to the user’s text, and the previous line of code
assigns the myName variable to this string value.
Printing the User’s Name
print('It is good to meet you, ' + myName)
It call to print() actually contains the expression 'It is good to meet you, ' + myName
between the parentheses.
Introduction to Python Programming
38
The len() function
The len() function find the length of a string by counting number of characters.
Example:
>>> len('hello')
5
>>> len('My very energetic monster just scarfed nachos.')
46
>>> len('')
0

Introduction to Python Programming


39
The str() Function:
The str() function converts given value to string.
Example:
>>> str(‘29’)
‘29’
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old.

Introduction to Python Programming


40
The int() Function:
The int() function converts given value to integer.
Example:
>>> int('42')
42
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1

Introduction to Python Programming


41
The float() Function
The float() function converts given numerical value to real type.
Example:
>>> float('3.14')
3.14
>>> float(10)
10.0

Introduction to Python Programming


42
Your First Program
# This program says hello and asks for my name.
>>>print('Hello world!')
print('What is your name?') # ask for their name
>>>myName = input()
>>>print('It is good to meet you, ' + myName)
>>>print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

Introduction to Python Programming


43
Output:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>================================RESTART=============
>>>
Hello world!
What is your name?
Al
It is good to meet you, Al
The length of your name is:
2
What is your age?
4
You will be 5 in a year.
>>>

Introduction to Python Programming


44
Dissecting Your Program
The following line is called a comment.
# This program says hello and asks for my name. Python ignores comments.
The print() function displays the string value inside the parentheses on the screen.
print('Hello world!')
print('What is your name?') # ask for their name

myName = input()
The input() function waits for the user to type some text on the keyboard. This function call evaluates to a
string equal to the user’s text, and it assigns the myName variable to this string value.

print('It is good to meet you, ' + myName)


This single string value is then passed to print(), which prints it on the screen.
print('The length of your name is:')
print(len(myName))
The len() function evaluates to the integer value of the number of characters in that string.
Introduction to Python Programming
45
Flow Control
Flow control statements can decide which Python instructions to execute under which
conditions. In general, program execution start from the first line of code and simply
execute every line, straight to the end.

Introduction to Python Programming


46
Boolean values
The Boolean data type has only two values: True and False.
(Boolean data type is named after mathematician George Boole).
When typed as Python code, the Boolean values True and False lack the quotes you place
around strings, and they always start with a capital T or F, with the rest of the word in
lowercase.
>>> spam = True
>>> spam
True
v >>> true
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
true
NameError: name 'true' is not defined
w >>> True = 2 + 2
SyntaxError: assignment to keyword

Introduction to Python Programming


47
Comparison Operators
Comparison operators compare two values and evaluate down to a single
Boolean value.

Example:
>>> 42 == 42
True
>>> 42 == 99
False
>>> 2 != 3
True
>>> 2 != 2
False

Introduction to Python Programming


48
Comparison Operators
Example:
>>> 42 < 100
True
>>> 42 > 100
False
>>> 42 < 42
False
>>> eggCount = 42
>>> eggCount <= 42
True
>>> myAge = 29
>>> myAge >= 10
True

Introduction to Python Programming


49
Boolean Operators
• The three Boolean operators (and, or, and not) are used to compare
Boolean values.
• Like comparison operators, they evaluate these expressions down to a
Boolean value.
Binary Boolean Operators:
• The and & or operators always take two Boolean values (or expressions),so they’re
considered binary operators.
• The and operator evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.
>>> True and True
True
>>> True and False
False
Introduction to Python Programming
50
The or operator:
The or operator evaluates an expression to True if either of the two Boolean
values is True. If both are False, it evaluates to False.
>>> False or True
True
>>> False or False
False

Introduction to Python Programming


51
The not operator:
Unlike and and or, the not operator operates on only one Boolean value (or expression).
The not operator simply evaluates to the opposite Boolean value.
>>> not True
False
u >>> not not not not True
True

Introduction to Python Programming


52
Mixing Boolean and Comparison Operators
• The comparison operators evaluate to Boolean values, you can use them in
expressions with the Boolean operators.
• The and, or, and not operators are called Boolean operators because they
always operate on the Boolean values True and False.
• While expressions like 4 < 5 aren’t Boolean values, they are expressions that
evaluate down to Boolean values.
Example:
>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
Introduction to Python Programming
53
Mixing Boolean and Comparison Operators
The computer will evaluate the left expression first, and then it will evaluate
the right expression. When it knows the Boolean value for each, it will then
evaluate the whole expression down to one Boolean value.
Example-1:
(4 < 5) and (5 < 6)
True and (5 < 6)
True and True
True
Example-2:
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
Introduction to Python Programming
54
Elements of Flow Control
Flow control statements often start with a part called the condition, and all
are followed by a block of code called the clause.
Conditions:
Conditions always evaluate down to a Boolean value, True or False.
A flow control statement decides what to do based on whether its condition is
True or False, and almost every flow control statement uses a condition.
Example:
if name == 'Mary’:
v
print('Hello Mary')

Introduction to Python Programming


55
Elements of Flow Control
Blocks of Code:
Lines of Python code can be grouped together in blocks.
When a block begins and ends from the indentation of the lines of code.
There are three rules for blocks.
1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing block’s
indentation.
Example:
if name == 'Mary’:
print('Hello Mary’)
if password == 'swordfish’:
print('Access granted.')
else:
v
print('Wrong password.')
Introduction to Python Programming
56
Program Execution
• Python started executing instructions at the top of the program going
down, one after another.
• The program execution (or simply, execution) is a term for the current
instruction being executed.
• If you print the source code on paper and put your finger on each line as it
is executed, you can think of your finger as the program execution. v

Introduction to Python Programming


57
Flow Control Statements: If statement
The most common type of flow control statement is the if statement.
An if statement’s clause (that is, the block following the if statement) will
execute if the statement’s condition is True. The clause is skipped if the
condition is False.
Example:
if name == 'Alice’:
print('Hi, Alice.’)
All flow control statements end with a colon
and are followed by a new block of code (the clause).
This if statement’s clause is the block with print('Hi, Alice.').

Introduction to Python Programming


58
If statement

if single-selection structure flowchart.

Introduction to Python Programming


59
If statement
Simple if statement Syntax:
number = int(input("Enter the number to find odd or even"))
if (condition) :
if(number % 2 == 0):
statement
print("Answer")
statement
print("Even")
statement if(number % 2 != 0):
print("Answer")
print("Odd")
Introduction to Python Programming
60
else: statements
An if clause can optionally be followed by an else statement.
The else clause is executed only when the if statement’s condition is False.
An else statement doesn’t have a condition,and in code, an else statement
always consists of the following:
• The else keyword
• A colon
• Starting on the next line,
an indented block of code (called the else clause)
Example:
if name == 'Alice':
print('Hi, Alice.’)
else:
print('Hello, stranger.')
Introduction to Python Programming
61
else: statements

false true

Grade >= 60

print “Failed” print “Passed”

if/else double-selection structure flowchart.

Introduction to Python Programming


62
else: statements
Example:
>>>number = int(input("Enter the number to find odd or even"))
if(number % 2 == 0):
print("Answer")
print("Even")
else:
print("Answer")
print("Odd")

Introduction to Python Programming


63
elif statements
The elif statement is an “else if” statement that always follows an if or another elif
statement.
It provides another condition that is checked only if any of the previous conditions
were False.
In code, an elif statement always consists of the following:
• The elif keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)
Example:
if name == 'Alice’:
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
Introduction to Python Programming
64
elif statements
Syntax:
if condition :
statements
elif condition :
statements
elif condition :
statements
elif condition :
statements
elif condition :
statements
.
else :
statements
Introduction to Python Programming
65
elif statements
The elif clause executes if age < 12 is True
and name == 'Alice' is False.
However, if both of the conditions are False,
then both of the clauses are skipped.
It is not guaranteed that at least one of the
clauses will be executed.
When there is a chain of elif statements, only
one or none of the clauses will be executed.
Once one of the statements’ conditions is
found to be True, the rest of the elif clauses
are automatically skipped.

Introduction to Python Programming


66
elif statements
if name == 'Alice’:
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an
undead, immortal vampire.’)
elif age > 100:
print('You are not Alice, grannie.')

Introduction to Python Programming


67
elif statements
Example:
if name == 'Alice’:
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')

Introduction to Python Programming


68
while Loop Statements
You can make a block of code execute over and over again with a while statement.
The code in a while clause will be executed as long as the while statement’s condition is True.
In code, a while statement always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code
(called the while clause)

Example:
spam = 0
while spam < 5:
print('Hello, world.’)
spam = spam + 1

Introduction to Python Programming


69
Comparison between If statement and while Loop Statements
Example: if statement
spam = 0
if spam < 5:
print('Hello, world.’)
spam = spam + 1

Example: while statement


spam = 0
while spam < 5:
print('Hello, world.’)
spam = spam + 1
For the if statement, the output is simply "Hello, world.".
But for the while statement, it’s "Hello, world." repeated five times!
Introduction to Python Programming
70
break statement:
There is a shortcut to getting the program execution to break out of a while
loop’s clause early. If the execution reaches a break statement, it immediately
exits the while loop’s clause.
In code, a break statement simply contains the break keyword.
Example:
while True:
print('Please type your name.’)
name = input()
if name == 'your name’:
break
print('Thank you!’)

Introduction to Python Programming


71
continue statement:
Like break statements, continue statements are used inside loops. When the
program execution reaches a continue statement, the program execution
immediately jumps back to the start of the loop and reevaluates the loop’s
condition.
Example:
while True:
print('Who are you?’)
name = input()
if name != 'Joe’:
continue
print('Hello, Joe. What is the password? (It is a fish.)’)
password = input()
if password == 'swordfish’:
break
print('Access granted.') Introduction to Python Programming
72
An Infinite Loop
Example-1:
while True:
print('Hello world!')
When you run this program, it will print Hello world! to the screen forever, because the while
statement’s condition is always True. In IDLE’s interactive shell window, there are only two
ways to stop this program: press ctrl+C or select Shell->Restart Shell from the menu.
Ctrl+C is handy if you ever want to terminate your program immediately, even if it’s not stuck
in an infinite loop.
Example-2:
n=5
while n > 0 :
print ( 'Lather’ )
print ( 'Rinse‘)
print ( 'Dry off!‘)
Introduction to Python Programming
73
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
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"
Introduction to Python Programming
74
The 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 [val1, val2, etc]:
statements
Target variable: the variable which is the target of the assignment at the
beginning of each iteration

Introduction to Python Programming


75
for Loop with string
Syntax: for <variable> in iterable:
statements
The following code iterate over a string and print each character on a new line.
>>> print (‘String Iteration’)
v1='SIT’
for i in v1:
print(i)
OUTPUT:
String Iteration
S
I
T

Introduction to Python Programming


76
Simple for Loop with a number list
The following code iterate over a numerical values and print each number on
a new line.
Example-2
>>>print('Number iteration:’)
for i in [1,2,3,4,5]:
print(i)
OUTPUT:
Number Iteration
1
2
3
4
5

Introduction to Python Programming


77
Simple for Loops and the range() Function
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

Introduction to Python Programming


78
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
An accumulator variable Known as program that keeps a
running total: accumulates total and reads in series
At end of loop, accumulator will reference the total

Introduction to Python Programming


79
for Loop with range() function with One argument
One argument: used as ending limit
Example:

>>>total=0
for i in range(5):
total=total+i
print(i)
print('Sum of the values',total)

Output
0
1
2
3
4
Sum of the values 10

Introduction to Python Programming


80
for Loop with range() function with Two arguments
Two arguments: starting value and ending limit
Example:
>>>total=0
for i in range(5,10):
total=total+i
print(i)
print('Sum of the values',total)
Output
5
6
7
8
9
Sum of the values 35

Introduction to Python Programming


81
for Loop with range() function with Three arguments
Three arguments: starting value, ending limit and third argument is step value
Example-1:
>>>total=0
for i in range(5, 15, 3):
total=total+i
print(i)
print('Sum of the values',total)
Output
5
8
11
14
Sum of the values 38

Introduction to Python Programming


82
for Loop with range() function decreasing order
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)
Example-2
>>>for i in range(5, 0, -1):
print(i)

Output
5
4
3
2
1

Introduction to Python Programming


83
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

Introduction to Python Programming


84
Nested Loops
Nested loop: loop that is contained inside another loop
• 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”
Example: Generating Multiplication table for the numbers 1 to 5
>>>for i in range(1,6):
print('The multiplication for the number ',i)
for j in range(1,11):
print(i,'*',j,' = ',i*j)
Output:
The multiplication for the number 1
1*1 = 1
1*2 = 2
………
……….
Introduction to Python Programming
85
Importing Modules
• All Python programs can call a basic set of functions called built-in functions, including
the print(), input(), and len() functions.
• Python also comes with a set of modules called the standard library. Each module is a
Python program that contains a related group of functions that can be embedded in your
programs.
• Before you can use the functions in a module, you must import the module with an
import statement.
• In code, an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas

Introduction to Python Programming


86
Example: Importing random module
Example:
>>>import random
for i in range(5):
print(random.randint(1, 10))
Output:
6
10
7
10
8
Here’s an example of an import statement that imports four different
modules:
>>>import random, sys, os, math

Introduction to Python Programming


87
Ending a Program Early with sys.exit()
The last flow control concept to cover is how to terminate the program.
This always happens if the program execution reaches the bottom of the instructions.
However, you can cause the program to terminate, or exit, by calling the sys.exit() function.
Since this function is in the sys module, you have to import sys before your program can use
it.
Example:
>>>import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + ‘.’)
Output:
Type exit to exit.
exit
An exception has occurred, use %tb to see the full traceback.
Introduction to Python Programming
88
Chapter-3. Functions
o A function is like a mini-program within a program.
o In Python a function is some reusable code that takes arguments(s) as input
does some computation and then returns a result or results
o We define a function using the def reserved word
o We call/invoke the function by using the function name, parenthesis and
arguments in an expression
o Once we define a function, we can reuse the function over and over
throughout our program

Introduction to Python Programming


89
Type of Python Functions
There are two kinds of functions in Python.
Built-in functions that are provided as part of Python
- input(), type(), float(), int() ...
Functions that we define ourselves and then use
We treat the user defined function names as "new" reserved
words (i.e. we avoid them as variable names)

Introduction to Python Programming


90
Built-in Functions
 Python provides a number of important built-in functions that we can use without
needing to provide the function definition.
 The creators of Python wrote a set of functions to solve common problems and
included them in Python for us to use.
 The max and min functions give us the largest and smallest values in a list,
respectively:

 The max function tells us the “largest character” in the string (which turns out to be
the letter “w”)
 The min function shows us the smallest character which turns out to be a space.

Introduction to Python Programming


91
Built-in Functions
 Another very common built-in function is the len function which tells us how
many items are in its argument.
 If the argument to len is a string, it returns the number of characters in the
string.

 These functions are not limited to looking at strings, they can operate on any
set of values.
 You should treat the names of built-in functions as reserved words (i.e. avoid
using “max” as a variable name).

Introduction to Python Programming


92
Type conversion functions
 Python also provides built-in functions that convert values from one type to
another.
 The int function takes any value and converts it to an integer, if it can, or
complains otherwise:

Introduction to Python Programming


93
Type conversion functions
 int can convert floating-point values to integers, but it doesn’t round off; it
chops off the fraction part:

 float converts integers and strings to floating-point numbers:

 str converts its argument to a string:

Introduction to Python Programming


94
Example: Random numbers
 The random function is only one of many functions which handle random
numbers.
 The function randint() takes parameters low and high and returns an integer
between low and high (including both).

 To choose an element from a sequence at random, you can use choice :

Introduction to Python Programming


95
Example: Math functions
 Python has a math module that provides most of the familiar mathematical functions.
 Before we can use the module, we have to import it:

 This statement creates a module object named math. If you print the module object,
you get some information about it:

 The module object contains the functions and variables defined in the module.
 To access one of the functions, you have to specify the name of the module and the name
of the function, separated by a dot (also known as a period).
 This format is called dot notation.

Introduction to Python Programming


96
Example: Math functions

 The first example computes the logarithm base 10 of the signal-to-noise ratio.
 The math module also provides a function called log that computes logarithms base e.
 The second example finds the sine of radians . The name of the variable is a hint that
sin and the other trigonometric functions ( cos , tan , etc.) take arguments in radians.
 To convert from degrees to radians, divide by 360 and multiply by 2π:

Introduction to Python Programming


97
Example: Math functions

 The expression math.pi gets the variable pi from the math module.
 The value of this variable is an approximation of π, accurate to about 15
digits.
 If you know your trigonometry, you can check the previous result by
comparing it to the square root of two divided by two:

Introduction to Python Programming


98
User defined Functions
• We create a new function using the def keyword followed by optional parameters in
parenthesis.
• We indent the body of the function
• This defines the function but does not execute the body of the function
• The rules for function names are the same as for variable names: letters, numbers and some
punctuation marks are legal, but the first character can’t be a number.
• You can’t use a keyword as the name of a function,
• You should avoid having a variable and a function with the same name.
• The empty parentheses after the name indicate that this function doesn’t take any
arguments.
def print_lyrics():
print("I'm a lumberjack, and I'm okay.”)
print('I sleep all night and I work all day.‘)

Introduction to Python Programming


99
User defined Functions
 The first line of the function definition is called the header; the rest is
called the body.
 The header has to end with a colon and the body has to be indented.
 By convention, the indentation is always four spaces.
 The body can contain any number of statements.
 The strings in the print statements are enclosed in double quotes.
 Single quotes and double quotes do the same thing;

Introduction to Python Programming


100
User defined Functions
 If you type a function definition in interactive mode, the interpreter prints
ellipses (...) to let you know that the definition isn’t complete:

 To end the function, you have to enter an empty line (this is not necessary in a
script or python file).

Introduction to Python Programming


101
User defined Functions
 The syntax for calling the new function is the same as for built-in functions:

 Once you have defined a function, you can use it inside another function.
 For example, to repeat the previous refrain, we could write a function called
repeat_lyrics

Introduction to Python Programming


102
Definitions and uses
 Pulling together the code fragments from the previous section, the whole program
looks like this:

 This program contains two function definitions: print_lyrics and repeat_lyrics.


 Function definitions get executed just like other statements, but the effect is to create
function objects.
 The statements inside the function do not get executed until the function is called,
and the function definition generates no output.
Introduction to Python Programming
103
Flow of execution
 In order to ensure that a function is defined before its first use, you have to
know the order in which statements are executed, which is called the flow of
execution.
 Execution always begins at the first statement of the program.
 Statements are executed one at a time, in order from top to bottom.
 Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the
function is called.
 A function call is like a detour in the flow of execution.
 Instead of going to the next statement, the flow jumps to the body of the
function, executes all the statements there, and then comes back to pick up
where it left off.
Introduction to Python Programming
104
Flow of execution
 That sounds simple enough, until you remember that one function can call
another.
 While in the middle of one function, the program might have to execute the
statements in another function.
 But while executing that new function, the program might have to execute yet
another function!
 Fortunately, Python is good at keeping track of where it is, so each time a
function completes, the program picks up where it left off in the function that
called it.
 When it gets to the end of the program, it terminates.
 When you read a program, you don’t always want to read from top to bottom.
 Sometimes it makes more sense if you follow the flow of execution.
Introduction to Python Programming
105
Example:
>>>def hello(): The first line is a def statement, which defines a function named
print('Howdy!') hello().
print('Howdy!!!') The code in the block that follows the def statement is the body of
the function. This code is executed when the function is called, not
print('Hello there.’) when the function is first defined.
Output The hello() lines after the function are function calls. In code, a
>>>hello() function call is just the function’s name followed by parentheses,
>>>hello() possibly with some number of arguments in between the
print('Howdy!') parentheses.
print('Howdy!!!') When the program execution reaches these calls, it will jump to the
print('Hello there.’) top line in the function and begin executing the code there. When it
reaches the end of the function, the execution returns to the line that
print('Howdy!') called the function and continues moving through the code as before.
print('Howdy!!!')
Since this program calls hello() two times, the code in the hello()
print('Hello there.’)
function is executed two times.

Introduction to Python Programming


106
def Statements with Parameters
We can also define your own functions that accept arguments.
Example:
>>>def hello(name):
print('Hello ' + name)
>>>hello('Alice’)
hello('Bob’)
Output:
Hello Alice
Hello Bob
A parameter is a variable that an argument is stored in when a function is
called. The first time the hello() function is called, it’s with the argument 'Alice'.
The program execution enters the function, and the variable name is
automatically set to 'Alice', which is what gets printed by the print() statement.
Introduction to Python Programming
107
def Statements with arguments
We can also define your own functions that accept arguments.
Example:
>>>def hello(name):
print('Hello ' + name)
>>>hello('Alice’)
hello('Bob’)
Output:
Hello Alice
Hello Bob
• An argument is a value we pass into the function as its input when we call the function
• We use arguments so we can direct the function to do different kinds of work when we call
it at different times
• We put the arguments in parenthesis after the name of the function
Here, names ‘Alice’ and ‘Bob’ are the arguments
Introduction to Python Programming
108
Return Statements
 To return a result from a function, we use the return statement in our function.
 For example, we could make a very simple function called addtwo that adds two numbers
together and return a result.

 When this script executes, the print statement will print out “8” because the addtwo
function was called with 3 and 5 as arguments.
 Within the function the parameters a and b were 3 and 5 respectively.
 The function computed the sum of the two numbers and placed it in the local function
variable named added and used the return statement to send the computed value
back to the calling code as the function result which was assigned to the variable x and
printed out.
Introduction to Python Programming
109
Return Values
• Often a function will take its arguments, do some computation and return a
value to be used as the value of the function call in the calling expression. The
return keyword is used for this.
def greet():
return “Hello”

print(greet(), "Glenn”) Hello Glenn


print(greet(), "Sally“) Hello Sally

 A “fruitful” function is one that produces a result (or return value)


 The return statement ends the function execution and “sends back” the result of the
function

Introduction to Python Programming


110
Return Values
>>> def greet(lang):
... if lang == 'es':
... return 'Hola’
... elif lang == 'fr':
... return 'Bonjour’
... else:
... return 'Hello’
... >>> print(greet('en'),'Glenn’)
Hello Glenn
>>> print(greet('es'),'Sally’)
Hola Sally
>>> print(greet('fr'),'Michael’)
Bonjour Michael
>>>
Introduction to Python Programming
111
Multiple Parameters / Arguments
• We can define more than one parameter in the function definition
• We simply add more arguments when we call the function
• We match the number and order of arguments and parameters

def addtwo(a, b):


added = a + b
return added
x = addtwo(3, 5)
print(x)

Introduction to Python Programming


112
The None Value
• In Python there is a value called None, which represents the absence of a value.
• None is the only value of the NoneType data type. (Other programming
languages might call this value null, nil, or undefined.)
• Just like the Boolean True and False values, None must be typed with a capital N.
• One place where None is used is as the return value of print().
• The print() function displays text on the screen, but it doesn’t need to return
anything in the same way len() or input() does.
Example:
>>> spam = print('Hello!')
Hello!
>>> None == spam
True
Introduction to Python Programming
113
Fruitful functions and void functions
 A “fruitful” function is one that produces a result (or return value)
 Some functions perform an action but don’t return a value. They are called
void functions
 The return statement ends the function execution and “sends back” the result
of the function
 When you call a fruitful function, you almost always want to do something
with the result;
 for example, you might assign it to a variable or use it as part of an expression:

Introduction to Python Programming


114
Fruitful functions and void functions
 When you call a function in interactive mode, Python displays the result:

 But in a script, if you call a fruitful function and do not store the result of the function in a variable, the
return value vanishes

 This script computes the square root of 5, but since it doesn’t store the result in a variable or display
the result, it is not very useful.
 Void functions might display something on the screen or have some other effect, but they don’t have a
return value.
 If you try to assign the result to a variable, you get a special value called None

Introduction to Python Programming


115
To function or not to function...
 Organize your code into “paragraphs” - capture a complete thought and
“name it”
 Don’t repeat yourself - make it work once and then reuse it
 If something gets too long or complex, break up logical chunks and put
those chunks in functions
 Make a library of common stuff that you do over and over - perhaps share
this with your friends...

Introduction to Python Programming


116
Local Variables
Local variable: variable that is assigned a value inside a function belongs
to the function in which it was created. Only statements inside that function
can access it, error will occur if another function tries to access the variable
Scope: the part of a program in which a variable may be accessed
For local variable: function in which created
Local variable cannot be accessed by statements outside its function.
Different functions may have local variables with the same name
Each function does not see the other function’s local variables, so no confusion

Introduction to Python Programming


117
Global Variables
Global variable: created by assignment statement written outside all
the functions. It can be accessed by any statement in the program file,
including from within a function. If a function needs to assign a value to the
global variable, the global variable must be redeclared within the function
General format: global variable_name
Reasons to avoid using global variables:
Global variables making debugging difficult
Many locations in the code could be causing a wrong variable value
Functions that use global variables are usually dependent on those variables
Makes function hard to transfer to another program
Global variables make a program hard to understand
Introduction to Python Programming
118
Global Constants
Global constant: global name that references a value that cannot be
changed
• Permissible to use global constants in a program
• To simulate global constant in Python, create global variable and do
not re-declare it within functions

Introduction to Python Programming


119
The Scope of Variables
Global constant: global name that references a value that cannot be
changed
• Permissible to use global constants in a program
• To simulate global constant in Python, create global variable and do
not re-declare it within functions

Introduction to Python Programming


120

You might also like