PYTHON PROGRAMMING:
MODULE 1 – INTRODUCTION TO
PYTHON – VARIABLES AND
OPERATORS
Prof J. Noorul Ameen M.E,(Ph.D), EMCAA, MISTE, D.Acu.,
Assistant Professor/CSE
Member – Centre for Technology & Capability Development
E.G.S Pillay Engineering College, Nagapattinam
9150132532
[email protected]
Profameencse.weebly.com Noornilo Nafees 1
MODULE 1 – INTRODUCTION TO PYTHON –
VARIABLES AND OPERATORS
At the end of this course students can able to
Appreciate the use of Graphical User Interface (GUI)
and Integrated Development
Environment (IDE) for creating Python programs.
Work in Interactive & Script mode for programming.
Create and assign values to variables.
Understand the concept and usage of different data
types in Python.
Appreciate the importance and usage of different
types of operators
Creating Python expression(s) and statement(s).
Noornilo Nafees 2
INTRODUCTION TO PYTHON
Python is a general purpose programming language
created by Guido Van Rossum from CWI (Centrum
Wiskunde & Informatica) which is a National
Research Institute for Mathematics and Computer
Science in Netherlands.
The language was released in I991.
Python supports both Procedural and Object
Oriented programming approaches.
Noornilo Nafees 3
Key features of Python:
It is a general purpose programming language which
can be used for both scientific and non-scientific
programming.
It is a platform independent programming language.
The programs written in Python are easily readable
and understandable.
The version 3.x of Python IDLE (Integrated
Development Learning Environment) is used to
develop and run Python code. It can be downloaded
from the web resource www.python.org.
Noornilo Nafees 4
Different ways of developing and executing python
programs:
Invoking Python Interpreter and using text editor.
Using an IDE (Pycharm)
Using web based IDE such as Jupyter notebook,
onlinegdb…
Noornilo Nafees 5
Programming in Python:
In Python, programs can be written in two ways
namely Interactive mode and Script mode.
The Interactive mode allows us to write codes in
Python command prompt (>>>), whereas in script
mode programs can be written and stored as separate
file with the extension .py and executed.
Script mode is used to create and edit python source
file.
Noornilo Nafees 6
Interactive mode Programming
In interactive mode Python code can be directly typed
and the interpreter displays the result(s) immediately.
The interactive mode can also be used as a simple
calculator.
(i) Invoking Python IDLE
The following command can be used to invoke Python
IDLE from Window OS.
Start → All Programs → Python 3.x → IDLE (Python
3.x) or Click python Icon on the Desktop if available.
Noornilo Nafees 7
Python IDLE :
Noornilo Nafees 8
The prompt (>>>) indicates that Interpreter is ready to
accept instructions.
Therefore, the prompt on screen means IDLE is
working in interactive mode.
Now let us try as a simple calculator by using a simple
mathematical expressions.
Noornilo Nafees 9
Noornilo Nafees 10
Script mode Programming:
A script is a text file containing the Python statements.
Python Scripts are reusable code.
Once the script is created, it can be executed again and
again without retyping.
The Scripts are editable.
(i) Creating Scripts in Python:
Choose File → New File or press Ctrl + N in Python
shell window.
Noornilo Nafees 11
An untitled blank script text editor will be displayed
on screen.
Noornilo Nafees 12
Type the following code in Script editor
a =100
b = 350
c = a+b
print ("The Sum=", c)
Noornilo Nafees 13
Choose File → Save or Press Ctrl + S
Noornilo Nafees 14
Now, Save As dialog box appears on the screen
Noornilo Nafees 15
In the Save As dialog box, select the location where
you want to save your Python code, and type the file
name in File Name box.
Python files are by default saved with extension .py.
Thus, while creating Python scripts using Python Script
editor, no need to specify the file extension.
Finally, click Save button to save your Python script.
Noornilo Nafees 16
Executing Python Script
(1) Choose Run → Run Module or Press F5
(2) If your code has any error, it will be shown in red
color in the IDLE window, and Python describes the
type of error occurred.
To correct the errors, go back to Script editor, make
corrections, save the file using Ctrl + S or File → Save
and execute it again.
(3) For all error free code, the output will appear in the
IDLE window of Python
Noornilo Nafees 17
Declaring variables:
Ex1: a=10
b=5.5
c=“Nafees”
EX2: a,b,c=10,5.5,Nafees
Input and Output Functions:
A program needs to interact with the user to
accomplish the desired task; this can be achieved using
Input-Output functions.
The input() function helps to enter data at run time by
the user
The output function print() is used to display the
result of the program on the screen after execution.
Noornilo Nafees 18
The print() function:
In Python, the print() function is used to display result
on the screen.
The syntax for print() is as follows:
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3”
……)
Noornilo Nafees 19
Example:
>>> print (“Welcome to Python Programming”)
Welcome to Python Programming
>>> x = 5
>>> y = 6
>>> z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11
Noornilo Nafees 20
The print ( ) evaluates the expression before printing it on the
monitor.
The print() displays an entire statement which is specified within
print ( ).
Comma ( , ) is used as a separator in print ( ) to print more than
one item.
input() function:
In Python, input( ) function is used to accept data as input at run
time.
The syntax for input() function is,
Variable = input (“prompt string”)
Where, prompt string in the syntax is a statement or message to
the user, to know what input can be given.
The input( ) takes whatever is typed from the keyboard and stores
the entered data in the given variable.
If prompt string is not given in input( ) no message is displayed on
the screen, thus, the user will not know what is to be typed as
input. Noornilo Nafees 21
Example 1:input( ) with prompt string
>>> name=input (“Enter Your Name: ”)
Enter Your Name: Nilo
>>> print (“My name is “,name)
My name is Nilo
Example 2:input( ) without prompt string
>>> city=input()
Nagapattinam
>>> print (“I am from”, city)
I am from Nagapattinam
Noornilo Nafees 22
In Example-2, the input( ) is not having any prompt
string, thus the user will not know what is to be typed
as input.
If the user inputs irrelevant data as given in the above
example, then the output will be unexpected.
So, to make your program more interactive, provide
prompt string with input( ).
Noornilo Nafees 23
The input ( ) accepts all data as string or characters but
not as numbers.
If a numerical value is entered, the input values should
be explicitly converted into numeric data type.
The int( ) function is used to convert string data as
integer data explicitly.
Example 3:
x = int (input(“Enter Number 1: ”))
y = int (input(“Enter Number 2: ”))
print (“The sum = ”, x+y)
Output:
Enter Number 1: 34
Enter Number 2: 56
The sum = 90
Noornilo Nafees 24
Comments in Python:
In Python, comments begin with hash symbol (#).
The lines that begins with # are considered as
comments and ignored by the Python interpreter.
Comments may be single line or no multi-lines.
The multiline comments should be enclosed within a
set of ''' '''(triple quotes) as given below.
# It is Single line Comment
''' It is multiline comment
which contains more than one line '''
Noornilo Nafees 25
Indentation:
Python uses whitespace such as spaces and tabs to
define program blocks whereas other languages like C,
C++, java use curly braces { } to indicate blocks of codes
for class, functions or body of the loops and block of
selection command.
The number of whitespaces (spaces and tabs) in the
indentation is not fixed, but all statements within the
block must be indented with same amount spaces.
Noornilo Nafees 26
Tokens:
Python breaks each logical line into a sequence of
elementary lexical components known as Tokens.
The token types are:
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens,
identifiers or keywords.
Noornilo Nafees 27
(1)Identifiers:
An Identifier is a name used to identify a variable, function,
class, module or object.
An identifier must start with an alphabet (A..Z or a..z) or
underscore ( _ ).
Identifiers may contain digits (0 .. 9)
Python identifiers are case sensitive i.e. uppercase and
lowercase letters are distinct.
Identifiers must not be a python keyword.
Python does not allow punctuation character such as %,$,
@ etc., within identifiers.
Example of valid identifiers
Sum, total_marks, regno, num1
Example of invalid identifiers
12Name, name$, total-mark, continue
Noornilo Nafees 28
(2)Keywords: These are special words used by Python
interpreter to recognize the structure of program.
As these words have specific meaning for interpreter,
they cannot be used for any other purpose.
Table - Python’s Keywords:
Noornilo Nafees 29
(3)Operators:
In computer programming languages operators are
special symbols which represent computations,
conditional matching etc.
Operators are categorized as Arithmetic, Relational,
Logical, Assignment etc.
Value and variables when used with operator are
known as operands
Noornilo Nafees 30
(i) Arithmetic operators: Mathematical operator that
takes two operands and performs a calculation on
them.
Most computer languages contain a set of such
operators that can be used within equations to
perform different types of sequential calculations.
Noornilo Nafees 31
Python supports following arithmetic operators.
Noornilo Nafees 32
#Program to test Arithmetic Operators
a=100
b=10
print ("The Sum = ",a+b)
print ("The Difference = ",a-b)
print ("The Product = ",a*b)
print ("The Quotient = ",a/b)
print ("The Remainder = ",a%30)
print ("The Exponent = ",a**2)
print ("The Floor Division =",a//30)
Output:
The Sum = 110
The Difference = 90
The Product = 1000
The Quotient = 10.0
The Remainder = 10
The Exponent = 10000
The Floor Division = 3 Noornilo Nafees 33
(ii)Relational or Comparative operators: It is also
called as Comparative operator which checks the
relationship between two operands.
If the relation is true, it returns True; otherwise it
returns False.
Python supports following relational operators
Noornilo Nafees 34
#Program to test Relational Operators
a=int (input("Enter a Value for A:"))
b=int (input("Enter a Value for B:"))
print ("A = ",a," and B = ",b)
print ("The a==b = ",a==b)
print ("The a > b = ",a>b)
print ("The a < b = ",a<b)
print ("The a >= b = ",a>=b)
print ("The a <= b = ",a<=0)
print ("The a != b = ",a!=b)
Output:
Enter a Value for A:35
Enter a Value for B:56
A = 35 and B = 56
The a==b = False
The a > b = False
The a < b = True
The a >= b = False
The a <= b = False
The a != b = True Noornilo Nafees 35
(iii)Logical operators:
In python, Logical operators are used to perform
logical operations on the given relational expressions.
There are three logical operators they are and, or and
not.
Noornilo Nafees 36
#Program to test Logical Operators
a=int (input("Enter a Value for A:"))
b=int (input("Enter a Value for B:"))
print ("A = ",a, " and b = ",b)
print ("The a > b or a == b = ",a>b or a==b)
print ("The a > b and a == b = ",a>b and a==b)
print ("The not a > b = ",not a>b)
OUTPUT:
Enter a Value for A:50
Enter a Value for B:40
A = 50 and b = 40
The a > b or a == b = True
The a > b and a == b = False
The not a > b = False Noornilo Nafees 37
(iv) Assignment operators
In Python, = is a simple assignment operator to assign
values to variable.
Let a = 5 and b = 10 assigns the value 5 to a and 10 to b
these two assignment statement can also be given as
a,b=5,10 that assigns the value 5 and 10 on the right to
the variables a and b respectively.
Noornilo Nafees 38
(v) Conditional operator:
Ternary operator is also known as conditional operator
that evaluate something based on a condition being
true or false.
It simply allows testing a condition in a single line
replacing the multiline if-else making the code
compact.
The Syntax conditional operator is,
Variable Name = [on_true] if [Test expression] else
[on_false]
Example :
min= 50 if 49<50 else 70
min= 50 if 49>50 else 70
Noornilo Nafees 39
# Program to demonstrate conditional operator
a, b = 30, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print ("The Minimum of A and B is ",min)
Output:
The Minimum of A and B is 20
Noornilo Nafees 40
(4)Delimiters:
Python uses the symbols and symbol combinations as
delimiters in expressions, lists, dictionaries and strings.
Following are the delimiters:
Noornilo Nafees 41
(5)Literals:
Literal is a raw data given to a variable or constant.
In Python, there are various types of literals.
a) Numeric
b) String
c) Boolean
Noornilo Nafees 42
a) Numeric Literals:
Numeric Literals consists of digits and are immutable
(unchangeable).
Numeric literals can belong to 3 different numerical
types Integer, Float and Complex.
Noornilo Nafees 43
# Program to demonstrate Numeric Literals
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
print ("Integer Literals :",a,b,c,d)
#Float Literal
e = 10.5
f = 1.5e2
print ("Float Literals :",e,f)
#Complex Literal
x = 1 + 3.14j
print ("Complex Literals :", x)
print ("x = ", x , "Imaginary part of x = ", x.imag, "Real part of x = ", x.real)
Output:
Integer Literals : 10 100 200 300
Float Literals : 10.5 150.0
Complex Literals : (1+3.14j)
x = (1+3.14j) Imaginary part of x = 3.14 Real part of x = 1.0
Noornilo Nafees 44
(b) String Literals:
In Python a string literal is a sequence of characters
surrounded by quotes.
Python supports single, double and triple quotes for a
string.
A character literal is a single character surrounded by
single or double quotes.
The value with triple-quote "' '" is used to give
multiline string literal.
Noornilo Nafees 45
# Program to test String Literals
s1 = "This is Python"
c1 = "C"
multiline_str = "‘Welcome to the world of
Python programming."'
print (s1)
print (c1)
print (multiline_str)
Output:
This is Python
C
Welcome to the world of Python programming..
Noornilo Nafees 46
(C)Boolean Literals:
A Boolean literal can have any of the two values: True or
False.
# Program to test Boolean Literals
boolean_1 = True
boolean_2 = False
print ("Demo Program for Boolean Literals")
print ("Boolean Value1 :",boolean_1)
print ("Boolean Value2 :",boolean_2)
# End of the Program
Output:
Demo Program for Boolean Literals
Boolean Value1 : True
Boolean Value2 : False
Noornilo Nafees 47
(d)Escape Sequences:
In Python strings, the backslash "\" is a special
character, also called the "escape“ character.
It is used in representing certain whitespace
characters:
"\t" is a tab,
"\n" is a newline, and
For example to print the message "It's raining", the
Python command is
>>> print ("It\'s raining")
It's raining
Noornilo Nafees 48
Python supports the following escape sequence
characters.
Noornilo Nafees 49
Python Data types:
All data values in Python are objects and each object
or value has type.
Python has Built-in or Fundamental data types such as
(a)Number,
(b)String,
(c)Boolean,
(d)Tuples,
(e)Lists and
(f)Dictionaries.
Noornilo Nafees 50
(a)Number: The built-in number objects in Python
supports integers, floating point numbers and complex
numbers.
(i)Integer Data: It can be decimal, octal or
hexadecimal.
Octal integer use digit 0 (Zero) followed by letter 'o' to
denote octal digits and
Hexadecimal integer use 0X (Zero and either uppercase
or lowercase X) and
L (only upper case) to denote long integer.
Example :
102, 4567, 567 # Decimal integers
0o102, 0o876, 0o432 # Octal integers
0X102, 0X876, 0X432 # Hexadecimal integers
Noornilo Nafees 51
Floating point data: It is represented by a sequence of
decimal digits that includes a decimal point.
An Exponent data contains decimal digit part, decimal
point, exponent part followed by one or more digits.
Complex number is made up of two floating point
values, one each for the real and imaginary parts.
Example:
123.34, 456.23, 156.23 # Floating point data
12.E04, 24.e04 # Exponent data
1 + 3.14j # Complex number
Noornilo Nafees 52
(b)String: String data can be enclosed in single quotes
or double quotes or triple quotes.
Char_data = ‘A’
String_data= "Computer Science"
Multiline_data= ”””String data can be enclosed in
single quotes or double quotes or triple quotes.”””
(c)Boolean Data type: A Boolean data can have any of
the two values: True or False.
Example :
Bool_var1=True
Bool_var2=False
Noornilo Nafees 53
POINTS TO REMEMBER:
Python is a general purpose programming language created
by Guido Van Rossum.
Python shell can be used in two ways, viz., Interactive mode
and Script mode.
Python uses whitespace (spaces and tabs) to define program
blocks
Whitespace separation is necessary between tokens,
identifiers or keywords.
A Program needs to interact with end user to accomplish the
desired task, this is done using Input-Output facility.
Python breaks each logical line into a sequence of
elementary lexical components known as Tokens.
Keywords are special words that are used by Python
interpreter to recognize the structure of program.
Noornilo Nafees 54
Module 1 Quiz
1. Who developed Python ?
A) Ritche B) Guido Van Rossum
C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept
instruction.
A) >>> B) <<<
C) # D) <<
3. Which of the following shortcut is used to create new Python
Program ?
A) Ctrl + C B) Ctrl + F
C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in
Python Program ?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($)
C) comma(,) D) Colon(:)
Noornilo Nafees 55
6. Which of the following is not a token ?
A) Interpreter B) Identifiers
C) Keyword D) Operators
Which of the following is not a Keyword in Python ?
A) break B) while
C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational
C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or
C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational
C) Logical D) Assignment
Noornilo Nafees 56
Module 1 : Hands On:
1. Write a Python program to read two numbers and print the
sum and average of given two numbers.
2. Write a Python program to find area of circle
3. Write a Python program to evaluate the below expression by
assigning values at run time and increment the result by 1 and
check whether it is greater than 50.
a+(b*c)/2
4. Write a Python program to accept country and mother
tongue of a person. using logical operator and check the
following
◦ (i)The logic is true if the person's country is india and mother tongue is
tamil
◦ (ii) The logic is true if either the person's country is india or mother
tongue is tamil
5. Write a Python program to check and print whether the given
number is even or odd using conditional/ternary operator
Noornilo Nafees 57
Module 1 : Assignment
1. Write a Python program to print your bio data.
2. Write a Python to get integer and float values and print
the given values
3. Write a Python program to accept student roll no, marks
in 3 subjects and calculate total, average and print it.
4. Write a Python program to evaluate the below
expression by assigning values at run time.
a square + b square - 2ab
5. Write a Python program to check whether a person's
age is greater than 18 and have any id proof. if both
available then print you are eligible to get driving license
or print you are not eligible to get driving license
Noornilo Nafees 58