Python Notes Part 1
Python Notes Part 1
Python Notes Part 1
UNIT II
Pytpppp
Python
• High-level programming language
• Interpreted
• Interactive
• Easy to learn
• Open source
• Features derived from many languages like C, C++, Java and other
scripting languages
• Available under GNU General Public License ( Free, Open Source)
Features
>>> degrees = 45
>>> radians = degrees / 180.0 * math.pi
>>> math.sin(radians)
0.707106781187
The expression math.pi gets the variable pi from the math module. Its value is a floating-point
approximation of π, accurate to about 15 digits.
Composition
• One of the most useful features of programming languages is their
ability to take small building blocks and compose them.
• For example, the argument of a function can be any kind of
expression, including arithmetic operators:
x = math.sin(degrees / 360.0 * 2 * math.pi)
x = math.exp(math.log(x+1))
Example
The left side of an assignment statement has to be a variable name.
Any other expression on the left side is a syntax error.
>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
Syntax Error: can't assign to operator
Fruitful Functions
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:
x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python displays the
result:
>>> math.sqrt(5)
2.2360679774997898
Fruitful function
But in a script, if you call a fruitful function all by itself, the return value
is lost forever!
math.sqrt(5)
This script computes the square root of 5, but since it doesn’t store or
display the result, it is not very useful.
Floor division
Conventional division returns a floating-point number:
>>> minutes = 105
>>> minutes / 60
1.75
But we don’t normally write hours with decimal points. Floor division returns
the integer number of hours, rounding down:
>>> minutes = 105
>>> hours = minutes // 60
>>> hours
1
Modulus
To use the modulus operator, %, which divides two numbers and
returns the remainder.
>>> remainder = minutes % 60
>>> remainder
45
Boolean expressions
A boolean expression is an expression that is either true or false.
The following examples use the operator ==, which compares two
operands and produces True if they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
Boolean expressions
True and False are special values that belong to the type bool; they are
not strings:
>>> type(True)
<class ‘bool’>
>>> type(False)
<class ‘bool’>
Relational operators
The == operator is one of the relational operators; the others are:
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
A common error is to use a single equal sign (=) instead of a double
equal sign (==). Remember that = is an assignment operator and == is a
relational operator.
Logical operators
• Logical AND
• Logical OR
• Logical NOT
Conditional execution
The simplest form is the if statement:
if x > 0:
print('x is positive’)
The boolean expression after if is called the condition. If it is true, the
indented statement runs. If not, nothing happens.
if statements have the same structure as function definitions: a header
followed by an indented body. Statements like this are called
compound statements.
Alternative execution
The second form of if Statement
There are two possibilities and the condition determines which one runs.
if x % 2 == 0:
print('x is even’)
else:
print('x is odd’)
If the remainder when x is divided by 2 is 0, then we know that x is even,
and the program displays an appropriate message. If the condition is false,
the second set of statements runs.
Chained conditionals
• Sometimes there are more than two possibilities and we need more than two
branches. One way to express a computation like that is a chained conditional:
if x < y:
print('x is less than y’)
elif x > y:
print('x is greater than y’)
else:
print('x and y are equal’)
elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no
limit on the number of elif statements. If there is an else clause, it has to be at the
end, but there doesn’t have to be one.
Nested conditionals
if x == y:
print('x and y are equal’)
else:
if x < y:
print('x is less than y’)
else:
print('x is greater than y’)
Keyboard input
• Python provides a built-in function called input that stops the
program and waits for the user to type something. When the user
presses Return or Enter, the program resumes and input returns what
the user typed as a string.
>>> text = input()
What are you waiting for?
>>> text
'What are you waiting for?'
Keyboard input
input can take a prompt as an argument:
>>> name = input('What...is your name?\n’)
What...is your name?
Arthur, King of the Britons!
>>> name 'Arthur, King of the Britons!'
New line Sequence
The sequence \n at the end of the prompt represents a newline, which is a
special character that causes a line break.
That’s why the user’s input appears below the prompt. If you expect the user to
type an integer, you can try to convert the return value to int:
>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n’
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
42
>>> int(speed)
42
Example
• But if the user types something other than a string of digits, you get
an error:
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int() with base 10
We will see how to handle this kind of error later.
Debugging
When a syntax or runtime error occurs, the error message contains a
lot of information, but it can be overwhelming.
The most useful parts are usually:
• What kind of error it was, and
• Where it occurred.
Whitespace Errors
Syntax errors are usually easy to find.
Whitespace errors can be tricky because spaces and tabs are invisible
and we are used to ignoring them.
>>>x = 5
>>> y = 6
File "", line 1
y=6
IndentationError: unexpected indent
Runtime errors
Suppose you are trying to compute a signal-to-noise ratio in decibels.
The formula is SNRdb = 10 log10(Psignal/Pnoise).
In Python, you might write something like this:
import math
signal_power = 9
noise_power = 10
ratio = signal_power // noise_power
decibels = 10 * math.log10(ratio)
print(decibels)
Error Message
When you run this program, you get an exception:
Traceback (most recent call last):
File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio)
ValueError: math domain error
The error message indicates line 5, but there is nothing wrong with that
line. To find the real error, it might be useful to print the value of ratio,
which turns out to be 0. The problem is in line 4, which uses floor
division instead of floating-point division.
Return values
Fruitful functions.
The first example is area, which returns the area of a circle with the
given radius:
def area(radius):
a = math.pi * radius**2
return a
In a fruitful function, the return statement includes an expression.
Return Values
The expression can be arbitrarily complicated, so we could have written
this function more concisely:
def area(radius):
return math.pi * radius**2
On the other hand, temporary variables like a can make debugging
easier.
Multiple return statements
def absolute_value(x):
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one run.
As soon as a return statement runs, the function terminates without executing any
subsequent statements.
Code that appears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
Incremental development
• As you write larger functions, you might find yourself spending more
time debugging.
• To deal with increasingly complex programs, you might want to try a
process called incremental development.
• The goal of incremental development is to avoid long debugging
sessions by adding and testing only a small amount of code at a time.
Incremental development
As an example, suppose you want to find the distance between two
points, given by the coordinates (x1, y1) and (x2, y2).
By the Pythagorean theorem, the distance is:
Try to consider what are the inputs (parameters) and what is the output
(return value)?
Incremental development
In this case, the inputs are two points, which you can represent using
four numbers.
The return value is the distance represented by a floating-point value.
Immediately you can write an outline of the function:
def distance(x1, y1, x2, y2):
return 0.0
To test the new function, call it with sample arguments:
>>> distance(1, 2, 4, 6)
0.0
Incremental development
• So the horizontal distance is 3 and the vertical distance is 4; that way,
the result is 5
• At this point we have confirmed that the function is syntactically
correct, and we can start adding code to the body.
• A reasonable next step is to find the differences x2 − x1 and y2 − y1.
The next version stores those values in temporary variables and prints
them.
Incremental development
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print('dx is', dx)
print('dy is', dy)
return 0.0
If the function is working, it should display dx is 3 and dy is 4. If so, we
know that the function is getting the right arguments and performing
the first computation correctly.
Incremental development
Next we compute the sum of squares of dx and dy:
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
print('dsquared is: ', dsquared)
return 0.0
Incremental development
• Again, you would run the program at this stage and check the output (which should
be 25).
• Finally, you can use math.sqrt to compute and return the result:
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
If that works correctly, you are done. Otherwise, you might want to print the value of
result before the return statement.
Boolean functions
Functions can return booleans, which is often convenient for hiding
complicated tests inside functions.
For example:
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
Boolean Functions
It is common to give boolean functions names that sound like yes/no
questions;
is_divisible returns either True or False to indicate whether x is divisible
by y.
Here is an example:
>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
Boolean functions
Boolean functions are often used in conditional statements:
if is_divisible(x, y):
print('x is divisible by y’)
It might be tempting to write something like:
if is_divisible(x, y) == True:
print('x is divisible by y’)
The result of the == operator is a boolean, so we can write the function
more concisely by returning it directly:
def is_divisible(x, y):
return x % y == 0
Iteration
A new assignment makes an existing variable refer to a new value.
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7
State Diagram
>>> a = 5
>>> b = a# a and b are now equal
>>> a = 3 # a and b are no longer equal
>>> b
5
The third line changes the value of a but does not change the value of b, so they
are no longer equal.
• v
Updating variables
A common kind of reassignment is an update, where the new value of
the variable depends on the old.
>>> x = x + 1
This means “get the current value of x, add one, and then update x with
the new value.”
If you try to update a variable that doesn’t exist, you get an error,
because Python evaluates the right side before it assigns a value to x:
>>> x = x + 1
NameError: name 'x' is not defined
Updating variables
Before you can update a variable, you have to initialize it, usually with a
simple assignment:
>>> x = 0
>>> x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is
called a decrement.
The while statement
• In a computer program, repetition is also called iteration.
def countdown(n):
while n > 0:
print(n)
n=n-1
print('Blastoff!’)
“While n is greater than 0, display the value of n and then decrement n.
When you get to 0, display the word Blastoff!”
The while statement
More formally, here is the flow of execution for a while statement:
1. Determine whether the condition is true or false.
2. If false, exit the while statement and continue execution at the next
statement.
3. If the condition is true, run the body and then go back to step 1.
This type of flow is called a loop because the third step loops back
around to the top.
The while statement
• The body of the loop should change the value of one or more
variables so that the condition becomes false eventually and the loop
terminates.
• Otherwise the loop will repeat forever, which is called an infinite loop.
The range() Function
• To loop through a set of code a specified number of times, we can use
the range() function,
• The range() function returns a sequence of numbers, starting from 0
by default, increments by 1 (by default), and ends at a specified
number.
Using the range() function:
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
Python for loops
• The range() function defaults to 0 as a starting value, however, it is
possible to specify the starting value by adding a parameter:
Syntax
for var in range(initial_value,excluding_final_value,step_value):
range(2, 6), which means values from 2 to 6 (but not including 6):
for x in range(2, 6):
print(x)
Python for loops
The range() function defaults to increment the sequence by 1, however,
it is possible to specify the increment value by adding a third
parameter: range(2, 30, 3):
for x in range(2, 30, 3):
print(x)
Else in For Loop
• The else keyword in a for loop specifies a block of code to be executed
when the loop is finished.
Example
Print all numbers from 0 to 5, and print a message when the loop has
ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
The else block will NOT be executed if the loop
Is stopped by a break statement.
The pass Statement
• for loop cannot be empty, but if you for some reason have no
content, put it in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
String Functions in Python
Python string data type is a sequence made up of one or more
individual characters where a character could be a letter, digit,
whitespace or any other symbol.
Strings in Python
• Strings are enclosed with single quotes, double quotes or triple
quotes
• Python has a built-in string class named “str”
Eg, name=“India”
country=name
graduate=‘N’
nationality = str (“Indian”)
Concatenating two Strings
Done by + operator
str1 =“Hello”
str2 = “world”
str3 = str1+str2
print (“ The concatenated string is : “, str3)
Concatenating two Strings
Output
Output :
Hello 7
Slice Operation
• A substring of string is called a slice.
Syntax of Slice operation
s [ start:end]
Eg, str = “PYTHON”
print (str [1:5])
Output:
YTHO
Slice operation
• Print (str [:6])
• o/p => P Y T H O N
Slice operation
• print (str [1:])
• Output :
YTHON
Slice operation
print (str [:])
• Output
PYTHON
Slice operation
• Print [1:20]
output
YTHON
Negative Indexes
Kilometer to miles
Fibonacci Series