Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Notes Part 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 122

CS22201

UNIT II
Pytpppp
Python
• High-level programming language

• Interpreted

• Interactive

• Object-Oriented Programming Language


Why Python

• Easy to learn

• Can be used in broad range of applications

• Open source

• Procedural, Functional, Object-Oriented


Evolution of Python

• Developed by Guido Van Rossum in early 1990s

• Named after a comedy group Monty Python

• Features derived from many languages like C, C++, Java and other

scripting languages
• Available under GNU General Public License ( Free, Open Source)
Features

• Extensive Standard Library

• Cross Platform Compatibility

• Portable and Extendable

• Databases and GUI Programming


• A program is a sequence of instructions that specifies how to perform
a computation.
• input: Get data from the keyboard, a file, the network, or some other device.
• output: Display data on the screen, save it in a file, send it over the network, etc.
• math: Perform basic mathematical operations like addition and multiplication.
• conditional execution: Check for certain conditions and run the appropriate code.
• repetition: Perform some action repeatedly, usually with some variation.
True and False are special values that belong to the type bool; they are
not strings:
>>> type(True)
<class ‘bool’>
>>> type(False)
<class ‘bool’>
Running Python
• The Python interpreter is a program that reads and executes Python
code.
• Depending on your environment, you might start the interpreter by
clicking on an icon, or by typing python on a command line.
Displaying Result
• The last line is a prompt that indicates that the interpreter is ready for
you to enter the code. If you type a line of code and hit Enter, the
interpreter displays the result:
The First Program
• In Python, it looks like this:

This is an example of a print statement.


Arithmetic operators
The operators +, -, and * perform addition, subtraction, and
multiplication, as in the following examples:

The operator / performs division:


Arithmetic operators
• The operator ** performs exponentiation.
Values and types
Values belong to different types:
• 2 is an integer,
• 42.0 is a floating-point number,
• and 'Hello, World!' is a string.
If you are not sure what type a value has, the interpreter can tell you:
Values and types
• What about values like '2' and '42.0’?
• They look like numbers, but they are quotation marks like strings.

• They are considered strings.


Values and types
• When you type a large integer, you might be tempted to use commas
between groups of digits, as in 1,000,000.
• This is not a legal integer in Python, but it is legal:
Formal and natural languages
• Natural languages are the languages people speak, such as English, Spanish, and
French. They were not designed by people; they evolved naturally.
• Formal languages are languages that are designed by people for specific
applications. For example, the notation that mathematicians use is a formal
language that is particularly good at denoting relationships among numbers and
symbols. Chemists use formal language to represent the chemical structure of
molecules.
• And most Programming languages are formal languages that have been designed
to express computations.
Debugging
• Programming errors are called bugs and the process of tracking them
down is called debugging.
Variables, expressions and statements
• An assignment statement creates a new variable and gives it a value:
>>> message = 'And now for something completely different’
>>> n = 17
>>> pi = 3.1415926535897932
This example makes three assignments.
• The first assigns a string to a new variable named message;
• the second gives the integer 17 to n;
• the third assigns the (approximate) value of π to pi.
Variable names
• Variable names can contain both letters and numbers, but they can’t
begin with a number.
• It is legal to use uppercase letters, but using only lowercase for
variable names is conventional.
• The underscore character, _, can appear in a name. It is often used in
names with multiple words, such as your_name or air_speed.
Keywords in Python
False class finally is return None
Continue for lambda try True def
From non local while and del
Global not with as elif if
or yield assert else import pass
break except in raise
Expressions and statements
• An expression is a combination of values, variables, and operators.

• When you type an expression at the prompt, the interpreter evaluates


