Python m1 Notes
Python m1 Notes
Precedence
The order of operations (also called precedence) of Python math operators is
similar to that of mathematics. The ** operator is evaluated first; the *, /, //,
and % operators are evaluated next, from left to right; and the + and - operators
are evaluated last (also from left to right).
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 48565878 * 578453
28093077826734
>>> 2 ** 8
256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
3
>>> 23 % 7
1
Module 1
2
>>> 2 + 2
4
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
2
Module 1
The integer (or int) data type indicates values that are whole numbers. Numbers
with a decimal point, such as 3.14, are called floating-point numbers (or floats).
Note that even though the value 42 is an integer, the value 42.0 would be a
floating-point number.
Table
The expression evaluates down to a single, new string value that combines the
text of the two strings. However, if you try to use the + operator on a string and
an integer value
>>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'Alice' + 42
TypeError: can only concatenate str (not "int") to str
The error message can only concatenate str (not "int") to str means that Python
thought you were trying to concatenate an integer to the string 'Alice'. Your code
will have to explicitly convert the integer to a string because Python cannot do
this automatically. (Converting data types will be explained in “Dissecting Your
Program” on page 13 when we talk about the str(), int(), and float() functions.)
The * operator multiplies two integer or floating-point values. But when
the * operator is used on one string value and one integer value, it becomes
3
Module 1
the string replication operator. Enter a string multiplied by a number into the
interactive shell to see this in action.
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
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, like the following:
>>> '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'
>>> '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'
VARIABLES
A variable is like a box in the computer’s memory where you can store a single
value. If you want to use the result of an evaluated expression later in your
program, you can save it inside a variable.
You’ll store values in variables with an assignment statement. An assignment
statement consists of a variable name, an equal sign (called the assignment
operator), and the value to be stored. If you enter the assignment statement spam
= 42, then a variable named spam will have the integer value 42 stored in it.
➊ >>> spam = 40
>>> spam
40
>>> eggs = 2
➋ >>> spam + eggs
42
>>> spam + eggs + spam
82
➌ >>> spam = spam + 2
>>> spam
42
A variable is initialized (or created) the first time a value is stored in it ➊. After
that, you can use it in expressions with other variables and values ➋. When a
variable is assigned a new value ➌, the old value is forgotten, which is
4
Module 1
Variable Names
A Python variable is a reserved memory location to store values. In other words, a variable in a python
program gives data to the computer for processing, variable it obeys the following three
rules.
FLOW CONTROL
Flow control statements can decide which Python instructions to execute under
which conditions, These flow control statements directly correspond to the
symbols in a flowchart, In a flowchart, there is usually more than one way to go
from the start to the end. The same is true for lines of code in a computer
program. Flowcharts represent these branching points with diamonds, while the
5
Module 1
other steps are represented with rectangles. The starting and ending steps are
represented with rounded rectangles.
BOOLEAN VALUES
While the integer, floating-point, and string data types have an unlimited number
of possible values, the Boolean data type has only two values: True and False.
➊ >>> spam = True
>>> spam
True
➋ >>> true
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
true
NameError: name 'true' is not defined
➌ >>> True = 2 + 2
SyntaxError: can't assign to keyword
Boolean values are used in expressions and can be stored in variables ➊. If you
don’t use the proper case ➋ or you try to use True and False for variable names ➌,
Python will give you an error message.
COMPARISON OPERATORS
Comparison operators, also called relational operators, compare two values and
evaluate down to a single Boolean value. Table shows the lists the comparison
operators.
Table
6
Module 1
These operators evaluate to True or False depending on the values you give them
>>> 42 == 42
True
>>> 42 == 99
False
>>> 2 != 3
True
>>> 2 != 2
False
The operator, == (equal to) evaluates to True when the values on both sides are
the same, and != (not equal to) evaluates to True when the two values are
different. The == and != operators can actually work with values of any data
type.
>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> True == True
True
>>> True != False
True
>>> 42 == 42.0
True
➊ >>> 42 == '42'
False
7
Module 1
BOOLEAN OPERATORS
The three Boolean operators (and, or, and not) are used to compare Boolean
values.
Binary Boolean Operators
The and 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. Enter
some expressions using and into the interactive shell to see it in action.
>>> True and True
True
>>> True and False
False
A truth table shows every possible result of a Boolean operator. Table is the truth
table for the and operator.
Table : The and Operator’s Truth Table
8
Module 1
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.
9
Module 1
We can also use multiple Boolean operators in an expression, along with the
comparison operators.
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
Conditions
The Boolean expressions you’ve seen so far could all be considered conditions,
which are the same thing as expressions; condition is just a more specific name
in the context of flow control statements. 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.
Blocks of Code
Lines of Python code can be grouped together in blocks. You can tell when a
block begins and ends from the indentation of the lines of code. There are three
rules for blocks.
Blocks begin when the indentation increases.
Blocks can contain other blocks.
Blocks end when the indentation decreases to zero or to a containing block’s
indentation.
10
Module 1
Example:
name = 'Mary'
password = 'swordfish'
if name == 'Mary':
➊ print('Hello, Mary')
if password == 'swordfish':
➋ print('Access granted.')
else:
➌ print('Wrong password.')
The first block of code ➊ starts at the line print('Hello, Mary') and contains all
the lines after it.
if Statements
The most common type of flow control statement is the if statement.
An if statement is executed if the condition is true else false.
In Python, an if statement consists of the following:
The if 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 if clause)
11
Module 1
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. In plain English,
an else statement could be read as, “If this condition is true, execute this code.
Or else, execute that code.” 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)
The example below uses an else statement to offer a different greeting if the
person’s name isn’t Alice.
12
Module 1
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 all
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)
The elif keyword
A condition (that is, an expression that evaluates to True or False)
A colon
Starting on the next line, an indented player_age = 12
13
Module 1
An else statement doesn't look for a specific condition. Else statements occur after an if or
elif statement in your code.
Every if/elif/else block must begin with one regular if statement and end with a single else
statement, but you can have as many elif statements in the middle as you want!
14
Module 1
These statements are similar—both if and while check the value of spam, and if
it’s less than 5, they print a message. But when you run these two code snippets,
something very different happens for each one. For the if statement, the output
is simply "Hello, world.". But for the while statement, it’s "Hello,
world." repeated five times!
15
Module 1
The code with the if statement checks the condition, and it prints Hello,
world. only once if that condition is true. The code with the while loop, on the
other hand, will print it five times. The loop stops after five prints because the
integer in spam increases by one at the end of each loop iteration, which means
that the loop will execute five times before spam < 5 is False.
In the while loop, the condition is always checked at the start of each iteration, If
the condition is True, then the clause is executed, and afterward, the condition is
checked again. The first time the condition is found to be False, the while clause
is skipped.
16
Module 1
break Statements:
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.
➊ while True:
print('Please type your name.')
➋ name = input()
➌ if name == 'your name':
➍ break
➎ print('Thank you!')
The first line ➊ creates an infinite loop; it is a while loop whose condition is
always True. After the program execution enters this loop, it will exit the loop
only when a break statement is executed, this program asks the user to enter your
name ➋. Now, however, while the execution is still inside the while loop,
17
Module 1
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 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.')
18
Module 1
If the user enters any name besides Joe ➊, the continue statement ➋ causes the
program execution to jump back to the start of the loop. When the program
reevaluates the condition, the execution will always enter the loop, since the
condition is simply the value True. Once the user makes it past that if statement,
they are asked for a password ➌. If the password entered is swordfish, then
the break statement ➍ is run, and the execution jumps out of the while loop to
print Access granted ➎. Otherwise, the execution continues to the end of
the while loop, where it then jumps back to the start of the loop.
19
Module 1
Local variables:- local variables are those which are defined inside a function and their scope is
limited to that function only.In other words, we can say that local variables are accessible only
inside the function in which it was initialized whereas the global variables are accessible
throughout the program and inside every function.
Ex:
def f():
# local variable
s = "I love Geeksforgeeks"
print(s)
f()
Output:
I love Geeksforgeeks
Can a local variable be used outside a function?
If we will try to use this local variable outside the function then let’s see what will happen.
def f():
s = "I love Geeksforgeeks"
print("Inside Function:", s)
f()
print(s)
Output:
Global Variables:-
These are those which are defined outside any function and which are
accessible throughout the program, i.e., inside and outside of every function
Ex:
def f():
print("Inside Function", s)
# Global scope
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)
Output
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks
20
Module 1
FUNCTIONS
A function is a block of code which only runs when it is called.You can pass data, known
as parameters, into a function.A function can return data as a result. A function is like a
miniprogram within a program.
Ex:
➊ def hello():
➋ print('Howdy!')
print('Howdy!!!')
print('Hello there.')
➌ hello()
hello()
hello()
The first line is a def statement ➊, which defines a function named hello(). 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, The hello() lines after the function ➌ are function calls. In code, a function
call is just the function’s name followed by parentheses, possibly with some number of
arguments in between the parentheses. Since this program calls hello() three times, the code in
the hello() function is executed three times. When you run this program, the output looks like
this:
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
When you call the print() or len() function, you pass them values,
called arguments, by typing them between the parentheses.
Ex:
➊ def hello(name):
➋ print('Hello, ' + name)
➌ hello('Alice')
hello('Bob')
21
Module 1
Output:
Hello, Alice
Hello, Bob
The definition of the hello() function in this program has a parameter
called name ➊. Parameters are variables that contain arguments. When a function
is called with arguments, the arguments are stored in the parameters. The first
time the hello() function is called, it is passed the argument 'Alice' ➌. The
program execution enters the function, and the parameter name is automatically set
to 'Alice', which is what gets printed by the print() statement ➋.
Define, Call, Pass, Argument, Parameter
Ex:
➊ def sayHello(name):
print('Hello, ' + name)
➋ sayHello('Al')
To define a function is to create it, just like an assignment statement like spam = 42 creates
the spam variable. The def statement defines the sayHello() function ➊.
The sayHello('Al') line ➋ calls the now-created function, sending the execution to the top of the
function’s code. This function call is also known as passing the string value 'Al' to the function. A
value being passed to a function in a function call is an argument. The argument 'Al' is assigned
to a local variable named name. Variables that have arguments assigned to them are parameters.
A return statement is used to end the execution of the function call and “returns”
the result (value of the expression following the return keyword) to the caller. The
statements after the return statements are not executed. If the return statement
is without any expression, then the special value None is
returned. A return statement is overall used to invoke a function so that the
passed statements can be executed.
Note: Return statement can not be used outside the function.
Syntax:
def fun():
statements
.
.
return [expression]
22
Module 1
Ex:def cube(x):
r=x**3
return r
Return values:
To let a function return a value, use the return statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output:
15
25
45
the print() function has the optional parameters end and sep to specify what
should be printed at the end of its arguments and between its arguments
(separating them), respectively.
Ex:
print('Hello')
print('World')
output:
Hello
World
23
Module 1
The two outputted strings appear on separate lines because the print() function
automatically adds a newline character to the end of the string it is passed.
However, you can set the end keyword argument to change the newline character
to a different string.
Ex:
print('Hello', end='')
print('World')
Output:
HelloWorld
Similarly, when you pass multiple string values to print(), the function will
automatically separate them with a single space.
>>> print('cats', 'dogs', 'mice')
cats dogs mice
Fig:The frame objects of the call stack as abcdCallStack.py calls and returns from functions
The top of the call stack is which function the execution is currently in.
24
Module 1
EXCEPTION HANDLING
Right now, getting an error, or exception, in your Python program means the
entire program will crash. we don’t want this to happen in real-world programs.
Instead, we want the program to detect errors, handle them, and then continue to
run.
As discussed there is a chance of runtime error while doing some program.
One of the possible reasons is wrong input.
For example, consider the
following code segment –
a=int(input("Enter a:"))
b=int(i
nput("
Enter
b:"))
c=a/b
print(c)
When you run the above code, one of the possible situations would be –
Enter a:12
Enter b:0
Traceback (most
recent call
last):c=a/b
try:
c=a/b
25
Module 1
print(c)
except:
print("Division by zero is not possible")
Output:
Enter a:12
Enter b:0
Question Bank
1.Need for role of precedence,Illustrate the rules of precedence
2.Explain the integer,floating point,and string data types
3.what is string concantination and repplication explain with examples
4.what are variables explain how values are storing to the variables
5.what is an expression made up of?what do all expressions do?
6.Explain with examples Local and Global variables(Scope)
7.What are comparission operators explain with examples?
8.Explain the 3 binary Boolean operators
9.Explain with examples the mixing Boolean with comparision operators
10.Explain all the flow control statements.
11.what are functions?Explain python functions with parameters and return statements
12.brief note on callstack
13.Define exception handling.Explain how exceptions are handled in python.
26