Module 1
Module 1
Introduction to Python
Python is a general-purpose high-level programming language, interpreted, interactive
and object- oriented scripting language.
The Python programming language has a wide range of syntactical constructions,
standard library functions, and interactive development environment features.
It was developed by Guido van Rossum during 1989 at the National Research
Institute for Mathematics and Computer Science in the Netherlands.
Python source code is also available under the GNU General Public License (GPL).
Python is designed to be highly readable. It uses English keywords frequently where
as other languages use punctuation, and it has fewer syntactical constructions than
other languages.
Features/Applications of Python
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − we can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
Characteristics of Python
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building
large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
History of Python
Python laid its foundation in the late 1980s.
The implementation of Python was started in the December 1989 by Guido Van
Rossum at the National Research Institute for Mathematics and Computer Science in
the Netherlands . This release included exception handling, functions, and the core
data types of list, dict, str and others. It was also object oriented and had a module
system.
In February 1991, van Rossum published the code (labeled version 0.9.0) to
[Link].
In 1994, Python 1.0 was released with new features like: lambda, map, filter, and
reduce.
Six and a half years later in October 2000, Python 2.0 was introduced. This release
included list comprehensions, a full garbage collector and it was supporting unicode.
On December 3, 2008, Python 3.0 (also known as "Python 3000" and "Py3K") was
released. It was designed to rectify fundamental flaw of the language. Python 3 is not
backwards compatible with Python 2.x.
ABC programming language is said to be the predecessor of Python language which
was capable of Exception Handling and interfacing with Amoeba Operating System.
Python is influenced by following programming languages:
-ABC language.
-Modula-3
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.
Applications of Python
Python is an example of a high-level language; other high-level languages are C++, PHP,
Pascal, C#, and Java.
The engine that translates and runs Python is called the Python Interpreter: There are two
ways to use it: immediate mode and script mode. In immediate mode, we type Python
expressions into the Python Interpreter window, and the interpreter immediately shows the
result:
Interactive shell in python can be launched using Python IDLE, which will be
installed with Python
On Windows, open the Start menu, select All Programs à Python 3.3, and then select
IDLE (Python GUI). A window with the >>> prompt should appear; that’s the
interactive shell.
On OS X, select Applications ▸ MacPython 3.3 à IDLE. On Ubuntu, open a new
Terminal window and enter idle3.
To find sum of 2 numbers example, enter 2 + 2 at the prompt to have Python do some
simple math.
>>> 2 + 2 à will give 4 as an answer
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 anywhere 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 results in 2
Alternatively, we can write a program in a file and use the interpreter to execute the contents
of the file. Such a file is called a script. Scripts have the advantage that they can be saved to
disk, printed, and so on.
Working directly in the interpreter is convenient for testing short bits of code because
we get immediate feedback. When we are writing a script we need a text editor. A few
examples of text editors are Notepad, Notepad++, vim, emacs and sublime.
What is a Program?
Semantic Errors
A semantic error occurs when your program runs without crashing but produces the
wrong result. The syntax is correct, and Python can execute it, but the meaning of the code —
its semantics — doesn’t match what you intended. These are the hardest errors to find
Dept. of CSE (Data Science) 6
Python Programming [1BPLC105B] Module 1
because the program appears to work. For example, if you mistakenly write a formula that
calculates the area of a triangle incorrectly, Python will not complain, but the answer will be
wrong.
Experimental Debugging
If we are not sure what class a value falls into, Python has a function called type which can
tell us. Python provides a built-in function type() to check the data type of any value.
>>> type("Hello, World!")
<class 'str'>
>>> type(17)
<class 'int'>
>>> type(3.2)
<class 'float'>
strings belong to the class str and integers belong to the class int. numbers with a decimal
point belong to a class called float, because these numbers are represented in a format called
floating-point.
>>> type("17")
<class 'str'>
>>> type("3.2")
<class 'str'>
Strings are textual, while numbers are quantitative."123" (a string) is not the same as 123
(an integer). We can’t perform arithmetic on a string unless you first convert it into a number
using int() or float().
Strings in Python can be enclosed in either single quotes (') or double quotes ("), or three of
each (' ' ' or """).
>>> type('This is a string.')
<class 'str'>
>>> type("And so is this.")
<class 'str'>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str'>
>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
"Oh no", she exclaimed, "Ben's bike is broken!"
Triple quoted strings can even span multiple lines:
>>> message = """This message will
... span several
... lines."""
>>> print(message) This message will span several lines.
>>>
When we type a large integer, we might to use commas between groups of three
digits, as in 42,000. The same goes for entering Dutch-style floating point numbers using a
comma instead of a decimal dot. This is not a legal integer in Python, but it does mean
something else, which is legal: Because of the comma, Python chose to treat this as a pair of
values.
>>> 42000
42000
>>> 42,000
(42, 0)
Variables
A variable is a name that refers to a value. A variable is the name of computer’s memory
location where single value can be stored. Values are stored in a variable using Assignment
Statement. A good variable name describes the data it contains.
Assignment statement consists of name of the variable, assignment operator (=) and a
value.
>>> a = 7.7
>>> a #outputs 7.7
>>> b = 3.3
>>> a+b #outputs 11.0
A variable is initialized (or created) the first time a value is stored in it (spam = 'Hello'). After
that, variable can be used in expressions with other variables and values (s=spam). When a
variable is assigned a new value, the old value is forgotten. (spam = 'Goodbye‘).
Rules for Variable names
Variable names are case sensitive.
It has to be only one word
It should contain only letters, numbers, under score character.
It can’t begin with a number.
Valid Variables:
o balance, curBal, acc4
Invalid Variables
o cur-bal (hyphan not allowed)
o cur bal (spaces are not allowed)
o 4acc (Can’t begin with a number)
o tot_$um ( Special characters are not allowed)
Keywords define the language’s syntax rules and structure, and they cannot be used as
variable names. Python has thirty-something keywords.
Statements
A statement is an instruction that the Python interpreter can execute. Each line of code in
Python is usually a statement.
Example:
x=5
print(x)
The first line (x = 5) is an assignment statement. The second line (print(x)) is a print
statement that produces output. Python executes statements one after another, in sequential
order (top to bottom), unless told otherwise by loops or conditionals.
Evaluating Expressions
An expression is a combination of values, variables, operators, and calls to functions. If you
type an expression at the Python prompt, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
>>> len("hello")
5
In this example, len is a built-in Python function that returns the number of characters in a
string. The evaluation of an expression produces a value, which is why expressions can
appear on the right-hand side of assignment statements. A value all by itself is a simple
expression, and so is a variable.
>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14
The type converter float can turn an integer, a float, or a syntactically legal string into a float:
>>> float(17)
17.0
>>> float("123.45")
123.45
Order of Operations
Dept. of CSE (Data Science) 13
Python Programming [1BPLC105B] Module 1
When more than one operator appears in an expression, the order of evaluation depends on
the rules of precedence. Python follows the same precedence rules for its mathematical
operators that mathematics does. The acronym PEM- DAS is a useful way to remember the
order of operations:
Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)
is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read,
as in (minute * 100) / 60, even though it doesn’t change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and
3*1**3 is 3 and not 27.
Multiplication and both Division operators have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5
rather than 4, and 5-2*2 is 1, not 6.
Operators with the same precedence are evaluated from left-to-right. In algebra we
say they are left-associative. So in the expression 6-3+2, the subtraction happens first,
yielding 3. We then add 2 to get the result 5. If the operations had been evaluated from right
to left, the result would have been 6-(3+2), which is 1.
** Exponent 2 ** 3 8
/ Division 22 // 8 2.75
* Multiplication 3*5 15
- Subtraction 5–2 3
+ Addition 2+2 4
Evaluate
>>> 2 + 5 * 6 #32
>>> 29 // 6 #4
>>> (6 -1) * ((7+2)/(3-1)) #22.5
Evaluating expression
Operations on strings:
String Concatenation (+)
>>> ‘Hello! #Syntax error : EOL while scanning string literal (closing Single
#quote is missing)
If + operator is used between string and integer, an error message will be displayed
>>>’Alice’ + 5 #TypeError : Can’t convert ‘int’ object to str implicitly
Input
There is a built-in function in Python for getting input from the user:
name = input("Please enter your name: ")
The user of the program can enter the name and click OK, and when this happens the text that
has been entered is returned from the input function, and in this case assigned to the variable
name.
Even if you asked the user to enter their age, you would get back a string like "17". It would
be your job, as the programmer, to convert that string into a int or a float, using the int or float
converter functions.
Program to calculate area of a circle.
response = input("What is your radius? ")
r = float(response)
area = 3.14159 * r**2
print("The area is ", area)
The modulus operator works on integers (and integer expressions) and gives the
remainder when the first number is divided by the second. In Python, the modulus operator is
a percent sign (%). The syntax is the same as for other operators. It has the same precedence
as the multiplication operator. So 7 divided by 3 is 2 with a remainder of 1.
>>> q = 7 // 3
>>> print(q)
2
>>> r = 7 % 3
>>> print(r)
1
let’s write a program to ask the user to enter some seconds, and we’ll convert them into
hours, minutes, and remaining seconds.
total_secs = int(input("How many seconds, in total?"))
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
Flow Control
Flow control statements can decide which Python instructions to execute under which
conditions. Flow control statements directly correspond to the symbols in a flowchart
Boolean Values
Boolean data type has only 2 values: True and False. (True and False are keywords).
(Boolean is capitalized because the data type is named after mathematician George Boole.)
>>> spam = True
>>> spam #True
>>> true #NameError: name 'true' is not defined
>>> True #True
>>> True+2 #3
>>> True=2+2 #SyntaxError: can't assign to keyword
Boolean values are used in expressions and can be stored in variables. If you don’t use the
proper case or you try to use True and False for variable names, Python will give you an error
message.
Comparison Operators
Comparison operators compare two values and evaluate down to a single Boolean value.
Operator Meaning
== Equal to
!= Not Equal to
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
== (equal to) evaluates to True when the values on both sides are the same, and != (not equal
to) evaluates to True when the two values are different.
>>> '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
Dept. of CSE (Data Science) 17
Python Programming [1BPLC105B] Module 1
Boolean Operators
== vs =
The == operator (equal to / Comparison) asks whether two values are the same as
each other.
The = operator (assignment) puts the value on the right into the variable on the left.
The three Boolean operators (and, or, and not) are used to compare Boolean values.
Boolean operators evaluate the expressions down to a Boolean value.
Expression Evaluates to ….
Expression Evaluates to ….
if Statement
An if statement’s clause (the block following the if statement) will execute if the statement’s
condition is True. The clause is skipped if the condition is False. 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:
o The if keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the if clause)
Syntax
if <condition>:
statements
Ex:-
if name == ‘Alice’:
print(‘Hi Alice’)
if-else Statements
An if clause can optionally be followed by an else Statement. The else clause is executed only
when the if statements condition is False. 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:
o The else keyword
o A colon
o Starting on the next line, an indented block of code (called the else clause)
Syntax:
if <condition>:
statements
else:
statements
Example:
if name == ‘Alice’:
print(‘Hi Alice’)
else:
print(‘Hello Stranger’)
Flow chart
elif Statements
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:
o The elif keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the elif clause)
Example 1:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
Example 2:
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:
The terminating condition is that there are no more elements in the sequence to assign
to the loop variable. The loop changes the usual “top-to-bottom, one statement at a time” flow
(control flow) by jumping back to the loop header after each iteration until termination.
Conceptually, Python keeps a “pointer” to which statement is coming up next (control
flow), and the loop redirects that flow repeatedly within its body until exhaustion of items.
Execution Flow
1. Evaluate the condition.
2. If True, execute the loop body.
3. Re-evaluate the condition.
4. Repeat until the condition becomes False.
5. Then continue with the next statement after the loop.
Example
count = 0
while count < 5:
print("Count is", count) count += 1
print("Done!")
Dept. of CSE (Data Science) 24
Python Programming [1BPLC105B] Module 1
Output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4 Done!
The Collatz 3n + 1 Sequence Definition
The Collatz sequence (or 3n + 1 problem) is a famous unsolved problem in mathematics.
Algorithm (steps)
1. Start with any positive integer n.
2. If n is even → divide by 2
3. If n is odd → multiply by 3 and add 1
4. Repeat until n becomes 1.
Example
n = int(input("Enter a number: "))
while n != 1:
print(n, end=" ")
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1 print(n)
Tables
A table is a systematic way to display values — usually two columns:
• one for input
• one for output (f of x)
Tables help visualize relationships between variables.
Example – Square Table
for x in range(1, 6):
print(x, x**2)
Dept. of CSE (Data Science) 25
Python Programming [1BPLC105B] Module 1
Output:
11
24
39
4 16
52
Two-Dimensional Tables
When data depend on two variables (e.g., multiplication table), use nested loops.
Example – Multiplication Table
for row in range(1, 6):
for col in range(1, 6):
print(row * col, end="\t")
print()
Output:
12345
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Syntax Example
while True:
n = int(input("Enter a positive number: "))
if n < 0:
break
print("You entered:", n)
print("Loop terminated.")
Example
for n in range(1, 10):
if n % 2 == 0:
continue
print(n)
Paired Data
Paired data are two lists that contain related information — e.g., student names and marks.
Example
When data contain lists within lists (e.g., matrix), use nested loops.
Example – Matrix Traversal
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()
Output:
123
456
789
Examp1e 2:
students = [
("John", ["CompSci", "Physics"]),
("Vusi", ["Maths", "CompSci", "Stats"]),
("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),
("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])]
output:
John takes 2 courses
Vusi takes 3 courses
Jess takes 4 courses
Sarah takes 4 courses
Zuki takes 5 courses
Example 3:
counter = 0
for name, subjects in students:
for s in subjects: # A nested loop!
if s == "CompSci":
counter += 1
print("The number of students taking CompSci is", counter)
The range() function can also be called with three arguments. The first two arguments
will be the start and stop values, and the third will be the step argument. The step is the
amount that the variable is increased by after each iteration.
for i in range(0, 10, 2): #Begin: 0 End: 10 (Exclude) interval: 2
print(i) #prints 0 2 4 6 8
The range() function is flexible in the sequence of numbers it produces for for loops.
for i in range(5, -1, -1):
print(i) #5 4 3 2 1 0
The middle-test loop with the exit test is in the middle of the body, rather than at the
beginning or at the end.
total = 0
while True:
response = input("Enter the next number.
(Leave blank to end)")
if response == "" or response == "-1":
break
total += int(response)
print("The total of the numbers you entered is ",
total)
Functions
In Python, a function is a named sequence of statements that belong together. Their primary
purpose is to help us organize programs into chunks that match how we think about the
problem.
The syntax for a function definition is:
<STATEMENTS>
Calling a function
• It can be called by name of the function and passing arguments.
• Ex:- printme(‘Vemana Institute of Technology’)
Example :
def hello(name):
print('Hello ' + name)
hello('Alice') #Hello Alice
hello('Bob') # Hello Bob
In Python there is a value called None, which represents the absence of a value.
None is the only value of the NoneType data type. (Other programming languages
might call this value null, nil, or undefined.)
None must be typed with a capital N.
To know the return value of None
>>> spam = print('Hello!') #Hello!, here spam doesnot have value
>>> None == spam #True
>>> type(spam) #<class 'NoneType'>
Parameters and Arguments
• The information into the functions can be passed as the parameters. The parameters
are specified in the parentheses. We can give any number of parameters, but we have to
separate them with a comma.
Example 1
#defining the function
def func (name):
print("Hai ",name); #print(‘Hai’+name)
#calling the function
func("Manu")
Syntax:
return [expression]
Parameters: return ends the function, [expression] is the optional value to return (defaults to
None).
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10
Example 1:
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Example 2:
def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"
print(evenOdd(16))
print(evenOdd(7))