0% found this document useful (0 votes)
103 views

18CS55 - Python Module 1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

18CS55 - Python Module 1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Python 17CS664

Module 1 Python Basics


Sl.no Content

1 Entering Expressions into the Interactive Shell

2 The Integer, Floating-Point, and String Data Types

3 String Concatenation and Replication

4 Storing Values in Variables

5 Your First Program

6 Dissecting Your Program

7 Flow control, Boolean Values, Comparison Operators

8 Boolean Operators, Mixing Boolean and Comparison Operators

9 Elements of Flow Control, Program Execution, Flow Control Statements,

10 Importing Modules Ending a Program Early with sys.exit

11 Functions, def Statements with Parameters, Return Values and return Statements,

12 The None Value, Keyword Arguments and print(),

13 Local and Global Scope,

14 The global Statement, Exception Handling,

15 A Short Program: Guess the Number

WHAT IS PYTHON
Swetha D. Dept.of CSE / ISE
Python 17CS664

Python is a clear and powerful object-oriented programming language, comparable to Perl,


Ruby, Scheme, or Java.

HISTORY
 Python is a high-level, interpreted scripting language developed in th late 1980s by
Guido van Rossum at the National Research Institute for Mathematics and Computer
Science in the Netherlands.
 The initial version was published at the alt.sources newsgroup in 1991, and version 1.0
was released in 1994.
 Python 2.0 was released in 2000, and the 2.x versions were the prevalent releases
until December 2008.
 At that time, the development team made the decision to release version 3.0, which
contained a few relatively small but significant changes that were not backward
compatible with the 2.x versions.
 Python 2 and 3 are very similar, and some features of Python 3 have been backported
to Python 2. But in general, they remain not quite compatible

SOME OF PYTHON'S NOTABLE FEATURES


 Uses an elegant syntax, making the programs you write easier to read.
 Is an easy-to-use language that makes it simple to get to know how the program is
working.
 Comes with a large standard library that supports many common programming
tasks such as connecting to web servers, searching text with regular expressions,
reading and modifying files.
 Python's interactive mode makes it easy to test short snippets of code. There's also a
bundled development environment called IDLE.
 Is easily extended by adding new modules implemented in a compiled language
such as C or C++.
 Can also be embedded into an applicati on to provide programmable interface.
 Runs anywhere, includingMac OS X, Windows, Linux, and Unix, with unofficial
builds also available for Android and iOS.
 Is free software in two senses . It doesn't cost anything to download or use Python,
or to include it in your application.
 Python can also be freely modified and re-distributed, because while the language is
copyrighted it's available under an open source license.

Swetha D. Dept.of CSE / ISE


Python 17CS664

SOME PROGRAMMING-LANGUAGE FEATURES:


 A variety of basic data types are available: numbers (floating point, complex, and
unlimited-length long integers), strings (both ASCII and Unicode), lists, and
dictionaries.
 Python supports object-oriented programming with classes and multiple inheritance.
 Code can be grouped into modules and packages.
 The language supports raising and catching exceptions, resulting in cleaner error
handling.
 Data types are strongly and dynamically typed. Mixing incompatible types (e.g.
attempting to add a string and a number) causes an exception to be raised, so errors are
caught sooner.
 Python contains advanced programming features such as generators and list
comprehensions.
 Python's automatic memory management frees you from having to manually allocate
and free memory in your code.

1.Entering Expressions into the Interactive Shell


we can run the interactive shell by launching IDLE. On Windows, open the Start menu, select Python
3.3, and then select IDLE (Python GUI).

A window with the >>> prompt should appear; that’s the interactive shell.

Enter 2 + 2 at the prompt to have Python do some simple math.

>>> 2 + 2
4
In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction in the
language. Expressions consist of values(such as 2) and operators (such as +), and they can always
evaluate (that is,reduce) down to a single value. That means you can use expressions any where in Python
code that you could also use a value.

In the previous example, 2 + 2 is evaluated down to a single value, 4. A single value with no operators is
also considered an expression, though it evaluates only to itself, as shown here:

>>> 2
2

Math Operators from Lowest to Highest

Swetha D. Dept.of CSE / ISE


Python 17CS664

Operator Meaning Example


