18CS55 - Python Module 1
18CS55 - Python Module 1
11 Functions, def Statements with Parameters, Return Values and return Statements,
WHAT IS PYTHON
Swetha D. Dept.of CSE / ISE
Python 17CS664
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
A window with the >>> prompt should appear; that’s the interactive shell.
>>> 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
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
(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
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:
+ 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.
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'
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.
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.”
Enter the following code into the interactive shell to try overwriting a string:
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)
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
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.
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.
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 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.
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 –
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 –
A function chr() is used to convert an integer input into equivalent ASCII character.
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.
>>> 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.
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
>>> 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
>>> 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
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
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 < 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.
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
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
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
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()
{
}
-----
----
}
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.
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.”
if condition:
Statement block
Entry
True
Statement Block
Exit
Python 17CS664
Consider an example –
if name == 'Alice':
print('Hi, Alice.')
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
• 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?
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
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.')
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.')
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")
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
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!!
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
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
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
statements_after_for
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)
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 –
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.
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).
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
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.
def myfun():
print("Hello")
Observe indentation print("Inside the function")
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'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)