0% found this document useful (0 votes)
27 views48 pages

Unit 1 and 2 Notes

Unit I of the Python Programming course covers the basics of Python, including the interpreter, data types (int, float, boolean, string, list), variables, expressions, and statements. It explains the structure of a program, the importance of modules, functions, and operators, as well as how to handle input and output. Additionally, it discusses Python's syntax rules, including variable naming conventions, and introduces key programming concepts such as expressions, statements, and debugging.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views48 pages

Unit 1 and 2 Notes

Unit I of the Python Programming course covers the basics of Python, including the interpreter, data types (int, float, boolean, string, list), variables, expressions, and statements. It explains the structure of a program, the importance of modules, functions, and operators, as well as how to handle input and output. Additionally, it discusses Python's syntax rules, including variable naming conventions, and introduces key programming concepts such as expressions, statements, and debugging.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Unit-I

PYTHON PROGRAMMING
UNIT I
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments;
modules and functions, function definition and use, flow of execution, parameters and
arguments; Illustrative programs: exchange the values of two variables, circulate the values of n
variables, distance between two points.

What is a program?
A program is a sequence of instructions that specifies how to perform a computation.
The computation might be something mathematical, such as solving a system of equations or
finding the roots of a polynomial, but it can also be a symbolic computation, such as searching
and replacing text in a document or (strangely enough) compiling a program.
There are few basic instructions appear in every programming language:
input: Get data from the keyboard, a file, or some other device.
output: Display data on the screen or send data to a file or other device.
math: Perform basic mathematical operations like addition and multiplication.
conditional execution: Check for certain conditions and execute the appropriate code.
repetition: Perform some action repeatedly, usually with some variation.

Python programming language


Python is an example of a high-level language; other high-level languages you might
have heard of are C, C++, Perl, and Java. There are also low-level languages, sometimes
referred to as “machine languages” or “assembly languages.
The high-level program is called the source code, and the translatedprogram is called the
object code or the executable. Once a program is compiled, you can execute it repeatedly
without further translation.
Programs written in a high-level language have to be processed before they can run.
Python is considered an interpreted language because Python programs are executed by an
interpreter. There are two ways to use the interpreter: interactive mode and script mode.
In interactive mode, type Python programs and the interpreter displays the result.
Eg: >>> 1 + 1
2
Where, >>> is the prompt the interpreter uses to indicate that it is ready
In script mode, type python program in a file and store the file with .py extension and use
the interpreter to execute the contents of the file, which is called a script. bug: An error in a
program.
debugging: The process of finding and removing any of the three kinds of programming errors.
syntax: The structure of a program.
syntax error: An error in a program that makes it impossible to parse (and therefore impossible
to interpret).
exception: An error that is detected while the program is running.
semantics: The meaning of a program.
Page 1
GE8151-Problem Solving and Python Programming Unit-I

semantic error: An error in a program that makes it do something other than what the
programmer intended.
VARIABLES, EXPRESSIONS AND STATEMENTS
Values and types
A value is one of the basic things a program. There are different values integers, float and
strings. The numbers with a decimal point belong to a type called float. The values written in
quotes will be considered as string, even it’s an integer. If type of value is not known it can be
interpreted as
Eg:
>>> type('Hello, World!')
<type 'str'>
>>> type(17)
<type 'int'>
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>

Variables
A variable is a name that refers to a value. A variable is a location in memory used to store some
data (value). They are given unique names to differentiate between different memory locations.
The rules for writing a variable name are same as the rules for writing identifiers in Python. The
assignment operator (=) to assign values to a variable. An assignment statement creates new
variables and gives them values:
Eg:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897932
The type of a variable is the type of the value it refers to.
Eg:
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>

Variable names and keywords


Variable names can be arbitrarily long and contain both letters and numbers, but they
have to begin with a letter. The underscore character, _, can appear in a name. It is often used in
names with multiple words, such as my_name or airspeed_of_unladen_swallow. If you give a
variable an illegal name, you get a syntax error:
Page 2
GE8151-Problem Solving and Python Programming Unit-I

