CSC 202 Note
CSC 202 Note
Python is an easy to learn, powerful high-level programming language. It has a simple but
effective approach to object-oriented programming. Python’s graceful semantics and syntax
together with its interpreted nature make it an ideal language for scripting and rapid
application development in many fields.
Advantages:
1
7. Dynamically typed language(No need to mention data type based on the value
assigned, it takes data type)
8. Object-Oriented and Procedural Programming language
9. Portable and Interactive
10. Ideal for prototypes – provide more functionality with less coding
11. Highly Efficient(Python’s clean object-oriented design provides enhanced process
control, and the language is equipped with excellent text processing and integration
capabilities, as well as its own unit testing framework, which makes it more efficient.)
12. Internet of Things(IoT) Opportunities
13. Interpreted Language
14. Portable across Operating systems
Disadvantages:
Applications:
2
11. Data Science and Machine Learning
12. Scripting
3
Keywords in Python are reserved words that can not be used as a variable name, function
name, or any other identifier.
List of Keywords in Python
Represents an
It is a Logical expression that It is a non-
and False nonlocal
Operator will result in local variable
not being true.
It is used to
It is used with It is a Logical
as create an alias finally not
exceptions Operator
name
pass is used
To import when the user
Break out a
break from specific parts pass doesn’t
Loop
of a module want any code
to execute
raise is used
It is used to
It is used to to raise
class global declare a raise
define a class exceptions or
global variable
errors.
Represents an
It is used to It is used to
expression
def define the import import a True
that will result
Function module
in true.
It is used to
It is used to
test if two Try is used to
del delete an is try
variables are handle errors
object
equal
4
Keyword Description Keyword Description Keyword Description
used to
statements, value is present
execute a
same as else- in a Tuple,
block of
if List, etc.
statements
1) Let’s start with typing print “Hello Python!” after the prompt.
>>>print("Hello Python!")
>>> x=1
>>> y=5
>>> z = x+y
Output: 6
5
A Python statement is an instruction that the Python interpreter can execute. There are
different types of statements in Python language as Assignment statements, Conditional
statements, Looping statements, etc. The token character NEWLINE is used to end a
statement in Python. It signifies that each line of a Python script contains a statement.
These all help the user to get the required output.
6
Declared using square brackets [] :
footballer = ['MESSI',
'NEYMAR',
'SUAREZ']
Whitespace is used for indentation in Python. Unlike many other programming languages
which only serve to make the code easier to read, Python indentation is mandatory. One
can understand it better by looking at an example of indentation in Python.
Role of Indentation in Python
A block is a combination of all these statements. Block can be regarded as the grouping of
statements for a specific purpose. Most programming languages like C, C++, and Java use
braces { } to define a block of code for indentation. One of the distinctive roles of Python is
its use of indentation to highlight the blocks of code. All statements with the same distance
to the right belong to the same block of code. If a block has to be more deeply nested, it is
simply indented further to the right.
Example 1:
The lines print(‘Logging on to geeksforgeeks…’) and print(‘retype the URL.’) are two
separate code blocks. The two blocks of code in our example if-statement are both indented
four spaces. The final print(‘All set!’) is not indented, so it does not belong to the else-
block.
Python3
# Python indentation
site = 'gfg'
7
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
Output
Logging on to geeksforgeeks...
All set !
Example 2:
To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is
required for indicating what block of code a statement belongs to. For example, j=1 and
while(j<=5): is not indented, and so it is not within the while block. So, Python code
structures by indentation.
Python3
j=1
print(j)
j=j+1
Output
1
2
3
8
4
5
What are Comments in Python
Python comments start with the hash symbol # and continue to the end of the
line. Comments in Python are useful information that the developers provide to make the
reader understand the source code. It explains the logic or a part of it used in the code.
Comments in Python are usually helpful to someone maintaining or enhancing your code
when you are no longer around to answer questions about it. These are often cited as useful
programming convention that does not take part in the output of the program but improves
the readability of the whole program.
Comments in Python are identified with a hash symbol, #, and extend to the end of the line.
Types of comments in Python
A comment can be written on a single line, next to the corresponding line of code, or in a
block of multiple lines. Here, we will try to understand examples of comment in Python one
by one:
Single-line comment in Python
Python single-line comment starts with a hash symbol (#) with no white spaces and lasts till
the end of the line. If the comment exceeds one line then put a hashtag on the next line and
continue the comment. Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See the following code
snippet demonstrating single line comment:
Example 1:
Python allows comments at the start of lines, and Python will ignore the whole line.
Python3
# This is a comment
print("GeeksforGeeks")
Output
GeeksforGeeks
Example 2:
Python also allows comments at the end of lines, ignoring the previous text.
Python3
9
sum = a + b # adding two integers
Output
4
Multiline comment in Python
Use a hash (#) for each extra line to create a multiline comment. In fact, Python multiline
comments are not supported by Python’s syntax. Additionally, we can use Python multi-
line comments by using multiline strings. It is a piece of text enclosed in a delimiter (“””)
on each end of the comment. Again there should be no white space between delimiter (“””).
They are useful when the comment text does not fit into one line; therefore need to span
across lines. Python Multi-line comments or paragraphs serve as documentation for others
reading your code. See the following code snippet demonstrating a multi-line comment:
A Python variable is a reserved memory location to store values. In other words, a variable in
a python program gives data to the computer for processing.
When we create a program, we often like to store values so that it can be used later. We use
objects to capture data, which then can be manipulated by computer to provide information.
By now we know that object/ variable is a name which refers to a value.
A) Identity of the object: It is the object's address in memory and does not change once it
has been created.
B) Type (i.e. Data Type): It is a set of values, and the allowable operations on those values.
It can be one of the following:
1. Number
10
Number data type stores Numerical Values. This data type is immutable i.e. value of its
object cannot be changed (we will talk about this aspect later). These are of three different
types:
i) Integers:
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99,
0, 17.
When we want a value to be treated as very long integer value appends L to the value. Such
values are treated as long integers by python.
>>> a = 10
>>> b = 5192L #example of supplying a very long value to a variable
>>> c= 4298114
>>> type(c) # type ( ) is used to check data type of value
ii) Floating Point: Numbers with fractions or decimal point are called floating point
numbers.
A floating point number will consist of sign (+,-) sequence of decimals digits and a dot such
as 0.0, -21.9, 0.98333328, 15.2963.
Example: y= 12.36
iii) Complex: Complex number in python is made up of two floating point values, one each
for real and imaginary part. For accessing different parts of variable (object) x; we will
use x.real and x.image. Imaginary part of the number is represented by j instead of i,
so 1+0j denotes zero imaginary part.
Example:
>>> x = 1+0j
>>> print (x.real,x.imag)
1.0 0.0
11
2. None
This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None.
3. Sequence
3.1) String: is an ordered sequence of letters/characters. They are enclosed in single quotes ('
') or double (" "). The quotes are not part of string. They only tell the computer where the
string constant begins and ends.
If we are not sure, what is the data type of a value, Python interpreter can tell us:
3.2) Lists: List is also a sequence of values of any type. Values in the list are called
elements / items. These are mutable and indexed/ordered. List is enclosed in square brackets.
3.3) Tuples:
Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable. Tuples are enclosed in (). We have already seen a tuple, in Example 2 (4, 2).
4. Sets
Set is an unordered collection of values, of any type, with no duplicate entry. Sets are
immutable.
Example:
{1, 2, 3, 4 }
5. Mapping
12
This data type is unordered and mutable. Dictionaries fall under Mappings.
5.1) Dictionaries: Can store any number of python objects. What they store is a key – value
pairs, which are accessed using key. Dictionary is enclosed in curly brackets.
Example: d = {1:'a',2:'b',3:'c'}
A Program needs to interact with the user to accomplish the desired task; this is done
using Input-Outputfacility. Input means the data entered by the user of the program. In
python, we have input() and raw_input ( ) function available for Input.
1) input()
Syntax:
input (expression)
If prompt is present, it is displayed on monitor, after which the user can provide data from
keyboard. Input takes whatever is typed from the keyboard and evaluates it. As the input
provided is evaluated, it expects valid python expression. If the input provided is not correct
then either syntax error or exception is raised by python.
Example:
34.78
2) raw_input()
Syntax:
raw_input (expression)
If prompt is present, it is displayed on the monitor after which user can provide the data from
keyboard. The function takes exactly what is typed from keyboard, convert it to string and
then return it to the variable on LHS of '='.
13
Enter your name: ABC
x is a variable which will get the string (ABC), typed by user during the execution of
program. Typing of data for the raw_input function is terminated by enter key.
We can use raw_input() to enter numeric data also. In that case we typecast, i.e., change the
data type using function, the string data accepted from user to appropriate Numeric type.
Example:
It will convert the accepted string i.e., 5 to integer before assigning it to 'y'.
Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
14
Comments:
# is used for single line comment in Python
""" this is a comment """ is used for multi line comments
Output:
My name is Joy Omoha
15
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:
Hello
5.5
10
16
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
As we know, python uses indentation to identify a block. So the block under an if statement
will be identified as shown in the below example:
if condition:
statement1
statement2
i = 10
if (i > 15):
Output:
I am Not in if
17
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
#!/usr/bin/python
i = 20
if (i < 15):
print("i'm in if Block")
else:
18
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
This code uses a for loop to iterate over a list of strings, printing each item in the list on a
new line. The loop assigns each item to the variable I and continues until all items in
the list have been processed.
Python3
for i in l:
print(i)
19
Output :
geeks
for
geeks
This code uses a for loop to iterate over a dictionary and print each key-value pair on a new
line. The loop assigns each key to the variable i and uses string formatting to print the key
and its corresponding value.
Python3
print("Dictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
Output:
Dictionary Iteration
xyz 123
abc 345
20
Python For Loop in Python String
This code uses a for loop to iterate over a string and print each character on a new line. The
loop assigns each character to the variable i and continues until all characters in the string
have been processed.
Python3
print("String Iteration")
s = "Geeks"
for i in s:
print(i)
Output:
String Iteration
G
e
e
k
s
21
Python For Loop with a step size
This code uses a for loop in conjunction with the range() function to generate a sequence of
numbers starting from 0, up to (but not including) 10, and with a step size of 2. For each
number in the sequence, the loop prints its value using the print() function. The output will
show the numbers 0, 2, 4, 6, and 8.
Python3
print(i)
Output :
0
2
4
6
8
This code uses nested for loops to iterate over two ranges of numbers (1 to 3 inclusive) and
prints the value of i and j for each combination of the two loops. The inner loop is executed
for each value of i in the outer loop. The output of this code will print the numbers from 1 to
3 three times, as each value of i is combined with each value of j.
print(i, j)
Output :
11
12
13
22
21
22
23
31
32
33
Same as of other programming languages, python also uses conditional Statements like if-
else, break, continue etc. While writing program(s), we almost always need the ability to
check the condition and then change the course of program, the simplest way to do so is
using if statement.
Code:
if x > 0:
print "x is positive"
Here, the Boolean expression written after if is known as condition, and if Condition is
True, then the statement written after, is executed. Let's see the syntax of if statement.
Syntax - 1
if condition:
STATEMENTs- BLOCK 1
[ else: #Statement with in [ ] bracket are optional.
STATEMENTs- BLOCK 2]
Let us understand the syntax, in Syntax 1 - if the condition is True (i.e. satisfied), the
statement(s) written after if (i.e. STATEMENT-BLOCK 1) is executed, and otherwise
statement written after else (i.e. STATEMENT-BLOCK 2) is executed. Remember else
clause is optional. If provided, in any situation, one of the two blocks get executed not both.
Syntax - 2
if condition-1:
STATEMENTs- BLOCK 1
[elif condition-2: #Statement with in [ ] bracket are optional.
STATEMENTs- BLOCK 2
23
else: STATEMENTs- BLOCK N]
We can say that, "if" with "else" provides an alternative execution, as there are two
possibilities and the condition determines which one gets executed. If there are more than two
possibilities then we need to chain the if statement(s). This is done using the 2nd option of if
statement. Here, we have used "elif" clause instead of "else". "elif" combines if else- if else
statements to one if "elif" …else. You may consider "elif" to be an abbreviation of else if.
There is no limit to the number of "elif" clause used.
In the chained conditions, each condition is checked in order if previous is False then next is
checked, and so on. If one of them is True then corresponding block of statement(s) are
executed and the statement ends i.e., control moves out of "if statement". If none is true,
then else block gets executed if provided. If more than one condition is true, then only the
first true option block gets executed.
It is possible to have a condition within another condition. Such conditions are known as
Nested Condition.
Example:
x=5
y=10
if x==y:
print x, "and", y, "are equal"
else:
if x<y:
print x, "is less than", y
else:
print x, "is greater than", y
Output
5 is less than 10
break Statement
break can be used to unconditionally jump out of the loop. It terminates the execution of the
loop. breakcan 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.
Example:
24
if letter =='h':
break
print (letter)
Output
P
y
t
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.
Example:
Output
P
y
t
o
n
Loops are used to repeatedly execute the same code in a program. Python provides two
types of looping constructs:
1. while statement
2. for statement
1) while statement
25
while condition: # condition is Boolean expression returning True or False
STATEMENTs BLOCK 1
[else: # optional part of while
STATEMENTs BLOCK 2]
We can see that while looks like if statement. The statement begins with
keyword while followed by Boolean condition followed by colon (:). What follows next is
block of statement(s).
The statement(s) in BLOCK 1 keeps on executing till condition in while remains True; once
the condition becomes False and if the else clause is written in while, then else will get
executed.
i=1
while (i <=10):
print i,
i = i+1 #could be written as i+=1
Output
1 2 3 4 5 6 7 8 9 10
In the above example,The first statement initialized the variable (controlling loop) and
then while evaluates the condition, which is True sothe block of statements written next will
be executed.
Last statement in the block ensures that, with every execution of loop, loop control variable
moves near to the termination point. If this does not happen then the loop willkeep on
executing infinitely.
As soon as i becomes 11, condition in while will evaluate to False and this will terminate the
loop.
Note: As there is ',' after print i all the values will be printed in the same line.
2) for statement
26
We can see that while looks like if statement. The statement begins with
keyword while followed by Boolean condition followed by colon (:). What follows next is
block of statement(s).
The statement(s) in BLOCK 1 keeps on executing till condition in while remains True; once
the condition becomes False and if the else clause is written in while, then else will get
executed.
Output
1 2 3 4 5 6 7 8 9 10
The statement introduces a function range(), its syntax is: range(start, stop, [step]),
where [step] is optional
range() generates a list of values starting from start till stop-1. Step if given is added to the
value generated, to get next value in the list.
Let's move back to the for statement: i is the variable, which keeps on getting a value
generated by range() function, and the block of statement (s) are worked on for each value
of i. As the last value is assigned to i, the loop block is executed last time and control is
returned to next statement.
Now we can easily understand the result of for statement. range() generates a list from 1, 2,
3, 4, 5, ..., 10 as the step mentioned is 1, i keeps on getting a value at a time, which is then
printed on screen.
Note:Apart from range() i (loop control variable) can take values from string, list,
dictionary, etc.
Example:
Output
27
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Coming out of loop
By now, you must have realized that, Syntax of for statement is also same as if
statement or while statement.
28
Functions in Python
1. Modules
2. Built-In
3. User Defined
1) Modules
A module is a file containing Python definitions (i.e. functions) and statements. Standard
library of Python is extended as module(s) to a Programmer. Definitions from the module can
be used into code of Program. To use these modules in a program, programmer needs to
import the module. Once we import a module, we can reference (use) to any of its functions
or variables in our code. There are two ways to import a module in our program, they are:
import
from
Import: It is simplest and most common way to use modules in our code.
Syntax:
Example: Input any number and to find square and square root.
import math
x = int(input("Enter any number:"))
y = math.sqrt(x)
a = math.pow(x,2)
print("Square Root value=",y)
print("Square value=",a)
Output
29
sum = 0
i=0
if i % 2 == 0:
print(i)
sum+=i
i+=1
EX. 3 prime_sum = 0
if num > 1:
if (num % i) == 0:
break
else:
prime_sum += num
print(num)
30
if num > 1:
if (num % i) == 0:
break
else:
print(num)
From statement: It is used to get a specific function in the code instead of complete file. If
we know beforehand which function(s), we will be needing, then we may use 'from'. For
modules having large number of functions, it is recommended to use from instead of import.
Syntax:
Example: Input any number and to find square and square root.
31
Output
2) Built in Function
Built in functions are the function(s) that are built into Python and can be accessed by
Programmer. These are always available and for using them, we don't have to import any
module (file). Python has a small set of built-in functions as most of the functions have been
partitioned to modules. This was done to keep core language precise.
In Python, it is also possible for programmer to write their own function(s). These functions
can then be combined to form module which can be used in other programs by importing
them. To define a function, keyword 'def' is used. After the keyword, comes an identifier i.e.
name of the function, followed by parenthesized list of parameters and the colon which ends
up the line, followed by the block of statement(s) that are the part of function.
Syntax:
def NAME ([PARAMETER1, PARAMETER2, …..])
#Square brackets include optional part of statement
Example: To find simple interest using function.
def SI(P,R,T):
return((P*R*T)/100)
Output
>>>SI(1000,2,10)
200.0
Lists in python
32
List is a sequence data type. It is mutable as its values in the list can be modified. It is a
collection of ordered set of values enclosed in square brackets []. As it is arranged set of
values, we can use index in square brackets [] to identify a particular value belonging to it.
The set of values that make up a list are called its elements, and they can be of any type.
List is a container that holds a number of elements in a given order. For accessing an
element of the list, indexing is used.
variable_name [index]
It will provide the value at "index+1" in the list. Indices of the lists have to be an integer
value which can be either positive or negative. Positive value of index means counting
forward from beginning of the list and negative value means counting backward from end of
the list.
>>>List1 = [1, 2, 3, 4]
>>>List3 = [ ]
Example:
33
[1, 7, 3, 4]
Here, 2nd element of the list (accessed using index value 1) is given a new value, so instead
of 2 it will be 7.
Note: An index can have a negative value, in that case counting happens from the end of the
list.
Creating a list
Example:
List5=List1 [:]
Here List5 is created as a copy of List1.
>>>print List5
List6 = List1 [0:2]
>>>print List6
List comprehension
Example:
In mathematical terms, A can be defined as A = {i2for: i in (0.....9)}. So, we can say that list
comprehension is short-hand for creating list.
34
Using built-in object
Example:
>>>List = list ( )
>>>print List
[ ] # empty list
Or
Example:
>>>List = list("String")
>>>print List
['S', 't', 'r', 'i', 'n', 'g']
>>>List[0]
[6, 7, 8]
To access an element of list containing another list, we use pair of index. Also a sub-list of
list can be accessed using list slice.
As the 4th element of this List is another list. To access elements of/from this sub-list, we will
use...
35
6
List Slices
Slice operator works on list also. We know that a slice of a list is its sub-list. For creating a
list slice, we use [l:r] operator. This will inclusive for l th element but exclusive for rth element
(including the first element but excluding the last element). So the resultant list will have m-n
elements in it.
>>>List1=[1,2,3,4,5]
will give
[2]
Slices are treated as boundaries, and the result will contain all the elements between
boundaries.
Where start, stop & step- all three are optional. If you omit first index, slice starts from "0"
and omitting of stop will take it to end. Default value of step is 1.
Example
>>>L2 [0:2]
["Gwalior", "Bhopal"]
Example
36
[11, 12, 13]
>>>list [:]
[11, 12, 13, 14, 15, 16]
>>>list [-1] # "-1" refers to last elements of list
16
2) Traversing a List
Let us visit each element (traverse the list) of the list to display them on screen. This can be
done in many ways:
>>>List=[2,4,6,8,10]
i) for i in List
print i
ii) i= 0
L = len (List)
while i < L :
i+=1
Using 2nd way for transversal, we are only able to access the list, but other ways can
alsobe used to update or write the element to the list.
Appending a listmeans adding more elements at the end of the list. To add new elements at
the end of the list, Python provides:
i) append ( )
37
Its Syntax is:
List.append (item)
Example:
>>>List=[1,2,3,4]
>>>List.append(5) # this will add 5 to the list at the end
>>>print List
>>>print len(List) # print length of the list List
[1, 2, 3, 4, 5]
5
38