+ Addition Sum= a+b
- Subtraction Diff= a-b
* Multiplication Pro= a*b
/ Division Q = a/b
X = 5/3
(X will get a value 1.666666667)
// Floor Division – returns only F = a//b
integral part after division X= 5//3 (X will get a value 1)
% Modulus – remainder after R = a %b
division (Remainder after dividing a by b)
** Exponent E = x** y
(means x to the powder of y)

The order of operations (also called precedence) of Python math operators is similar to that of
mathematics. The ** operator is evaluated first; the *, /, //, and % operators are evaluated next, from left
to right; and the + and - operators are evaluated last (also from left to right)

>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 48565878 * 578453
28093077826734
>>> 2 ** 8
256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
3
>>> 23 % 7
2
>>> 2 + 2
4
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0

Evaluating an expression reduces it to a single value.

Swetha D. Dept.of CSE / ISE


Python 17CS664

(5 - 1) * ((7 + 1) / (3 - 1))

4 * ((7 + 1) / (3 - 1))

4 * ( 8 ) / (3 - 1))

4*(8)/(2)

4 * 4.0

16.0

if you type in a bad Python instruction, Python won’t be able to understand it and will display a
SyntaxError error message, as shown here:

>>> 5 +
File "<stdin>", line 1
5+
^
SyntaxError: invalid syntax

>>> 42 + 5 + * 2
File "<stdin>", line 1
42 + 5 + * 2
^
SyntaxError: invalid syntax

2.The Integer, Floating-Point, and String Data Types


Common Data Types

Data type Examples

Integers -2, -1, 0, 1, 2, 3, 4, 5

Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25

Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

Swetha D. Dept.of CSE / ISE


Python 17CS664

common data types in Python are listed in Table. The values -2 and 30, for example, are said to be integer
values. The integer (or int) data type indicates values that are whole numbers. Numbers with a decimal
point, such as 3.14, are called floating-point numbers (or floats).

Note that even though the value 42 is an integer, the value 42.0 would be a floating-point number.

Error message SyntaxError: EOL while scanning string literal, you probably forgot the final single quote
character at the end of the string, such as in this example:

>>> 'Hello world!

SyntaxError: EOL while scanning string literal

3. String Concatenation and Replication

+ operator(String Concatenation)

The meaning of an operator may change based on the data types of the values next to it. For example, + is
the addition operator when it operates on two integers or floating-point values. However, when + is used
on two string values, it joins the strings as the string concatenation operator.

>>> 'Alice' + 'Bob'


'AliceBob'

The expression evaluates down to a single, new string value that combines the text of the two strings.
However, if you try to use the + operator on a string and an integer value, Python will not know how to
handle this, and it will display an error message.

>>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
'Alice' + 42
TypeError: Can't convert 'int' object to str implicitly

* operator(string Replication)

The * operator is used for multiplication when it operates on two integer or floating-point values. But
when the * operator is used on one string value and one integer value, it becomes the string replication
operator.
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'

Swetha D. Dept.of CSE / ISE


Python 17CS664

The * operator can be used with only two numeric values (for multiplication) or one string value and one
integer value (for string replication) Otherwise, Python will just display an error message.

>>> 'Alice' * 'Bob'


Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
'Alice' * 'Bob'
TypeError: can't multiply sequence by non-int of type 'str'
>>> 'Alice' * 5.0
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
'Alice' * 5.0
TypeError: can't multiply sequence by non-int of type 'float'

4. Storing Values in Variables

A variable is like a box in the computer’s memory where you can store a single value. If you want to use
the result of an evaluated expression later in your program, you can save it inside a variable.

Assignment Statements

An assignment statement consists of a variable name, an equal sign (called the assignment operator), and
the value to be stored. If you enter the assignment statement spam = 42, then a variable named spam will
have the integer value 42 stored in it.

spam = 42 is like telling the program, “The variable spam now has the integer value 42 in it.”

For example, enter the following into the interactive shell:


>>> spam = 40
>>> spam
40
>>> eggs = 2
>>> spam + eggs
42

>>> spam + eggs + spam


82
Swetha D. Dept.of CSE / ISE
Python 17CS664

w >>> spam = spam + 2


>>> spam
42

Enter the following code into the interactive shell to try overwriting a string:

>>> spam = 'Hello'


>>> spam
'Hello'
>>> spam = 'Goodbye'
>>> spam
'Goodbye

Rules for declaring variable