Eg:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical
Zymurgy' SyntaxError: invalid syntax
The interpreter uses keywords to recognize the structure of the program, and they cannot be used
as variable names. Python 2 has 31 keywords. In Python 3, has 33 keywords.
and del from not while
as elif global or with
assert else if pass yield
break except import print nonlocal
class exec in raise false
continue finally is return
def for lambda try

Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It
helps differentiating one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_screen,
all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. Identifier can be of any length.

Data types in Python


In Python programming, data types are actually classes and variables are instance (object)
of these classes. They are defined as int, float and complex class in Python.

Lists
List is an ordered sequence of items. Python knows a number of compound data types,
used to group together other values. The most versatile is the list, which can be written as a list
of comma-separated values (items) between square brackets. List items need not all have the
same type.
Eg:
>>> a = [’spam’, ’eggs’, 100, 1234]
>>> a
Output: [’spam’, ’eggs’, 100, 1234]
Page 3
GE8151-Problem Solving and Python Programming Unit-I

Expressions and statements


An expression is a combination of values, variables, and operators.
Eg:
17
x
x + 17
Instructions that a Python interpreter can execute are called statements. A statement is a
unit of code that the Python interpreter can execute. Two kinds of statement: print and
assignment.
Eg:
a=1+2+3+\
4+5+6+\
7+8+9
In Python, end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\).

Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that
block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.

Python Tuple
Tuple is an ordered sequence of items same as list.The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.
It is defined within parentheses () where items are separated by commas.
Eg:
>>> t = (5,'program', 1+3j)
>>> a=(5,7.9,10)