it, which means that it finds the value of the expression. In this
example, n has the value of 17, and n + 25 has the value of 42.
Script mode
• So far we have run Python in interactive mode, which means that you
interact directly with the interpreter.
• The alternative is to save code in a file called a script and then run the
interpreter in script mode to execute the script. By convention,
Python scripts have names that end with .py.
Evaluation in Python
For example, if you are using Python as a calculator, you might type
>>> miles = 26.2
>>> miles * 1.61
42.182
The first line assigns a value to miles, but it has no visible effect. The
second line is an expression, so the interpreter evaluates it and displays
the result.
It turns out that a marathon is about 42 kilometers.
Print Statement
• Python evaluates the expression, but it doesn’t display the result.
• To display the result, you need a print statement like this:
miles = 26.2
print(miles * 1.61)
Order of operations
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
For mathematical operators, Python follows mathematical convention. The
acronym PEMDAS is a useful way to remember the rules:
• Parentheses have the highest precedence. Expressions in parentheses are
evaluated first,
2 * (3-1) is 4, and
(1+1)**(5-2) is 8.
• You can also use parentheses to make an expression easier to read, as in (minute
* 100) / 60, even if it doesn’t change the result.
Order of operations
• Exponentiation has the next highest precedence,
so 1 + 2**3 is 9, and
2 * 3**2 is 18.
• Multiplication and Division have higher precedence than Addition and
Subtraction.
So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right
(except exponentiation). So in the expression
degrees / 2 * pi, the division happens first and the result is multiplied by
pi. To divide by 2π, you can use parentheses or write degrees / 2 / pi.
String operations
• The + operator performs string concatenation, which means it joins
the strings by linking them end-to-end.
For example:
>>> first = ‘Hello’
>>> second = ‘world’
>>> first + second
Helloworld
* Operator
• The * operator also works on strings; it performs repetition.
For example,
‘Hello'*3 is ‘HelloHelloHello’.
If one of the values is a string, the other has to be an integer.
Comments
• Adding notes to programs to explain in natural language what the
program is doing.
• These notes are called comments, and they start with the # symbol:
For Example,
v=5 # assign 5 to v
Function calls
• We have already seen one example of a function call:
>>> type(42)
• The name of the function is type. The expression in parentheses is
called the argument of the function.
• The result, for this function, is the type of the argument. It is common
to say that a function “takes” an argument and “returns” a result. The
result is also called the return value.
Example
int can convert floating-point values to integers, but it doesn’t round off; it chops off
the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159’)
3.14159
Example
• Finally, str converts its argument to a string:
>>> str(32)
'32’
>>> str(3.14159)
'3.14159'
Math functions
Python has a math module that provides most of the familiar
mathematical functions. A module is a file that contains a collection of
related functions.
Before we can use the functions in a module, we have to import it with
an import statement:
>>> import math
Math Function - Example
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.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
Examples
>>> radians = 0.7
>>> height = math.sin(radians)

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

The concatenated string is : Hello World


Appending a string
• It can be done by += operator

Eg, str = “Hello,”


name = input (“\n Enter your name:”)
str+=name
str+= “ . Welcome to python programming
print (str)
Appending a string
Output:

Enter your name : Arnav


Hello , Arnav. Welcome to python programming
Repeating a String
• It can be done by * operator

Eg, str= “Hello”


print (str*3)
Repeating a String
Output:

Hello Hello Hello


String Function
The str() function is used to convert values of any other type into string
type.

Eg, str1= “ Hello”


var=7
str2= str1+var
print (str2)
String Function
str1 = “Hello”
var = 7
str2 = str1+str (var)
print (str2)

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

Print (str [-1])


Output -> N
Examples
• Print (str [-6] )
o/p -> P
Print (str[-2:])
o/p-> ON
Print (str[:-2])
o/p -> PYTH
Print (str[-5:-2])
o/p-> YTH
If statements
Without Indendation
Elif
• "if the previous conditions were not true, then try this
condition".
ELSE
• The else keyword catches anything which isn't caught
by the preceding conditions.
Example
Short Hand If
• If you have only one statement to execute, you can put
it on the same line as the if statement.
Short Hand If ... Else
• If you have only one statement to execute, one for if,
and one for else, you can put it all on the same line:
• One line if else statement:
And
• The and keyword is a logical operator, and is used to
combine conditional statements:
Or
• The OR keyword is a logical operator, and is used to
combine conditional statements:
NOT
• The NOT keyword is a logical operator, and is used to
reverse the result of the conditional statement:
Nested If
The pass Statement
While Loops
The break Statement
• With the break statement we can stop the loop even if
the while condition is true:
The else Statement
• With the else statement we can run a block of code once when
the condition no longer is true:
Print a message once the condition is false:
Square Root
Area of a triangle
Quadratic Equation
Swap two variables
Miles = Kilometers * 0.621371
Kilometers = Miles * 1.60934

Kilometer to miles
Fibonacci Series

You might also like