Professional Documents
Culture Documents
CREDITS – 03
Course Learning Objectives: This course will enable students to-
• Python will keep evaluating parts of the expression until it becomes a single value
Entering Expressions into the Interactive Shell
If you type in a bad Python instruction, Python won’t be able to understand it
and will display a SyntaxError error message.
>>> 5 +
File "<stdin>", line 1
5+
^
SyntaxError: invalid syntax
>>> 42 + 5 + * 2
File "<stdin>", line 1
42 + 5 + * 2
^
SyntaxError: invalid syntax
Comparison Operators
20
Logical Operators
Bitwise Operators
Operator Precedence
The Integer, Floating-Point, and String Data Types
A data type is a category for values, and every value belongs to exactly one data type.
• The * operator can be used with only two numeric values (for multiplication) or
one string value and one integer value (for string replication). Otherwise, Python
will just display an error message.
>>> '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‘
String Concatenation and Replication
>>> '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'
Storing Values in Variables
• A variable is like a box in the computer’s • Think of a variable as a labeled
memory where you can store a single box that a value is placed in.
value.
Assignment Statements:
• We can store values in variables with an
assignment statement.
>>> len('')
0
Dissecting Your Program
The error that shows up when the following is typed into the interactive shell
>>> print('I am ' + 29 + ' years old.')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print('I am ' + 29 + ' years old.')
TypeError: Can't convert 'int' object to str implicitly
Python gives an error because you can use the + operator only to add two integers
together or concatenate two strings. You can’t add an integer to a string.
>>> 'I am ' + 29 + ' years old.'
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
'I am ' + 29 + ' years old.'
TypeError: Can't convert 'int' object to str implicitly
Dissecting Your Program -The str(), int(), and float() Functions
• The str() function can be passed an integer value and will evaluate to a string value
version of it, as follows:
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old.
• The str(), int(), and float() functions will evaluate to the string, integer, and floating
point forms of the value you pass, respectively.
Examples:
• The int() function is also useful if you need to round a floating-point number down.
• If you want to round a floating-point number up, just add 1 to it afterward.
>>> int(7.7)
7
>>> int(7.7) +1
8
• Note that if you pass a value to int() that it cannot evaluate as an integer, Python will
display an error message.
>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99‘
>>> int('twelve')
The int() function is also useful
Traceback (most recent call last): if you need to round a floating-
File "<pyshell#19>", line 1, in <module> point number down.
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve‘
• In the program, we have used the int() and str() functions in the last three lines
to get a value of the appropriate data type for the code.
Example:
>>> False or True
True
>>> False or False
False
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.
Example:
>>> not True
False
>>> not not not not True
True
Mixing Boolean and Comparison Operators
>>> (4 < 5) and (5 < 6)
True
Conditions
• The Boolean expressions can be considered conditions, which are the same thing
as expressions;
• Conditions always evaluate down to a Boolean value, True or False.
• 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.
Elements of Flow Control
Blocks of Code
Lines of Python code can be grouped together in blocks.
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:
print('Wrong password.')
Program Execution
• Python starts 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.
Flow Control Statements
Flow control statements can decide which Python instructions to execute
under which conditions.
• if Statements
• else Statements
• elif Statements
• while Loop Statements
• break Statements
• continue Statements
• for Loops and the range() Function
if Statements
• 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.')
else Statements
• An if clause can be followed by an else statement.
The else clause is executed only when the if
statement’s condition is False.
• 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.')
elif Statements
• elif statement is used when we want one of many possible clauses to execute. It provides
another condition that is checked only if any of the previous conditions were False.
• 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.')
Example
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.
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.')
Example
The order of the elif statements does matter
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 100:
print('You are not Alice, grannie.')
elif age > 2000:
print('Unlike you, Alice is not an undead,
immortal vampire.')
Example
• Optionally, an else statement can be used after
the last elif statement.
• In that case, it is guaranteed that at least one
(and only one) of the clauses will be executed.
• If the conditions in every if and elif statement are
False, then the else clause is executed.
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.')
Program Example
Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range,
print an error. If the score is between 0.0 and 1.0, print a grade using the following table
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
while Loop Statements
• We 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.
• 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)
while Boolean_Expression:
statement(s)
Example :
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
Output
Please type your name.
Al
Please type your name.
Albert
Please type your name.
%#@#%*(^&!!!
Please type your name.
your name
Thank you!
break Statements
• A shortcut way 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.
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
continue Statements
• 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 re-evaluates the loop’s condition.
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.')
“Truthy” and “Falsey” Values
• There are some values in other data types that conditions will consider
equivalent to True and False. When used in conditions, 0, 0.0, and '' (the empty
string) are considered False, while all other values are considered True.name = '‘
name =''
while not name:
print('Enter your name:')
name = input()
print('How many guests will you have?')
numOfGuests = int(input())
if numOfGuests:
print('Be sure to have enough room for all your guests.')
print('Done')
Program Examples
1) Write a program that uses a while loop to add up all the even numbers
between 100 and 200
2) Write a program to read N integers and find the sum and average ( N is the
input from the user)
3) Write python program to find the sum of all digits of a given number
4) Write python program to reverse a given number
5) Write a program to find the GCD of two positive numbers
for Loops and the range() Function
• If we want to execute a block of code only a certain number of times, then we can do
this with a for loop statement and the range() function.
for iteration_variable in sequence :
statement(s)
• A for statement looks something like for i in range(5) : and always includes the
following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)
The range() function generates a sequence of numbers which can be iterated through
using for loop. The syntax for range() function is,
range([start ,] stop [, step])
Example:
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
Output
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
The Starting, Stopping, and Stepping Arguments to range()
for i in range(12, 16):
print(i)
The first argument will be where the for loop’s variable starts, and the
second argument will be up to, but not including, the number to stop at.
output
12
13
14
15
The Starting, Stopping, and Stepping Arguments to range()
The range() function can also be called with three arguments. The first two
arguments will be the start and stop values, and the third will be the step
argument. The step is the amount that the variable is increased by after each
iteration.
for i in range(0, 10, 2):
print(i)
output
0
2
4
6
8
The Starting, Stopping, and Stepping Arguments to range()
We can even use a negative number for the step argument to make the for
loop count down instead of up.
output
5
4
3
2
1
0
Example: for Loop Using range() Function
output
# print("Only ''stop'' argument value specified in range function")
for i in range(3): 0
print(i) 1
2
# print("Both ''start'' and ''stop'' argument values specified in range
function") 2
for i in range(2, 5): 3
print(i) 4
Another example:
Following import statement that imports four different modules:
import random, sys, os, math
Contd… math module few examples
math.pow(x, y)
math.sqrt(x)
math.log2(x)
math.log(x[, base])
math.log10(x) Return the base-10 logarithm of x.
math.pow(x, y) Return x raised to the power y.
math.sqrt(x) Return the square root of x.
math.gcd(a, b)
math.ceil(x) Return the ceiling of x
math.fabs(x) Return the absolute value of x.
math.factorial(x) Return x factorial. Raises ValueError if x is not integral or is
negative.
math.floor(x)
math.exp(x) Return e**x.
Contd…
from import Statements
Example:
Example:
def hello(name): The definition of the hello() function in this
print('Hello ' + name) program has a parameter called name.
A parameter is a variable that an argument is
hello('Alice') stored in when a function is called.
hello('Bob')
Output:
Hello Alice
Hello Bob
Return Values and return Statements
• In general, the value that a function call evaluates to is called the return value
of the function.
• When creating a function using the def statement, we can specify what the
return value should be with a return statement
• A return statement consists of the following:
• The return keyword
• The value or expression that the function should return
• When an expression is used with a return statement, the return value is what
this expression evaluates to.
Example
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Try again'
elif answerNumber == 5:
return 'Ask again later'
r = random.randint(1, 5)
fortune = getAnswer(r)
print(fortune)
The None Value
• In Python, the value None represents the absence of a value.
• None is the only value of the NoneType data type
• None must be typed with a capital N.
Example:
>>> spam = print('Hello!')
Hello!
>>> None == spam Python adds return None to the end of any
True function definition with no return
statement.
>>> type(None)
<class 'NoneType'>
Keyword Arguments and print()
• Keyword arguments are identified by the keyword put before them in the
function call.
• Keyword arguments are often used for optional parameters.
Example-1: Example-2:
• There is only one global scope, and it is created when your program begins.
When your program terminates, the global scope is destroyed, and all its
variables are forgotten.
• Code in a function’s local scope cannot use variables in any other local scope.
• You can use the same name for different variables if they are in different
scopes. That is, there can be a local variable named spam and a global variable
also named spam.
Local Variables Cannot Be Used in the Global Scope
Example:
def spam():
eggs = 31337
spam()
print(eggs)
eggs = 42
spam()
print(eggs)
Local and Global Variables with the Same Name
def spam(): Output:
eggs = 'spam local'
print(eggs) # prints 'spam local'
bacon local
def bacon():
spam local
eggs = 'bacon local'
print(eggs) # prints 'bacon local' bacon local
spam() global
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
The global Statement
• If you need to modify a global variable from within a function, use the
global statement.
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
When you run this program, the final print() call will output this:
spam
The global Statement
• There are four rules to tell whether a variable is in a local scope or global
scope:
1. If a variable is being used in the global scope (that is, outside of all
functions), then it is always a global variable.
2. If there is a global statement for that variable in a function, it is a global
variable.
3. Otherwise, if the variable is used in an assignment statement in the
function, it is a local variable.
4. But if the variable is not used in an assignment statement, it is a global
variable.
The global Statement
Example program
def spam():
global eggs
eggs = 'spam' # this is the global
def bacon():
eggs = 'bacon' # this is a local
def ham():
print(eggs) # this is the global
Note:
If you ever want to modify the value stored in a global variable from in a
function, you must use a global statement on that variable.
Exception Handling
• Errors detected during execution are called exceptions ( errors occur at runtime)
• Getting an error, or exception, in your Python program means the entire program will
crash. Instead, the program should detect errors, handle them, and then continue to
run.
Output:
Example:
21.0
def spam(divideBy): 3.5
return 42 / divideBy Traceback (most recent call last):
File "F:/python programs/except1.py", line 6, in <module>
print(spam(2)) print(spam(0))
print(spam(12)) File "F:/python programs/except1.py", line 2, in spam
print(spam(0)) return 42 / divideBy
print(spam(1)) ZeroDivisionError: division by zero
A ZeroDivisionError happens whenever you try to divide a number by zero.
Examples
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
Try clause
• We can handle exceptions in our program by using try block and except block.
• A critical operation which can raise exception is placed inside the try block and
the code that handles exception is written in except block.
• The syntax for try–except block
Try clause
Example: Output:
def spam(divideBy):
try: 21.0
return 42 / divideBy 3.5
except ZeroDivisionError: Error: Invalid argument.
print('Error: Invalid argument.')
None
print(spam(2)) 42.0
print(spam(12))
print(spam(0))
print(spam(1))
A Short Program: Guess the Number
Write a Python program so that when its executed, the output will look
something like this:
I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!
A Short Program: Guess the Number
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
for guessesTaken in range(1, 7): # Ask the player to guess 6 times.
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
Output
I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!
Practice Questions
• What three functions can be used to get the integer, floating-point number,
or string version of a value?
• What is the difference between break and continue? Explain with example.
• How many global scopes are there in a Python program? How many local
scopes? Explain the local scope and global scope with an example.
• When does the code in a function execute: when the function is defined or
when the function is called?
END