Page 4
GE8151-Problem Solving and Python Programming Unit-I

Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """. Eg:

>>> s = "This is a string"


>>> s = '''a multiline

Comments
Comments indicate Information in a program that is meant for other programmers (or
anyone reading the source code) and has no effect on the execution of the program. In Python,
we use the hash (#) symbol to start writing a comment. Eg:

#This is a comment
#print out Hello
print('Hello')

Python Output Using print() function

The actual syntax of the print() function is

print (“Statement”,variable_name)
print (‘Statement’,variable_name)
print (“Statement %formatting function”%variable_name)

After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout (screen)
Eg:
print ('This sentence is output to the screen')
# Output: This sentence is output to the screen

a=5

print ('The value of a is', a)


# Output: The value of a is 5

Python Input
The syntax for input() is

input([prompt])
raw_input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
Eg:
>>> num = input('Enter a number: ')
Page 5
GE8151-Problem Solving and Python Programming Unit-I

Enter a number: 10
>>> num
'10'
>>>a=raw_input(‘Enter a number’)
10
Modules
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix .py appended. A module can contain executable statements as well
as function definitions. Each module has its own private symbol table, which is used as the
global symbol table by all functions defined in the module. Modules can import other modules.

Python Import
A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive
interpreter in Python. We use the import keyword to do this.
Python provides two ways to import modules.

>>> import math


>>> print math
<module 'math' (built-in)>
>>> print math.pi
3.14159265359
If you import math, you get a module object named math. The module object contains
constants like pi and functions like sin and exp.
But if you try to access pi directly, you get an error.
>>> print pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined

As an alternative, you can import an object from a module like this:


>>> from math import pi

Now you can access pi directly, without dot notation.


>>> print pi
3.14159265359

Operators and operands


Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands.

Page 6
GE8151-Problem Solving and Python Programming Unit-I

The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and


exponentiation.
Eg:
20+32
hour-1
hour*60+minute
minute/60
5**2 (5+9)*(15-7)

Precedence Of Operators
The order of evaluation depends on the rules of precedence. The acronym PEMDAS is
a useful way to remember the rules:
Parentheses have the highest precedence
Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3,
not 27.
Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. 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.

Type of operators in Python


Arithmetic operators
Comparison (Relational) operators
Logical (Boolean) operators
Bitwise operators
Assignment operators
Special operators

Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Arithmetic operators in Python
Operator Meaning Example
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
% Modulus - remainder of the division of left operand by the right x % y (remainder of

Common to all Branch Page 7


GE8151-Problem Solving and Python Programming Unit-I

x/y)
// Floor division - division that results into whole number adjusted x // y
to the left in the number line
** Exponent - left operand raised to the power of right x**y (x to the power y)
Example: Arithmetic operators in Python
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)

# Output: x - y = 11
print('x - y =',x-y)

# Output: x * y = 60
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)

# Output: x // y = 3
print('x // y =',x//y)

# Output: x ** y = 50625
print('x ** y =',x**y)
When you run the program, the output will be:
x + y = 19
x - y = 11 x
* y = 60 x /
y = 3.75 x
// y = 3
x ** y = 50625

Comparison operators
Comparison operators are used to compare values. It either returns True or False
according to the condition.
Operator Meaning Example
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y

Common to all Branch Page 8


GE8151-Problem Solving and Python Programming Unit-I

!= Not equal to - True if operands are not equal x != y


>= Greater than or equal to - True if left operand is greater than or equal to the x >= y
right
<= Less than or equal to - True if left operand is less than or equal to the right x <= y

Example: Comparison operators in Python


x = 10
y = 12

# Output: x > y is False


print('x > y is',x>y)

# Output: x < y is True


print('x < y is',x<y)

# Output: x == y is False
print('x == y is',x==y)

# Output: x != y is True
print('x != y is',x!=y)

# Output: x >= y is False


print('x >= y is',x>=y)

# Output: x <= y is True


print('x <= y is',x<=y)
Output:
x > y is False
x < y is True x
== y is False x
!= y is True x
>= y is False x
<= y is True

Logical operators

Logical operators are and, or, not operators.

Operator Meaning Example


and True if both the operands are true x and y

Common to all Branch Page 9


GE8151-Problem Solving and Python Programming Unit-I

or True if either of the operands is true x or y


not True if operand is false (complements the operand) not x

Example: Logical Operators in Python


x = True
y = False

# Output: x and y is False


print('x and y is',x and y)

# Output: x or y is True
print('x or y is',x or y)

# Output: not x is False


print('not x is',not x)

Output:
x and y is False
x or y is True
not x is False

Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by
bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Bitwise operators in Python


Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)


<< Bitwise left shift x<< 2 = 40 (0010 1000)

Assignment operators
Assignment operators are used in Python to assign values to variables. a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.
Page 10
GE8151-Problem Solving and Python Programming Unit-I

There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.

Assignment operators in Python


Operator Example Equivatent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

Example: Assignment operators in Python


x = 15
y=4
x+=y
# Output: x + y =
19 print('x + y =',x)

x = 15
y=4
x-=y
# Output: x - y =
11 print('x - y =',x)

x = 15
y=4
x*=y
# Output: x * y =
60 print('x * y =',x)

Page 11
GE8151-Problem Solving and Python Programming Unit-I

x = 15
y=4
x/=y
# Output: x / y = 3.75
print('x / y =',x)

x = 15
y=4
x//=y
# Output: x // y =
3 print('x // y =',x)

x = 15
y=4
x**=y
# Output: x ** y =
50625 print('x ** y =',x)

Special operators
Python language offers some special type of operators like the identity operator or the
membership operator.

Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.
Identity operators in Python
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True

Example: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False

Page 12
GE8151-Problem Solving and Python Programming Unit-I

print(x1 is not y1)

# Output: True
print(x2 is y2)

# Output: False
print(x3 is y3)

Output:
False
True
False

Here, we see that x1 and y1 are integers of same values, so they are equal as well as
identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. Since list are mutable (can be
changed), interpreter locates them separately in memory although they are equal.

Membership operators
in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary). In a dictionary we
can only test for presence of key, not the value.

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example: Membership operators in Python


x = 'Hello world'
y = {1:'a',2:'b'}

# Output: True
print('H' in x)

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)

# Output: False
Page 13
GE8151-Problem Solving and Python Programming Unit-I

print('a' in y)

Output:
True
True
True
False

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Functions

In Python, function is a group of related statements that perform a specific task.


Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. Furthermore, it avoids
repetition and makes code reusable.

Function Definitions
In Python each function definition is of the form
def name of function (list of formal
parameters):
body of function

For example, we could define the function max by the code


def max(x, y):
if x > y:
return x
else:
return y
def is a reserved word that tells Python that a function is about to be defined.

A function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules
of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements
must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Page 14
GE8151-Problem Solving and Python Programming Unit-I

Function Call
A function is a named sequence of statements that performs a computation. When you
define a function, you specify the name and the sequence of statements. Later, you can “call” the
function by name.
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument
of the function. The resultis called the return value.

The return statement


The return statement is used to exit a function and go back to the place from where it was
called. The Syntax of return statement:
return [expression_list]

This statement can contain expression which gets evaluated and the value is returned. If there is
no expression in the statement or the return statement itself is not present inside a function, then
the function will return the None object.
For example:
>>> print(greet("May"))
Hello, May. Good
morning! None
Here, None is the returned value.

How Function works in Python?

Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.

Page 15
GE8151-Problem Solving and Python Programming Unit-I

Type conversion functions


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

>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello

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
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 mathematical functions.

>>> import math


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

>>> print math


<module 'math' (built-in)>

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.
Page 16
GE8151-Problem Solving and Python Programming Unit-I

Eg:
>>> math.sqrt(2) / 2.0
0.707106781187

Flow of execution
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.

Parameters and arguments


Some of the built-in functions we have seen require arguments. For example, when you
call math.sin you pass a number as an argument. Some functions take more than one argument:
math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called parameters. Here is
an example of a user-defined function that takes an argument:
Eg: def print_twice(bruce):
print bruce
print bruce
This function assigns the argument to a parameter named bruce. When the function is
called, it prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> print_twice(math.pi)
3.14159265359
3.14159265359

Parameter Passing
Parameter passing is the process of passing arguments to a function. There are two types
of arguments: Actual arguments and formal arguments. Actual arguments are the values passed
to a function’s formal parameters to be operated on. Eg:

def f(x): #name x used as formal parameter


y=1
x=x+y
Page 17
GE8151-Problem Solving and Python Programming Unit-I

print 'x =', x


return x
x=3
y=2
z = f(x) #value of x used as actual parameter
print 'z =', z
print 'x =', x
print 'y =', y
When run, this code prints,
x=4
z=4
x=3
y=2
A default argument is an argument that can be optionally provided in a given function
call. When not provided, the corresponding parameter provides a default value. Eg:

def greet(name, msg = "Good morning!"):


"""
This function greets to
the person with the
provided message.
If message is not provided,
it defaults to "Good
morning!"
"""

print("Hello",name + ', ' + msg)


greet("Kate")
greet("Bruce","How do you do?")

Output:
Hello Kate, Good morning!
Hello Bruce, How do you do?

Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable is recognized.
Parameters and variables defined inside a function is not visible from outside. Hence, they have a
local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory.
The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.

Page 18
GE8151-Problem Solving and Python Programming Unit-I

Eg:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20

Local Scope and Local Variables


A local variable is a variable that is only accessible from within a given function. Such
variables are said to have local scope .

Global Variables and Global Scope


A global variable is a variable that is defined outside of any function definition. Such
variables are said to have global scope .

Variable max is defi ned outside func1 and func2 and therefore “global” to each.

Page 19
GE8151-Problem Solving and Python Programming Unit-I

Programs

1. Python program to swap two variables

# To take input from the user


x = input('Enter value of x: ')
y = input('Enter value of y: ')
#x = 5
#y = 10
# create a temporary variable and swap the
values x = x + y
y=x-y
x=x+y
print 'The value of x after swapping:’,x
print 'The value of y after swapping:’,y

2. Python Program to calculate the square root

# Note: change this value for a different


result num = 8
# uncomment to take the input from the
user #num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

3. Distance between two points


import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)

4. Write a function that draws a grid like the following:


+----+----+
| | |
| | |
| | |
| | |
+----+----+
| | |
| | |
| | |
| | |
+----+----+

Common to all Branch Page 20


GE8151-Problem Solving and Python Programming Unit-I

def print_border():
print ("+", "- " * 4, "+", "- " * 4, "+")

def print_row():
print ("|", " " * 8, "|", " " * 8, "|")

def block():
print_border()
print_row()
print_row()
print_row()
print_row()

block()
block()
print_border()

5. Adding two numbers using user defined function.


# Program to illustrate
# the use of user-defined
functions def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))

6. Program to circulate the values of n variables


from collections import deque
lst=[1,2,3,4,5] d=deque(lst)
print d
d.rotate(2)
print d
Output:[3,4,5,1,2]

(OR)
list=[10,20,30,40,50]
n=2 #Shift 2 location
list[n:]+list[:n]

Output: [30,40,50,10,20]
Page 21
1

UNIT II
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions:
return values, parameters, local and global scope, function composition, recursion; Strings: string
slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative
programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary
search.

Conditionals and recursion

Modulus operator
The modulus operator works on integers and yields the remainder when the first
operand is divided by the second. In Python, the modulus operator is a percent sign (%). The
syntax is the same as for other operators:
>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
So 7 divided by 3 is 2 with 1 left over.
The modulus operator turns out to be surprisingly useful. For example, you can check
whether one number is divisible by another—if x % y is zero, then x is divisible by y.
Also, you can extract the right-most digit or digits from a number. For example, x % 10
yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.

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
True and False are special values that belong to the type bool; they are not strings:
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
2

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

Logical operators
There are three logical operators: and, or, and not. The semantics (meaning) of these
operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is
greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions is true,
that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is
false, that is, if x is less than or equal to y. The operands of the logical operators should be
boolean expressions. Any nonzero number is interpreted as “true.”
>>> 17 and True
True

Keyboard input
Python 2 provides a built-in function called raw_input that gets input from the keyboard.
In Python 3, it is called input.
>>> text = raw_input()
What are you waiting for?
>>> print text
What are you waiting for?
>>> name = raw_input('What...is your name?\n')
What...is your name?
Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!

The sequence \n at the end of the prompt represents a newline, which is a special
character that causes a line break.
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42

Conditional statement (if)


Conditional statements give us the ability to check conditions and change the behavior
of the program accordingly. The syntax for if statement:
3

if <test_expression>:
<body>

Eg:
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")

The boolean expression after if is called the condition. If it is true, then the indented
statement gets executed. If not, nothing happens.

Alternative execution (if… else)


A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax looks like this:

if <test_expression>:
<body_1>
else:
<body_2>
4

Eg:
# Program checks if the number is positive or
negative num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays a message to that effect. If the condition is false, the second set of statements is
executed.

Chained conditionals
Sometimes there are more than two possibilities and we need more than two branches.
The syntax looks like this:
if <test_expression_1>:
<body1>
elif <test_expression_2>:
<body2>
elif <test_expression_3>:
<body3>
….
…..
else:
<bodyN>
5

Eg:
# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message

num = 3.4

# Try these two variations as well:


# num = 0
# num = -4.5

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
6

elif is an abbreviation of “else if.” Again, exactly one branch will be executed. 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.
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and so on. If
one of them is true, the corresponding branch executes, and the statement ends. Even if more
than one condition is true, only the first true branch executes.

Nested conditionals
One conditional can also be nested within another. We could have written the trichotomy
example like this:
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

The outer conditional contains two branches. The first branch contains a simple
statement. The second branch contains another if statement, which has two branches of its own.
Those two branches are both simple statements, although they could have been conditional
statements as well.
Although the indentation of the statements makes the structure apparent, nested
conditionals become difficult to read very quickly.
Logical operators often provide a way to simplify nested conditional statements. For
example, we can rewrite the following code using a single conditional:

if 0 < x:
if x < 10:
print 'x is a positive single-digit number.'
The print statement is executed only if we make it past both conditionals, so we can get
the same effect with the and operator:
7

if 0 < x and x < 10:


print 'x is a positive single-digit number.'

Recursion
Recursion is the process of calling the function that is currently executing. It is legal for
one function to call another; it is also legal for a function to call itself. An example of recursive
function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

# An example of a recursive function to


# find the factorial of a number
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))

num = 4
print("The factorial of", num, "is", calc_factorial(num))
Output:
The factorial of 4 is 24

The Advantages of recursion


1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested
iteration. The Disadvantages of recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.

Iteration
The while statement
The keyword while followed by a test expression (which can be any valid expression),
and a colon. Following the header is an indented body. The test expression is evaluated. If it
8

evaluates to True, then the body of the loop is executed. After executing the body, the test
expression is evaluated again. While test expression evaluates to True, the body of the loop is
executed. When the test expression evaluates to False, the loop is terminated and execution
continues with the statement following the body.

while
<test_expression>:
<body>

Eg:
def sequence(n):
while n != 1:
print n,
if n%2 == 0: # n is even
n = n/2
else: # n is odd
n = n*3+1

The condition for this loop is n != 1, so the loop will continue until n is 1, which
makes the condition false.
Each time through the loop, the program outputs the value of n and then checks whether
9

it is even or odd. If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3+1.
For example, if the argument passed to sequence is 3, the resulting sequence is 3,10, 5, 16, 8, 4,
2, 1.

The for Statement


Python’s for statement iterates over the items of any sequence (a list or a string), in the
order that they appear in the sequence.

for val in sequence:


Body of for

Eg:

# Program to find the sum of all numbers stored in a list


# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
10

The range() function


If you do need to iterate over a sequence of numbers, the built-in function range() comes
in handy. It generates arithmetic progressions:

Eg:
# Prints out the numbers
0,1,2,3,4 for x in range(5):
print(x)

This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.

Python break and continue


The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate
the innermost loop.
The working of break statement in for loop and while loop is shown below.

Eg:
# Prints out
0,1,2,3,4 count = 0
while True:
print(count)
count += 1 if
count >= 5:
break
11

The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
The working of continue statement in for and while loop is shown below.

Eg:
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

Python pass statement


The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action.
Eg:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
... pass
...
Another place pass can be used is as a place-holder for a function or conditional body
when you are working on new code, allowing you to keep thinking at a more abstract level. The
pass is silently ignored:
>>> def initlog(*args):
... pass # Remember to implement this!
12

FRUITFUL FUNCTIONS
Return values
The built-in functions we have used, such as abs, pow, and max, have produced results.
Calling each of these functions generates a value, which we usually assign to a variable or use as
part of an expression.
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10

But so far, none of the functions we have written has returned a value. In this chapter, we
are going to write functions that return values, which we will call fruitful functions, for want of a
better name. The first example is area, which returns the area of a circle with the given radius:
def area(radius):
temp = 3.14159 * radius**2
return temp

We have seen the return statement before, but in a fruitful function the return statement
includes a return value. This statement means: Return immediately from this function and use the
following expression as a return value. The expression provided can be arbitrarily complicated,
so we could have written this function more concisely:
def area(radius):
return 3.14159 * radius**2

On the other hand, temporary variables like temp often make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a conditional.
We have already seen the built-in abs, now we see how to write our own:
def absolute_value(x):
if x < 0:
return -x
else:
return x

Since these return statements are in an alternative conditional, only one will be executed.
As soon as one is executed, the function terminates without executing any subsequent
statements. Another way to write the above function is to leave out the else and just follow the if
condition by the second return statement.
def absolute_value(x):
if x < 0:
return -x
return x

Think about this version and convince yourself it works the same as the first one.
13

Code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement. The following version of absolute_value fails to do this:
def
absolute_value(x):
if x < 0:
return -x
elif x > 0:
return x

This version is not correct because if x happens to be 0, neither condition is true, and the
function ends without hitting a return statement. In this case, the return value is a special value
called None:
>>> print absolute_value(0)
None

None is the unique value of a type called the NoneType:


>>> type(None)

All Python functions return None whenever they do not return another value.

Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable is recognized.
Parameters and variables defined inside a function is not visible from outside. Hence, they have a
local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory.
The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.

Eg:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
14

Local Scope and Local Variables


A local variable is a variable that is only accessible from within a given function. Such
variables are said to have local scope .

Global Variables and Global Scope


A global variable is a variable that is defined outside of any function definition. Such
variables are said to have global scope .

Variable max is defi ned outside func1 and func2 and therefore “global” to
each. Function Composition
As you should expect by now, you can call one function from within another. This ability
is called composition.
As an example, we’ll write a function that takes two points, the center of the circle and a
point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the perimeter point
is in xp and yp. The first step is to find the radius of the circle, which is the distance between the
two points. Fortunately, we’ve just written a function, distance, that does just that, so now all we
have to do is use it:
15

radius = distance(xc, yc, xp, yp)


The second step is to find the area of a circle with that radius and return it. Again we will
use one of our earlier functions:
result = area(radius)

return result Wrapping that up in a function, we get:


def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius) return result

We called this function area2 to distinguish it from the area function defined earlier.
There can only be one function with a given name within a given module. The temporary
variables radius and result are useful for development and debugging, but once the program is
working, we can make it more concise by composing the function calls:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))

STRINGS
A string is a sequence of characters. You can access the characters one at a time with the
bracket operator:
>>> fruit = 'banana'
>>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.
The expression in brackets is called an index. The index indicates which character in the
sequence you want (hence the name).
But you might not get what you expect:
>>> print letter
a

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the
index is an offset from the beginning of the string, and the offset of the first letter is zero.
>>> letter = fruit[0]
>>> print letter
b

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is
the 2th(“two-eth”) letter.
You can use any expression, including variables and operators, as an index, but the
value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers, not float
16

len
len is a built-in function that returns the number of characters in a string:
>>> fruit = 'banana'
>>> len(fruit)
6

To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range
The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since
we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you
have to subtract 1 from length:
>>> last = fruit[length-1]
>>> print last
a

Alternatively, you can use negative indices, which count backward from the end of
the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and
so on.
String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”
character, including the first but excluding the last. This behavior is counterintuitive, but it
might help to imagine the indices pointing between the characters, as in Figure 8.1.
If you omit the first index (before the colon), the slice starts at the beginning of the string.
If you omit the second index, the slice goes to the end of the string:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
''
17

An empty string contains no characters and has length 0, but other than that, it is the
same as any other string.

Strings are immutable


It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string. For example:
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
The “object” in this case is the string and the “item” is the character you tried to assign.
For now, an object is the same thing as a value, but we will refine that definition later. An item
is one of the values in a sequence.
The reason for the error is that strings are immutable, which means you can’t change
an existing string. The best you can do is create a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!

This example concatenates a new first letter onto a slice of greeting. It has no effect
on the original string.

String methods
A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper().
>>> word = 'banana'
>>> new_word =
word.upper()
>>> print new_word
BANANA

This form of dot notation specifies the name of the method, upper, and the name of
the string to apply the method to, word. The empty parentheses indicate that this method
takes no argument.
A method call is called an invocation; in this case, we would say that we are
invoking upper on the word.
As it turns out, there is a string method named find that is remarkably similar to
the function we wrote:
>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1
18

In this example, we invoke find on word and pass the letter we are looking for as
a parameter.
Actually, the find method is more general than our function; it can find substrings, not
just characters:
>>> word.find('na')
2

It can take as a second argument the index where it should start:


>>> word.find('na', 3)
4
And as a third argument the index where it should stop:
>>> name = 'bob'
>>> name.find('b', 1, 2)
-1
This search fails because b does not appear in the index range from 1 to 2 (not including 2).

String comparison
The relational operators work on strings. To see if two strings are equal:
if word == 'banana':
print 'All right, bananas.'

Other relational operations are useful for putting words in alphabetical order:
if word < 'banana':
print 'Your word,' + word + ', comes before
banana.' elif word > 'banana':
print 'Your word,' + word + ', comes after
banana.' else:
print 'All right, bananas.'

Python does not handle uppercase and lowercase letters the same way that people do.
All the uppercase letters come before all the lowercase letters, so:Your word, Pineapple, comes
before banana.
A common way to address this problem is to convert strings to a standard format, such as
all lowercase, before performing the comparison. Keep that in mind in case you have to defend
yourself against a man armed with a Pineapple.
19

Program
1. Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7
# uncomment to take input from the
user #num = int(input("Enter a number:
")) factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative
numbers") elif num == 0:
print("The factorial of 0 is
1") else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

2. Python program to find the factorial of a number using recursion.

def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)

# Change this value for a different


result num = 7

# uncomment to take input from the user


#num = int(input("Enter a number: "))

# check is the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
20

3. Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number between",num1,",",num2,"and",num3,"is",largest)

4. Python program to find the sum of natural numbers up to n where n is provided by user

# change this value for a different result


num = 16

# uncomment to take input from the user


#num = int(input("Enter a number: "))

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till
zero while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
21

5. Python program to check if the input number is prime or

not num = 407

# take input from the user


# num = int(input("Enter a number: "))

# prime numbers are greater than 1


if num > 1:
# check for factors for
i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

6. Program to display the Fibonacci sequence up to n-th term where n is provided by the
user

# change this value for a different result


nterms = 10

# uncomment to take input from the user


#nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 0

# check if the number of terms is


valid if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
22

print("Fibonacci sequence upto",nterms,":")


print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

7. Python Program to Check Armstrong

Number num = 1634

# Changed num variable to string,


# and calculated the length (number of digits)
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each


digit temp = num
while temp > 0: digit =
temp % 10 sum +=
digit ** order temp
//= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

8. Python program to check if the input number is odd or even.

# A number is even if division by 2 give a remainder of 0.


# If remainder is 1, it is odd number.
23

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

9. Program to add two matrices using nested loop

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)

10. Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
24

result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]

# iterate through rows of


X for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of
Y for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)

11. Program to transpose a matrix using nested loop

X = [[12,7],
[4 ,5], [3
,8]]

result = [[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result:
print(r)

12. Program to sort alphabetically the words form a string provided by the user

# change this value for a different result


my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the


user #my_str = input("Enter a string: ")
25

# breakdown the string into a list of


words words = my_str.split()

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

13. Python program to find the H.C.F of two input number

# define a function
def computeHCF(x, y):

# choose the smaller number


if x > y:
smaller =
y else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i

return hcf

num1 = 54
num2 = 24

# take input from the user


# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))

print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

14. Linear search

list = [4,1,2,5,3]
#set up array
26

search = int(input("Enter search number"))


# ask for a number
for i in range(0,len(list)):
#repeat for each item in
list if search==list[i]:
#if item at position i is search time
print(str(search) + " found at position " +
str(i))
#report find

15. Binary search


def binary_search(item_list,item):
first = 0
last =
len(item_list)-1
found = False
while( first<=last and not
found): mid = (first +
last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found

print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))

16. Program to find Fibonacci series upto n

>>> def fib(n): # write Fibonacci series up to n


... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a)
... a, b = b, a+b
...
>>> # Now call the function we just defined:
... fib(2000)

You might also like