Python Notes Unit1
Python Notes Unit1
Python Notes Unit1
Unit-1
Python is an elegant and robust programming language that delivers both the power and
general applicability of traditional compiled languages with the ease of use (and then
some) of simpler scripting and interpreted languages. It allows you to get the job done, and
then read what you wrote later. You will be amazed at how quickly you will pick up the
language as well as what kind of things you can do with Python, not to mention the things
that have already been done. Your imagination will be the only limit.
● Work on Python began in late 1989 by Guido van Rossum, then at CWI (Centrum
voorWiskundeenInformatica, the National Research Institute for Mathematics and
Computer Science) in the Netherlands.
● It was eventually released for public distribution in early 1991. How did it all begin?
Like C, C++, Lisp, Java, and Perl, Python came from a research background where the
programmer was having a hard time getting the job done with the existing tools at
hand, and envisioned and developed a better way.
● At the time, van Rossum was a researcher with considerable language design
experience with the interpreted language ABC, also developed at CWI, but he was
unsatisfied with its ability to be developed into something more. Having used and
partially developed a higher-level language like ABC, falling back to C was not an
attractive possibility.
● Some of the tools he envisioned were for performing general system administration
tasks, so he also wanted access to the power of system calls that were available
through the Amoeba distributed operating system. Although van Rossum gave some
thought to an Amoeba-specific language, a generalized language made more sense,
and late in 1989, the seeds of Python were sown.
Features
● High Level
● Object Oriented
● Scalable:
Python is often compared to batch or Unix shell scripting languages. Simple shell scripts
handle simple tasks. They may grow (indefinitely) in length, but not truly in depth. There
is little code-reusability and you are confined to small projects with shell scripts.
● Extensible
● Portable
● Easy to Learn
● Easy to Read
● Easy to Maintain
● Robust
● Effective as a Rapid Prototyping Tool
● A Memory Manager
● Interpreted and (Byte-) Compiled
Downloading and Installing Python
On Windows, the default installation area is C:\Python2x. TRy to avoid installing Python in
C:\Program Files.
Running Python
There are three different ways to start Python.
● The simplest way is by starting the interpreter interactively, entering one line of
Python at a time for execution.
● Another way to start Python is by running a script written in Python. This is
accomplished by invoking the interpreter on your script application.
● Finally, you can run from a graphical user interface (GUI) from within an integrated
development environment (IDE). IDEs typically feature additional tools such as an
integrated debugger, text editor, and support for a wide range of source code control
tools such as CVS.
Command-Line Options When starting Python from the command-line, additional options
may be provided to the interpreter. Here are some of the options to choose from:
-d Provide debug output
-O Generate optimized bytecode (resulting in .pyo files)
-S Do not run importsite to look for Python paths on startup
-v Verbose output (detailed trace on import statements)
-m mod run (library) module as a script
-Q opt division options (see documentation)
-c cmd Run Python script sent in as cmd string
file Run Python script from given file (see later)
Python Documentation
Introduction
In all interactive examples, you will see the
● Python primary ( >>> ) The primary prompt is a way for the interpreter to let you
know that it is expecting the next Python statement,
● secondary ( ... ) prompts.
while the secondary prompt indicates that the interpreter is waiting for additional
input to complete the current statement.
print Statement :
>>> myString = 'AIMLDS SECSIOT '
>>> print myString
SECSIOT
>>> myString
'AIMLDS SECSIOT '
The underscore (_) also has special meaning in the interactive interpreter: the last
evaluated expression. So after the code above has executed, _ will contain the string:
>>> _
SECSIOT
● Python's print statement, paired with the string format operator (%), supports
string substitution, much like the printf() function in C:
>>> print ("%s is number %d!" % ("Python", 1) )
Python is number 1!
Input Statement:
The int() function converts the string num to an integer so that the mathematical operation
can be performed
>>> input
<built-in function input>
Comments:
The hash or pound ( # ) sign signals that a comment begins from the # and continues until
the end of the line.
Single line comment :
>>> # one comment
>>> print ('Hello World!') # another comment
Hello World!
We can observe that on running this code, there will be no output; thus, we utilize the
strings inside triple quotes(""") as multi-line comments.
Python Docstring
The strings enclosed in triple quotes that come immediately after the defined function are
called Python docstring. It's designed to link documentation developed for Python modules,
methods, classes, and functions together. It's placed just beneath the function, module, or
class to explain what they perform. The docstring is then readily accessible in Python using
the __doc__ attribute.
Code
Output:
def foo():
"This is a doc string."
return True
Algorithm: Algorithm is a step-by-step process of solving a well-defined computational problem. In practice, in
order to solve any complex real life problems, first we have to define the problem and then, design algorithm
to solve it. Generally, algorithms are used to simplify the program implementation. Also, defined step-by-step
procedure to solve the problem is called algorithm.
Example 1:
Write an algorithm to how to Make “Maggi Noodles”?
Step 1: Start
Step 2: Take pan with water Step
3: Put pan on the burner Step 4:
Switch on the gas/burner Step 5:
Put magi and masala Step 6: Give
two minutes to boil Step 7: Take
off the pan
Step 8: Take out the magi with the help of fork/spoon Step
9: Put the maggi on the plate and serve it
Step 10: Stop.
Example 2:
Write an algorithm to print “Good Morning”.
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop
Example 3:
Write an algorithm to find area of a rectangle.
Step 1: Start
Step 2: Take length and breadth and store them as L and B?
Step 3: Multiply by L and B and store it in area
Step 4: Print area
Step 5: Stop
Program: A program is a collection instructions that can do a particular task or problem. Programming is the
process of taking an algorithm and writing it in a particular programming language, so that it can b executed
by a computer. Programmers can use any of the programming languages to write programs.
Why the name Python? Rossum was fan of a comedy series from late seventies. The name "Python" was
adopted from the same series "Monty Python's Flying Circus".
Applications of Python
Python is a high level general purpose programming language that is used to develop a wide range of
applications including image processing, text processing, web, and enterprise level applications using
scientific and numeric data from network. Some of the key applications of python includes:
❖ In operations of Google search engine, youtube, etc.
Data Types:
Variables can hold values of different types called data types. The standard data types supported by Python
includes -
1) Numbers
a. Integers
b. Floating Point Numbers
c. Complex Numbers
2) None
3) Sequences
a. Strings
b. Tuple
c. List
4) Sets
5) Mappings – Dictionary
1) Numbers: Number refers Numerical Values. This data type is immutable i.e. its value cannot be
changed. These are of three different types:
a) Integers
b) Float/floating point
c) Complex
a) Integers: Numbers like 5 or other whole numbers are referred to as integers. Bigger whole numbers are
called long integers. For example, 56958558585855L is a long integer. Note that a long integer must have ‘l’ or
‘L’ as the suffix.
Integers contain Boolean Type which is a unique data type, consisting of two constants, True & False. A
Boolean True value is Non-Zero, Non-Null and Non-empty.
Example
b) Floating point numbers: Numbers with fractions or decimal point are called floating point numbers.
Example
y= 12.36
3) Sequence:
A sequence is an ordered collection of items, indexed by positive integers. It is combination of mutable and
non mutable data types. Three types of sequence data type available in Python are Strings, Lists & Tuples.
i) Strings: String is an ordered sequence of letters/characters. String is also defined as a group or set of
characters. They are enclosed in single quotes (‘ ’) or double (“ ”). Strings are immutable data types.
Example
>>> a = 'Ram'
ii) List: List is data type available in python. It is a sequence in which elements are written as a list of comma
separated values between square brackets. List is mutable data type which means the value of its elements
can be changed.
Syntax: list_variable=[var1,var2, ]
Example
rgukt = *“spam”, 20.5,5]
iii) Tuples: Tuples is data type available in python. Tuples are sequence of elements separated by comma
enclosed in parenthesis. They are immutable data type.
Example
my_tuple = (4, 2, 5, 8)
4) Sets: Set is an unordered collection of values, of any type, with no duplicate entry. Sets are immutable.
Example
s = set ([1,2,34])
5) Mapping: This data type is unordered and mutable. A dictionary comes under Mappings.
Dictionary: Dictionary is a data type available in python which store values as a pair of key and value. Each key
is separated from its value by a colon (:), and consecutive items are separated by commas. The entire items in
a dictionary are enclosed in curly brackets {}. Dictionary keys must be of immutable type.
Example: d = {1:'a',2:'b',3:'c'}
A mutable variable is one whose value may change , whereas in an immutable variable the value cannot be
change.
Multiple assignments
Python allows you to assign a single value to several variables simultaneously. For
example: a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location.
You can also assign multiple objects to multiple variables. For example – Example:
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object
with the value "john" is assigned to the variable
Example:
sum=a+b (Expression)
a and b operands and + is operator.
Operators are the constructs that are used to manipulate the value of operands. Some basic operators include
+, -, *, /.
Operands are the values.
A Python statement is a unit of code that the Python interpreter can execute.
Python Identifiers:
Identifier is the name given to entities like class, functions, variables etc. For naming identifier, there are some
basic rules that you must follow. These rules are
⮚ 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 (_).
⮚ Keywords cannot be used as identifiers.
⮚ An identifier cannot start with a digit. 1variable is invalid, but variable1 is valid.
⮚ Identifier names are case sensitive. For example myvar and myVar are not the same.
⮚ Punctuation characters such @,$,£ and % are not allowed within identifiers.
⮚ Does not include space character in the identifier name
Example:
Valid identifier names are: sum, _my_var, num1, r, var_33, first etc
Invalid identifier names are: 1num, my-var, %check, basic sal etc
Comments
Comments are the non-executable statements in a program. They are just added to describe the code of the
program. Comments make the program easily readable and understandable by the programmer as well as
other users who are seeing the code. The interpreter simply ignores the comments.
In python, a has sign (#) symbol writing as a comment.
Example
#This is a comment
#print out Hello
print('Hello')
#program ends here
Multi-line comments
If we have comments that extend multiple lines, We can use triple quotes, either ''' or """.
Example
"""This is also a
perfect example
of multi-line comments"""
Keywords in Python
Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any
other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords
are case sensitive. There are 33 keywords in Python. All the keywords except True, False and None are in
lowercase and they must be written as it is. The list of all the keywords are given below.
Indentation:
White space at the beginning of the line is called indentation. These whitespaces or the indentation are
very important in python. Most of the programming languages like C, C++, Java use braces { } to define a
block of code. Python uses indentation.
Leading white space (spaces and taps) at the beginning of each statement, which is used to determine the
group of statement, is known as “indentation”.
Example
If A > B :
else:
In the above example, if statements are a type of code block. If the “if” expression evaluates to true, then
Block1 is executed, otherwise, it executes Block2. Obviously, blocks can have multiple lines. As long as they are
all indented with the same amount of spaces, they constitute one block.
Example:
result=a+b
(a, b operands and + is operator)
3) Logical Operators
Python supports three logical operators logical and, logical or and logical not. Normally, the logical expressions
are evaluated from left to right.
Symbol Descriptio
n
If both the operands are true, then the condition becomes true.
and (&)
Ex: x and y
If any one of the operand is true, then the condition becomes true.
or (|)
Ex: x or y
True if operand is false (complements the operand)
Not (!)
Ex: not x
4) Assignment Operators
Assignment operators are used in Python to assign values to variables or operands. It is also known as shortcut
operators that includes +=, -=, *=, /=, %=, //= and **= etc.
5) Unary Operators
Unary operators act on single operands. Python supports Unary minus operator. An operand is preceded by a
minus sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary minus operator.
Similarly, if the number is negative, it becomes positive after applying the unary minus operator.
Ex: b=10
a = - (b)
The result of the expression is a = -10, because variable b has a positive value. After applying unary minus operator
(-) on the operand b, the value becomes -10, which indicates it as a negative value.
6) Bitwise Operators
Bitwise operators perform operations at the bit level. These operators include bitwise AND, bitwise OR,
bitwise XOR, and shift operators.
In the following example, we have two integer values 1 and 3 and we will perform bitwise AND operation and
display the result.
Example:
Bitwise OR
Bitwise OR | will give 0 only if both the operands are 0 otherwise, 1. The
truth table for bitwise OR.
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1
In the following example we have two integer values 1 and 2 and we will perform bitwise OR operation and
display the result.
Example:
Bitwise XOR
Bitwise XOR ^ will give 1 for odd number of 1s otherwise, 0. The
truth table for bitwise XOR.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
In the following example we have two integer values 2 and 7 and we will perform bitwise XOR operation and
display the result. Example,
Shift Operators:
Python supports two bitwise shift operators. They are shift left (<<) and shift right (>>). These operations are
used to shift bits to the left or to the right.
i) << Binary Left Shift: The left operands value is moved left by the number of bits specified by the right
operand.
Example:
a=60
a<<2
output: 240
ii) >> Binary Right Shift: The left operands value is moved right by the number of bits specified by the right
operand.
Example:
a=60
a >> 2
output: 15
7) Membership operators
Python supports two types of membership operators – in and not in. These operators used to test a value or
variable is found in a sequence. (stings, list or tuple)
Example:
>>>a=”Hello World”
>>>print (‘H’ in a)
True
>>>print (‘m’ in a)
False
8) Identity operators
Python supports two types of identity operators. These operators compare the memory locations of two
objects.
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.
Above given example, see that x and y are integers of same values, so they are equal as well as identical. But
a and b 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.
Operato Descriptio
r n
% =, / =, //
Assignment operators
=,
- =, + =, * =
Operator precedence table is important as it affects how an expression is evaluated. For example
>>>10+3*5
160
This is because * has higher precedence than +, so it first multiplies 30 and 5 and then adds 10.
Output:
What’s your name? Ramesh
Enter your age: 20
Ramesh, you are 20 years old
Print Statement
Syntax: print expression/constant/variable
Print evaluates the expression before printing it on the monitor. Print statement outputs an entire (complete)
line and then goes to next line for subsequent output (s). To print more than one item on a single line, comma
(,) may be used.
Example
>>> print “Hello”
Hello
>>> print 5.5
5.5
>>> print 4+6
10
>>a=5
>>b=10
>>print (a,b)
Function Descriptio
n
int(x) Converts x to an integer
Errors
An error is a term used to describe any issue that arises unexpectedly that cause a computer to not function
properly. There are three types of errors generally occur during running (execution) of a program. They are (i)
Syntax error; (ii) Logical error; and (iii) Runtime error.
(i) Syntax error: Every programming language has its own rules and regulations (syntax). If we overcome the
particular language rules and regulations, the syntax error will appear (i.e. an error of language resulting
from code that does not conform to the syntax of the programming language). It can be recognized during
compilation time.
Example
a=0
while a < 10
a=a+1
print a
In the above statement, the second line is not correct. Since the while statement does not end with “:”. This
will flash a syntax error.
(ii) Logical error: Programmer makes errors while writing program that is called “logical error‟. It is an error in
a program's source code that results in incorrect or unexpected result. It is a type of runtime error that may
simply produce the wrong output or may cause a program to crash while running. The logical error might only
be noticed during runtime, because it is often hidden in the source code and are typically harder to find and
debug.
a = 100
while a < 10:
a=a+1
print a
In the above example, the while loop will not execute even a single time, because the initial value of “a” is 100.
(iii) Runtime error: A runtime error is an error that causes abnormal termination of program during running
time. In general, the dividend is not a constant but might be a number typed by you at runtime. In this case,
division by zero is illogical. Computers check for a "division by zero" error during program execution, so that
you can get a "division by zero" error message at runtime, which will stop your program abnormally. This type
of error is called runtime error.
Example
(a) A=10
B=0
print (A/B)
Exercise
1. Write a program that asks two people for their names; stores the names in variables called name1 and
name2; says hello to both of them.
2. Write a Python program which accepts the radius of a circle from the user and compute the area.
Sample Output :
r = 1.1
Area = 3.8013271108436504
3. Write a Python program which accepts the user's first and last name and print them in reverse order
with a space between them.
4. Write a Python program that will accept the base and height of a triangle and compute the area.
17. Write a program to calculate average of two numbers. Print their deviation.
18. Write a program to covert a floating point number into the corresponding integer.
19. Write a program to convert a integer into the corresponding floating point number.
20. Write a program to calculate area of triangle using Heron’s formula. ( Hint: Heron’s formula is :
area = sqrt(s*(s-a)*(s-b)*(s-c))
Assignment-I
1. Define datatype. What are the datatypes available in Python? Explain in detail.
2. What is an Identifier? List out the rules of an identifier.
3. What is a Python? Write notes on Python history, features and Applications.
4. What is indentation? Explain with an example.
5. Define the following terms.
i) Algorithm ii) Interpreter iii) variable iv) Expression v) Value vi) comments
Assignment-II
1. What is an operator? Explain all the operators available in Python.
2. What is the type conversion or Type casting? Explain type casting functions along with examples.
Control Statements:
A control statement is a statement that determines the control flow of a set of instructions. It decides the
sequence in which the instructions in a program are to be executed. A control statement can either comprise
of one or more instructions.
i) Sequential Control Statements: The code of Python program is executed sequentially from the first line of
the program to its last line. That is, the second statement is executed after the first, the third statement is
executed after the second, so on and so forth. This method is known as sequential Control flow and these
statements called as sequential control statements.
ii) Selection Control Statements: Some cases, execute only a set of statements called as selection control
statements. This method is known as selection control flow.
iii) Iterative Control Statements: execute a set of statements repeatedly called as Iterative control
statements. This method is known as Iterative control flow.
SELECTION/CONDITIONAL CONTROL STATEMENTS
The decision control statements usually jumps from one part of the code to another depending on whether a
particular condition is satisfied or not. That is, they allow you to execute statements selectively on certain
decisions. Such type of decision control statements are known as selection control statements or conditional
branching statements. Python supports different types of conditional branching statements which are as
follows:
● If statement
● If –else statement
● Nested if statement
● If-elif-else statement
Syntax of if statement
if test_expression:
Statement1
Statement2
…….
Statement n
Statement x
Output:
x=11
Output:
Enter the age: 35
You are eligible to vote
if –else Statement: An if-else construct, first the test expression (Boolean expression) is evaluated. If the
expression is True, statement block 1 is executed and statement block 2 is skipped. Otherwise, if the
expression is False, statement block 2 is executed and statement block 1 is ignored.
Syntax of if statement
if test_expression:
Statement block 1
else:
Statement block 2
Statement x
Example 3: Write a program to determine whether a person is eligible to vote or not. If he is not eligible,
display how many years are left to be eligible.
age=int(input(“Enter the age:”))
if (age>=18):
print (“You are eligible to vote”)
else:
yrs=18-age
print (“You have to wait for another”+ str(yrs)+ “years to
cast your vote”)
Output:
Enter the age: 10
You have to wait for another 8 years to cast your vote.
Example 4: Write a program to find whether the given number is even or odd.
num=int(input(“Enter any number :”))
if (num%2==0):
print (num, “is even”)
else:
print (num, “is odd”)
Output:
Enter any number: 125
125 is odd
Nested if statements: To perform more complex check, if statement can be nested, that is can be placed one
inside the other. In such a case, the inner if statement is the statement part of the outer one. Nested if
statements are used to check if more than one condition is satisfied.
Example 5: Write a python program to find the given number is positive or negative number, if positive
number then compare with 100, if number is greater than 100, output display as “high” otherwise display as
“low”.
num = float(input("Enter a number: "))
if num >0:
if num >100:
print("High")
else:
print("Low")
else:
print("Negative number")
Output:
Enter a number: 5
low
if-elif-else Statement: The elif statement allows to check multiple expressions and executes block of
statements wherever the condition returns as True. From there, it exit from the entire if-elif-else block. If any
of the expression not returns as true, then it executes the else block code.
Example 6: Program to test whether a number entered by the user is negative, positive or equal to Zero?
num=int(input(“Enter any number”))
if (num==0):
print (“The value is equal to zero”)
elif (num>0):
print (“The number is positive”)
else:
print (“The number is negative”)
Output:
Enter any number : -10
The number is negative
Exercise:
1. Write a program to find larger of two numbers.
2. A Company decides to give bonus to all its employees on Diwali. A 5% bonus on salary is given to the male
workers and 10% bonus on salary to the female workers. Write a Python program to enter the salary of the
employee and gender of the employee. If the salary of the employee is less than Rs/- 10,000 then the
employee gets an extra 2% bonus on salary. Calculate the bonus that has to be given to the employee and
display the salary that the employee will get.
3. Write a program to find whether a given year is a leap year or not.
4. Write a program to determine whether the character entered is a vowel or not.
5. Write a program to find the greatest number from the three numbers.
6. Write a program that prompts the user to enter a number between 1-7 and then displays the
corresponding day of the week.
7. Write a program to calculate tax given the following conditions:
If income is less than 1,50,000 then no tax
If taxable income is 1,50,001 – 3,00,000 then charge 10% tax If
taxable income is 3,00,001 – 5,00,000 then charge 20% tax If
taxable income is above 5,00,001 then charge 30% tax
8. Write a program to enter the marks of a student in four subjects. Then calculate the total and aggregate, and
display the grade obtained by the student. If the student scores an aggregate greater than 75%, then the grade
is Distinction. If aggregate is 60>= and <75, then the grade is First Division. If aggregate is 50>= and <60, then
the grade is Second Division. If aggregate is 40>= and <50, then the grade is Third Division. Else the grade is fail.
9. Write a program to calculate roots of a quadratic equation.
10. Write a program to take input from the user and then check whether it is a number or a character. If it is a
character, determine whether it is in uppercase or lowercase.
11. Write a program that prompts users to enter a character (O, A,B,C,F). Then using if-elif-else construct
display Outstanding, Very Good, Good, Average and Fail respectively.
12. Write a program to read two numbers. Then find out whether the first number is a multiple of the
second number.
While loop:
The while loop provides a mechanism to repeat one or more statements while a particular condition is True.
Example 7: Write a python program to print first 10 numbers using a while loop. i=0
while (i<=10):
print (i)
i=i+1
Output:
1
2
3
4
5
6
7
8
9
10
Example 8: Write a python program to print first 10 numbers using a while loop on the same line. i=0
while (i<=10):
print (i, end= ' ')
i=i+1
Output:
1 2 3 4 5 6 7 8 9 10
Example 9: Program to display the Fibonacci sequence up to n-th term where n is provided by the user nterms
= 10
n1 = 0
n2 = 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
p
r
i
n
t
(
"
F
i
b
o
n
a
c
c
i
s
e
q
u
e :
n p
c r
e i
n
u t
p (
t n
o 1
" ,
, e
n n
t d
e =
r '
m
s ,
,
" '
: )
"
) n
t
w h
h
i =
l
e n
1
c
o +
u
n n
t 2
n
< 1
n =
t
e n
r 2
m
s n
2 n
t
= h
count += 1
Output:
Fibonacci sequence upto 10 :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Note: In simple terms, end specifies the values which have to be printed after the print statement has been
executed. In above example, the values printed on the same line, used end with a separator. You can specify
any separator like tab (\t), space, comma, etc., with end.
Exercise:
1. Write a program to calculate the sum and average of first 10 numbers.
2. Write a program to print 20 horizontal asterisks(*).
3. Write a program to calculate the sum of numbers from m to n.
4. Write a program to read the numbers until -1 is encountered. Also count the negative, positive and
zeros entered by user.
5. Write a program to read the numbers until -1 is encountered. Find the average of positive number and
negative numbers entered by the user.
6. Write a program to find whether the given number is an Armstrong Number or not.
7. Write a program to enter a decimal number. Calculate and display the binary equivalent of this number.
8. Write a program to enter a binary number and convert it into decimal number.
9. Write a program to read a character until a * is encountered. Also count the number of uppercases,
lowercase and numbers entered by the users.
10. Write a program to enter a number and then calculate the sum of the digits.
11. Write a program to calculate GCD of two numbers.
12. Write a program to print the reverse of a number.
13. Write a program to read a number from the user and find whether it is a palindrome number or not.
14. Write program using a while loop that asks the user for a number and prints a countdown from that
number to zero.
15. Write a program that prompts users to enter numbers. Once the user enters -1, it displays the count,
sum and average of even numbers and that of odd numbers.
For loop:
The for loop provides a mechanism to repeat a task(set of statements) until a particular condition is true.
The range() produces a sequence of numbers starting with beginning (inclusive) and ending with one less
than the numeber end. The step argument is optional. By default, every number in range is incremented by 1
but we can specify a different increment using step.
Note: Step size can be either positive or negative but it cannot be equal to zero.
Example 10:
Program:
for i in range (1,5):
print (i, end=“ ”)
Output: 1 2 3 4
Example 11:
Program:
for i in range(1, 10, 2):
print (i, end= “ ” )
Output: 1 3 5 7 9
Example 12:
Program:
for i in range(10):
print (i, end= “ ” )
Output: 0 1 2 3 4 5 6 7 8 9
Example 13:
Program:
for i in range(1, 15):
print (i, end= “ ” )
Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Example 14:
Program:
for i in range(1, 20,3): print
(i, end= “ ” )
Output: 1 4 7 10 13 16 19
Nested Loops:
Nested loops, that is, loops can be placed inside other loops.This feature works any loop like while loop as well
as for loop, but it is most commonly used with the for loop, because this is easiest to control.
Exercise:
1. Write a program to print the following pattern.
RGUKT 1 – 1 2 3 4 5
RGUKT 2 – 1 2 3 4 5
RGUKT 3 – 1 2 3 4 5
RGUKT 4 – 1 2 3 4 5
RGUKT 5 – 1 2 3 4 5
break STATEMENT:
Break can be used to unconditionally jump out of the loop. It terminates the execution of the loop. Break can
be used in while loop and for loop. Break is mostly required, when because of some external condition, we
need to exit from a loop.
Continue Statement:
This statement is used to tell Python to skip the rest of the statements of the current loop block and to move
to next iteration, of the loop. Continue will return back the control to the beginning of the loop. This can also
be used with both while and for statement.
Exercise:
1. Write a program to classify a given number as prime or composite.
2. Write a program to read the numbers until -1 is encountered. Count the number of prime numbers and
composite numbers entered by the user.
3. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
4. Write a Python program to Print first 100 prime numbers.
Pass Statement:
The pass statement is used when a statement is required syntactically but no command or code has to be
executed. It specifies a null operation or No Operation (NOP) statement. Nothing happens when the pass
statement is executed.
Output:
PASS: H
PASS: E
PASS: L
PASS: L
PASS: O
Done
The pass statement is used as a placeholder. For example, if we have a loop that is not implement yet, but we
may wish to write some piece of code in it in the future. In such cases, pass statement can be written because
we cannot have an empty body of the loop. Though the pass statement will not do anything but it will make
the program syntactically correct.
Note: The difference between comment and pass statements is, pass is null statement that is executed by
python interpreter, comment is non-executable statement that is ignored(not executed) by python interpreter.
Example 18:
for i in range(1,11):
print (i, end="")
else:
print ("\n Done")
Output:
1 2 3 4 5 6 7 8 9 10
Done
Example 19:
for i in range(1,20):
if (i==5):
break
print (i, end="")
else:
print ("\n Done")
Output:
1234
2) else statement with the while loop, the else statement is executed when the conditions becomes False. The
while loop can be terminated with a break statement. In such case, the else part is ignored. Hence, a while
loop's else part runs if no break occurs and the condition is false.
Example 20:
i=1
while (i<0):
print (i)
i=i-1
else:
print (i, "is not negative so loop did not execute")
Output:
1 is not negative so loop did not execute
Example 21:
i=1
while (i<10):
if (i==6):
break
print (i, end=“ ”)
i=i+1
else:
print ("Completed")
Output:
12345
Assignment-III
1. Write a detail notes on conditional/selectional branching statements supported by python?
2. Explain for and while loop in python along with syntax, flowchart and an example?
3. Write a program to print the following pattern.
PYTHON 1 – 1 2 3 4 5
PYTHON 2 – 1 2 3 4 5
PYTHON 3 – 1 2 3 4 5
PYTHON 4 – 1 2 3 4 5
PYTHON 5 – 1 2 3 4 5
Assignment-IV
1. Explain range() function along with an example?
2. Explain break statement with the help of an example?
3. Explain continue statement with the help of an example?
4. Explain about pass statement in Python?
5. Write short notes on for-else and while-else?
6. Write a Python program to print prime numbers between 500 to 600.
Functions
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. It avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters): #Keyword def marks the start of function header.
statement(s)
Examples:
User-defined functions
Functions that we define ourselves to do certain specific task are referred as user-defined functions.
Functions that readily come with Python are called built-in functions. If we use functions
written by others in the form of library, it can be termed as library functions.
All the other functions that we write on our own fall under user-defined functions. So, our
user-defined function could be a library function to someone else.
Example 22:
Write a python script to print a message using user-defined function.
def message( ):
message( )
Docstring
The first string after the function header is called the docstring and is short for documentation string. It is used
to explain in brief, what a function does.
Example 23:
def greet(name):
parameter"""
print(greet.__doc )
Output:
This function greets to
name parameter
Once we have defined a function, we can call it from another function, program or even the Python prompt. To
call a function we simply type the function name with appropriate parameters.
Example 24:
def greet(name):
Example 25:
# This program has two functions. First we define the main function. def
main( ):
message( )
print('Goodbye!')
def message( ):
main( )
Example 26:
#Providing Function Definition
def sum(x,y):
s=x+y
print(s)
sum(10,20)
sum(20,30)
Example 27:
# Function definition is here
def changeme( x ):
=5
print changeme( x )
Example 28:
# Function definition is here
def changeme( x ):
=5
print changeme( x )
Void Functions:
Function performs a task, and does not contain a return statement such functions are called void functions. Void
functions do not return anything. 'None' is a special type in Python which is returned after a void function ends.
Example 29:
def check (num):
if (num%2==0):
print “True”
else:
print “False”
Output:
False
None
Exercise:
1. Write a Python function to find the Min of three numbers.
3. Write a Python function to calculate the factorial of a number (a non-negative integer). The function
accepts the number as an argument.
4. Write a Python function that accepts a string and calculate the number of upper case letters and lower
case letters.
5. Write a Python function that takes a number as a parameter and check the number is prime or not.
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 definition does not alter the flow of execution of program, as the statement
inside the function is not executed until the function is called.
On a function call, instead of going to the next statement of program, the control jumps to the body of the
function; executes all statements of the function in the order from top to bottom and then comes back to the
point where it left off. This remains simple, till a function does not call another function. Simillarly, in the
middle of a function, program might have to execute statements of the other function and so on.
The First type of data is the data passed in the function call. This data is called arguments. Arguments can be
variables and expressions.
Argument is the actual value of this variable that gets passed to function.
The second type of data is the data received in the function definition(function header). This data is called
parameters. Parameters must be variable to holding coming values.
Parameter is variable in the declaration of function.
1. Required Arguments: In the required arguments, the arguments are passed to a function in correct
positional order. The number of arguments in the function call should exactly match with the number of
parameters specified in the function definition.
Example:
2. Keyword Arguments: Python allows functions to be called using keyword arguments. When we call
functions in this way, the order (position) of the arguments can be changed.
Example:
def display(name,x,y):
display(y=20,name="RAMESH",x=40)
3. Default Arguments: A default argument is an argument that assumes a default value which defined in
the called function if a value is not provided in the function call for that argument.
Example:
def display(name,course="BTECH"):
display("RAJESH","MBA")
display(course="MSC",name="RAJU") display(name="RAVI")
In the function definition we use an asterisk (*) before the parameter name to denote this kind of argument.
Here is an example.
Example
def display(*names):
for i in names:
print("Hello",name)
display("Monica","Luke","Steve","John")
Scope of Variables:
Scope of variable refers to the part of the program in which a variable is accessible. Some of the variables may
not exist for the entire duration of the program. In which part of the program can access a variable and which
part of the program a variable exists depends on how the variable has been declared.
1) Global Variables : The variables which are defined (declared) in the main body of the program called
global variables. Those variables can be accessed anywhere in the program.
Example
x=50 #global variable
def test ( ):
Inside test x is 50
Value of x is 50
Example:
x=50 # global variable
def test ( ):
x+= 10
will produce
Inside test x is 60
Value of x is 60
2) Local variables: The variables which are defined within a function is called local variables. Local variables
can be accessed only within the function. It exists as long as the function is executing. Function parameters
behave like local variables in the function.
Example
X=50 #global variable
def test ( ):
y
test() =
2
0
#local variable print (“Value of x is”, X, “y
Example
x=50 #global variable
def test ( ):
x=5 #local variable
y=2 #local variable
print (“Value of x & y inside the function are” , x , y)
test()
print (“Value of x outside the function is” , x)
This code will produce following output: Value
of x & y inside the function are 5 2 Value of x
outside the function is 50
global var1
var1= “Morning”
show() print (“In function var is –”, var)
print (“Outside function, var1 is – ”, var1)
print (“var is ”, var)
Output:
In function var is – Good
Outside function, var1 is – Morning var
is – Good