It is a good programming practice to name the variable such that its name indicates its purpose
in the program. There are certain rules to be followed while naming a variable
1 Variable name must not be a keyword
2 They can contain alphabets (lowercase and uppercase) and numbers, but should not
start with a number.
3 It may contain a special character underscore(_), which is usually used to combine
variables with two words like my_salary, student_name etc. No other special
characters like @, $ etc. are allowed.
4 As Python is case-sensitive, variable name sum is different from SUM, Sum etc.
Valid variable names Invalid variable names
balance current-balance (hyphens are not allowed)

currentBalance current balance (spaces are not allowed)

current_balance 4account (can’t begin with a number)

_spam 42 (can’t begin with a number)

SPAM total_$um (special characters like $ are not allowed)

account4 'hello' (special characters like ' are not allowed)

Your First Program

While the interactive shell is good for running Python instructions one at a time, to write entire Python
programs, you’ll type the instructions into the file editor. The file editor is similar to text editors such as

Swetha D. Dept.of CSE / ISE


Python 17CS664

Notepad or TextMate, but it has some specific features for typing in source code. To open the file editor
in IDLE, select File4New Window.

The window that appears should contain a cursor awaiting your input, but it’s different from the
interactive shell, which runs Python instructions as soon as you press enter. The file editor lets you type in
many instructions,
save the file, and run the program. Here’s how you can tell the difference between the two:

1. The interactive shell window will always be the one with the >>> prompt.
2. The file editor window will not have the >>> prompt.

# This program says hello and asks for my name.


print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

From the menu at the top of the file editor window, select File ->Save As. In the Save As window, enter
hello.py in the File Name field and then click Save. Once you’ve saved, let’s run our program. Select
Run->Run Module or just press the F5 key
>>>
Hello world!
What is your name?
Al
It is good to meet you, Al
The length of your name is:
2
What is your age?
4
You will be 5 in a year.
>>>

Comments
The following line is called a comment.

# This program says hello and asks for my name.


it is asking my name
Swetha D. Dept.of CSE / ISE
Python 17CS664

It is a good programming practice to add comments to the program wherever required.


This will help someone to understand the logic of the program. Comment may be in a
single line or spread into multiple lines. A single-line comment in Python starts with the
symbol #. Multiline comments are enclosed within a pair of 3-single quotes.

Ex1. #This is a single-line comment

Ex2. '''
T
h
i
s

i
s

m
u
l
t
i
l
i
n
e
comment '''

Python (and all programming languages) ignores the text written as comment lines.
They are only for the programmer’s (or any reader’s) reference.

The print() Function

The print() function displays the string value inside the parentheses on the screen.

print('Hello world!')
print('What is your name?') # ask for their name The line print('Hello world!') means “Print out the text in
the string 'Hello world!'.” When Python executes this line, you say that Python is
calling the print() function and the string value is being passed to the function. A value that is passed to a
function call is an argument. Notice that the quotes are not printed to the screen. They just mark where
the string begins and ends; they are not part of the string value.

Swetha D. Dept.of CSE / ISE


Python 17CS664

The input() Function

Python uses the built-in function input() to read the data from the keyboard. When this function is
invoked, the user-input is expected. The input is read till the user presses enter- key. For example:
>>> str1=input()
Hello how are you? #user input
>>> print(“String is “,str1)
String is Hello how are you? #printing str1

When input() function is used, the curser will be blinking to receive the data. For a better understanding,
it is better to have a prompt message for the user informing what needs to be entered as input. The input()
function itself can be used to do so, as shown below –

>>> str1=input("Enter a string: ")


Enter a string: Hello
>>> print("You have entered: ",str1)
You have entered: Hello

One can use new-line character \n in the function input() to make the cursor to appear in the next line of
prompt message –
>>> str1=input("Enter a string:\n")
Enter a string: Hello #cursor is pushed here

The key-board input received using input() function is always treated as a string type. If you need an
integer, you need to convert it using the function int(). Observe the following example –
>>> x=input("Enter x:")
Enter x:10 #x takes the value “10”, but not 10
>>> type(x) #So, type of x would be str
<class 'str'>
>>> x=int(input("Enter x:")) #use int()
Enter x:10
>>> type(x) #Now, type of x is int
<class 'int'>

A function float() is used to convert a valid value enclosed within quotes into float number as shown
below –

>>> f=input("Enter a float value:")


Enter a float value: 3.5
>>> type(f)
<class 'str'> #f is actually a string “3.5”
>>> f=float(f) #converting “3.5” into float value 3.5
>>> type(f)
<class 'float'>

A function chr() is used to convert an integer input into equivalent ASCII character.

Swetha D. Dept.of CSE / ISE


Python 17CS664

>>> a=int(input("Enter an integer:")) Enter an integer:65


>>> ch=chr(a)
>>> print("Character Equivalent of ", a, "is ",ch)
Character Equivalent of 65 is A

Printing the User’s Name


The following call to print() actually contains the expression 'It is good to meet you, ' + myName between
the parentheses.

print('It is good to meet you, ' + myName)

Remember that expressions can always evaluate to a single value. If 'Al' is the value stored in myName
on the previous line, then this expression evaluates to 'It is good to meet you, Al'. This single string value
is then passed to print(), which prints it on the screen.

The len() Function


You can pass the len() function a string value (or a variable containing a string), and the function
evaluates to the integer value of the number of characters in that string.

print('The length of your name is:')


print(len(myName))

The length of your name is: 2

Enter the following into the interactive shell to try this:


>>> len('hello')
5
>>> len('My very energetic monster just scarfed nachos.')
46
>>> len('')
0

The str(), int(), and float() Functions


The str(), int(), and float() functions will evaluate to the string, integer,and floating-point forms of the
value you pass, respectively
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99')
-99

Swetha D. Dept.of CSE / ISE


Python 17CS664

>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
>>> float(10)
10.0

For example, the input() function always returns a string, even if the user enters a number. Enter spam
= input() into the interactive shell and enter 101when it waits for your text.
>>> spam = input()
101
>>> spam
'101'
The value stored inside spam isn’t the integer 101 but the string '101'.If you want to do math using the
value in spam, use the int() function to get the integer form of spam and then store this as the new value
in spam.

>>> spam = int(spam) int('101')


>>> spam
101

Now you should be able to treat the spam variable as an integer instead of a string.
>>> spam * 10 / 5
202.0

Note that if you pass a value to int() that it cannot evaluate as an integer, Python will display an error
message.

>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'

>>> int('twelve')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'

The int() function is also useful if you need to round a floating-point number down.
>>> int(7.7)
7

Swetha D. Dept.of CSE / ISE


Python 17CS664

>>> int(7.7) + 1
8

Flow Control

In a flowchart, there is usually more than one way to go from the start to the end. The same is true for
lines of code in a computer program. Flowcharts represent these branching points with diamonds, while
the other steps are represented with rectangles. The starting and ending steps are represented with
rounded rectangles.

Boolean Values
the Boolean data type has only two values: True and False
>>> spam = True
>>> spam
True

>>> true

Swetha D. Dept.of CSE / ISE


Python 17CS664

Traceback (most recent call last):


File "<pyshell#2>", line 1, in <module>
true
NameError: name 'true' is not defined

>>> True = 2 + 2
SyntaxError: assignment to keyword

Comparison Operators
Comparison operators compare two values and evaluate down to a single Boolean value.

Comparison Operators

Operator Meaning
== Equal to

!= Not equal to

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

These operators evaluate to True or False depending on the values you give them.

>>> 42 == 42
True
>>> 42 == 99
False
>>> 2 != 3
True
>>> 2 != 2

Swetha D. Dept.of CSE / ISE


Python 17CS664

False

The == and != operators can actually work with values of any data type.
>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> True == True
True
>>> True != False
True
>>> 42 == 42.0
True
>>> 42 == '42'
False

The <, >, <=, and >= operators, on the other hand, work properly only with integer and floating-point
values.

>>> 42 < 100


True

>>> 42 > 100


False

>>> 42 < 42
False

>>> eggCount = 42
>>> eggCount <= 42
True

>>> myAge = 29
>>> myAge >= 10
True

Boolean Operators
The three Boolean operators (and, or, and not) are used to compare Boolean values. Like comparison
operators, they evaluate these expressions down to a Boolean value. Let’s explore these operators in
detail, starting with the and operator.

Binary Boolean Operators

Swetha D. Dept.of CSE / ISE


Python 17CS664

The and and or operators always take two Boolean values (or expressions), so they’re considered binary
operators. The and operator evaluates an expression to True if both Boolean values are True; otherwise, it
evaluates to False.

Enter some expressions using and into the interactive shell to see it in action.
>>> True and True
True
>>> True and False
False
The "and" Operator’s Truth Table
Expression Evaluates to…
True and True True
True and False False
False and True False
False and False False

On the other hand, the or operator evaluates an expression to True if either of the two Boolean values is
True. If both are False, it evaluates to False.
>>> False or True
True
>>> False or False
False

The or Operator’s Truth Table


Expression Evaluates to…
True and True True
True and False True
False and True True
False and False False

The not Operator


Unlike and and or, the not operator operates on only one Boolean value (or expression). The not operator
simply evaluates to the opposite Boolean value.
>>> not True
False
>>> not not not not True
True

The not Operator’s Truth Table


Expression Evaluates to…
not True False
not False True

Mixing Boolean and Comparison Operators


Swetha D. Dept.of CSE / ISE
Python 17CS664

Since the comparison operators evaluate to Boolean values, you can use them in expressions with the
Boolean operators.
>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True

The computer will evaluate the left expression first, and then it will evaluate the right expression. When it
knows the Boolean value for each, it will then evaluate the whole expression down to one Boolean value

(4 < 5) and (5 < 6)

True and (5 < 6)

True and True

True

The Boolean operators have an order of operations just like the math operators do. After any math and
comparison operators evaluate Python evaluates the not operators first, then the and operators, and then
the or operators

/*
=-
NOT AND OR

Elements of Flow Control


Flow control statements often start with a part called the condition, and all are followed by a block of
code called the clause.

Conditions
Conditions always evaluate down to a Boolean value, True or False. A flow control statement
decides what to do based on whether its condition is True or False, and almost every flow control
statement uses a condition.

if( a>b)
{
-----if()
{
}
-----

Swetha D. Dept.of CSE / ISE


Python 17CS664

----
}
if a>b :
print()
print()
print()

Blocks of Code
Lines of Python code can be grouped together in blocks. You can tell when a block begins and ends from
the indentation of the lines of code. There are three rules for blocks.

1. Blocks begin when the indentation increases.


2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing
block’s indentation.
Blocks are easier to understand by looking at some indented code, so let’s find the blocks in part of a
small game program, shown here:

if name == 'Mary':
print('Hello Mary')
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')

Program Execution
The most common type of flow control statement is the if statement. An if statement’s clause (that is, the
block following the if statement) will execute if the statement’s condition is True. The clause is skipped if
the condition is False.

In plain English, an if statement could be read as, “If this condition is true, execute the code in the
clause.”

In Python, an if statement consists of the following:


• The if keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the if clause)

if condition:
Statement block

Entry

Swetha D. Dept.of CSE / ISE


False
condition?

True
Statement Block

Exit
Python 17CS664

Consider an example –

if name == 'Alice':
print('Hi, Alice.')

else Statements/ Alternative Execution

An if clause can optionally be followed by an else statement. The else clause is executed only when the if
statement’s condition is False. In plain English, an else statement could be read as, “If this condition is
true, execute this code. Or else, execute that code.” An else statement doesn’t have a condition, and in
code, an else statement always consists of the following:
• The else keyword

Swetha D. Dept.of CSE / ISE


Python 17CS664

• A colon
• Starting on the next line, an indented block of code (called the else
clause)

if condition:
Statement block -1
else:

Statement block -2

True False
Condition?

Statement block-1 Statement block -2

if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')

elif Statements /Chained Conditionals


While only one of the if or else clauses will execute, you may have a case where you want one of many
possible clauses to execute. The elif statement is an “else if” statement that always follows an if or
another elif statement. It provides another condition that is checked only if any of the previous conditions
were False. In code, an elif statement always consists of the following:

Swetha D. Dept.of CSE / ISE


Python 17CS664

• The elif keyword


• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)

if condition1:
Statement Block-1
elif condition2:
Statement Block-2
|
|
|
|
elif condition_n:
Statement Block-n
else:
Statement Block-(n+1)

if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')

Swetha D. Dept.of CSE / ISE


Python 17CS664

if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')

Swetha D. Dept.of CSE / ISE


Python 17CS664

while Loop Statements


You can make a block of code execute over and over again with a while statement. The code in a while
clause will be executed as long as the while statement’s condition is True. In code, a while statement
always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the while
clause)

while condition:

statement_1 statement_2
…………….
statement_n

statements_after_while

Here, while is a keyword. The condition is evaluated first. Till its value remains true,
the statement_1 to statement_n will be executed. When the condition becomes
false, the loop is terminated and statements after the loop will be executed. Consider an
example –

n=1
while n<=5:
print(n) #observe
indentation n=n+1

print("over")

The output of above code segment would be –


1
2
3
4
5
over

spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1

Swetha D. Dept.of CSE / ISE


Python 17CS664

2.1.1 Infinite Loops, break and continue


A loop may execute infinite number of times when the condition is never going to become
false. For example,

n=1
while True:
print(n)
n=n+1

Here, the condition specified for the loop is the constant True, which will never get
terminated. Sometimes, the condition is given such a way that it will never become false
and hence by restricting the program control to go out of the loop. This situation may
happen either due to wrong condition or due to not updating the counter variable.

In some situations, we deliberately want to come out of the loop even before the normal
termination of the loop. For this purpose break statement is used. The following example
depicts the usage of break. Here, the values are taken from keyboard until a negative
number is entered. Once the input is found to be negative, the loop terminates.
while True:
x=int(input("Enter a
number:")) if x>= 0:
print("You have entered ",x)
else:
print("You have entered a negative number!!")
break #terminates the loop

Sample output:

Enter a number:23
You have entered
23 Enter a
number:12 You have
entered 12 Enter a
number:45 You have
entered 45 Enter a
number:0 You have
entered 0 Enter a
number:-2
You have entered a negative number!!

Swetha D. Dept.of CSE / ISE


In the above example, we have used the constant True as condition for while-loop, which
will never become false. So, there was a possibility of infinite loop. This has been avoided
by using break statement with a condition. The condition is kept inside the loop such a
way that, if the user input is a negative number, the loop terminates. This indicates that, the
loop may terminate with just one iteration (if user gives negative number for the very first
time) or it may take thousands of iteration (if user keeps on giving only positive numbers as
input). Hence, the number of iterations here is unpredictable. But, we are making sure that
it will not be an infinite-loop, instead, the user has control on the loop.

Sometimes, programmer would like to move to next iteration by skipping few statements in
the loop, based on some condition. For this purpose continue statement is used. For
example, we would like to find the sum of 5 even numbers taken as input from the
keyboard. The logic is –
 Read a number from the keyboard
 If that number is odd, without doing anything else, just move to next iteration for
reading another number
 If the number is even, add it to sum and increment the accumulator variable.
 When accumulator crosses 5, stop the

program The program for the above task can be

written as –

sum=0
count=0
while True:
x=int(input("Enter a
number:")) if x%2 !=0:
continue
else:
sum+=x
count+=1

if count==5:
break

print("Sum= ", sum)

Sample Output:
Enter a number:13
Enter a number:12
Enter a number:4
Enter a number:5
Enter a number:-3
Enter a number:8
Enter a number:7
Enter a number:16
Enter a
number:6 Sum=
46

2.1.2 Definite Loops using for


The while loop iterates till the condition is met and hence, the number of iterations are
usually unknown prior to the loop. Hence, it is sometimes called as indefinite loop. When
we know total number of times the set of statements to be executed, for loop will be used.
This is called as a definite loop. The for-loop iterates over a set of numbers, a set of words,
lines in a file etc. The syntax of for-loop would be –
for var in list/sequence:
statement_1
statement_2
………………
statement_n

statements_after_for

Here, for and in are keywords

list/sequence is a set of elements on which the loop is iterated. That is,


the loop will be executed till there is an element in
list/sequence
statements constitutes body of the loop

Ex: In the below given example, a list names containing three strings has been created.
Then the counter variable x in the for-loop iterates over this list. The variable x takes the
elements in names one by one and the body of the loop is executed.

names=["Ram", "Shyam",
"Bheem"] for x in names:
print(x)

The output would be –


Ram
Shyam
Bheem

NOTE: In Python, list is an important data type. It can take a sequence of elements of
different types. It can take values as a comma separated sequence enclosed within square
brackets. Elements in the list can be extracted using index (just similar to extracting array
elements in C/C++ language). Various operations like indexing, slicing, merging, addition
and deletion of elements etc. can be applied on lists. The details discussion on Lists will be
done in Module 3.
The for loop can be used to print (or extract) all the characters in a string as shown below –
for i in "Hello":
PYTHON(18CS55)

print(i, end=’\t’)

Output:
H e l l o

When we have a fixed set of numbers to iterate in a for loop, we can use a function
range(). The function range() takes the following format –

range(start, end, steps)

The start and end indicates starting and ending values in the sequence, where
end is excluded in the sequence (That is, sequence is up to end-1). The default
value of start is 0. The argument steps indicates the increment/decrement in
the values of sequence with the default value as 1. Hence, the argument steps is
optional. Let us consider few examples on usage of range() function.

Ex1. Printing the values from 0 to 4 –


for i in range(5):
print(i, end=
‘\t’)

Output:
0 1 2 3 4
Here, 0 is the default starting value. The statement range(5) is same as
range(0,5)
and range(0,5,1).

Ex2. Printing the values from 5 to 1 –


for i in range(5,0,-1):
print(i, end= ‘\t’)

Output:
5 4 3 2 1
The function range(5,0,-1)indicates that the sequence of values are 5 to
0(excluded) in steps of -1 (downwards).
Ex3. Printing only even numbers less than 10 –
for i in range(0,10,2):
print(i, end= ‘\t’)

Output:
0 2 4 6 8

Swetha D Asst. professor Page 30


PYTHON(18CS55)

Importing Modules
Python
also comes with a set of modules called the standard library. Each module is a Python program
that contains a related group of functions that can be embedded in your programs. For example,
the math module has mathematics related functions, the random module has random number–
related functions, and so on.
Before you can use the functions in a module, you must import the module with an import
statement. In code, an import statement consists of
the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas

Once you import a module, you can use all the cool functions of that module. Let’s give it a try
with the random module, which will give us access to the random.ranint() function.

import random
for i in range(5):
print(random.randint(1, 10))
When you run this program, the output will look something like this:
4
1
8
4
1
Ending a Program Early with sys.exit()
The last flow control concept to cover is how to terminate the program. This always happens if
the program execution reaches the bottom of the instructions. However, you can cause the
program to terminate, or exit, by calling the sys.exit() function. Since this function is in the sys
module, you have to import sys before your program can use it.

import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')

Run this program in IDLE. This program has an infinite loop with no break statement inside. The
only way this program will end is if the user enters exit, causing sys.exit() to be called. When
response is equal to exit, the program ends. Since the response variable is set by the input()
function, the user must enter exit in order to stop the program.

Swetha D Asst. professor Page 31


PYTHON(18CS55)

def Statements with Parameters


When you call the print() or len() function, you pass in values, called arguments
in this context, by typing them between the parentheses. You can also
define your own functions that accept arguments.
def hello(name):
v print('Hello ' + name)
w hello('Alice')
hello('Bob')
When you run this program, the output looks like this:
Hello Alice
Hello Bob
Python facilitates programmer to define his/her own functions. The function
written once can be used wherever and whenever required. The syntax of
user-defined function would be –
def fnam(arg_list):
statement_1
statement_2
……………
Statement_n return
value

Here def is a keyword indicating it as a function definition.


fname is any valid name given to the function
arg_list is list of arguments taken by a function. These are treated
as inputs to the function from the position of function call.
There may be zero or more arguments to a function.
statements are the list of instructions to perform required task.
return is a keyword used to return the output value. This statement is
optional

The first line in the function def fname(arg_list)is known as function


header. The remaining lines constitute function body. The function header is
terminated by a colon and the function body must be indented. To come out
of the function, indentation must be terminated. Unlike few other
programming languages like C, C++ etc, there is no main()
function or specific location where a user-defined function has to be called.
The programmer has to invoke (call) the function wherever required

Swetha D Asst. professor Page 32


PYTHON(18CS55)

Consider a simple example of user-defined function –

def myfun():
print("Hello")
Observe indentation print("Inside the function")

Statements outside print("Example of function")


the function myfun()
without indentation. print("Example over")
myfun() is called here.

The output of above program would be –


Example of function
Hello
Inside the function
Example over

When creating a function using the def statement, you can specify what
the return value should be with a return statement. A return statement consists
of the following:
The return keyword
The value or expression that the function should return

import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very doubtful'

Swetha D Asst. professor Page 33


PYTHON(18CS55)

r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)

Swetha D Asst. professor Page 34

You might also like