Introduction to Python
Programming
Part 2
Shrihari A
IIT Guwahati
Daksh Gurukul, IIT Guwahati 1
Agenda
• Basic Syntax
o Identifiers and Keywords
o Lines and Indentation
o Multi-line comments
o Command-line arguments
• Basic Operators
o Arithmetic
o Comparison
o Logical and Bitwise
• Decision Making
o If statement
o Single Statement Suites
• Loops
o While loop
o For loop
o Using else statement in loops
o Nested loops
Daksh Gurukul, IIT Guwahati 2
Why Python for Beginners?
• Easy - to - learn
• Code is 3-5 times shorter than Java
• 5-10 times shorter than C++
• Stepping Stone to Programming universe
• Python's methodologies can be used in a
broad range of applications
• Bridging the Gap between abstract computing
and real world applications
• Python is used as main programming
language to do projects using Raspberry Pi
• Rising Demand for Python Programmers
• Google, Nokia, Disney, Yahoo, IBM use
Python
• Open- Source, Object - Oriented, procedural and
functional
• Not only a Scripting language, also supports
Web Development and Database
Connectivity
Daksh Gurukul, IIT Guwahati 3
Daksh Gurukul, IIT Guwahati 4
Print Statement
• Displays the output on the screen of user
• Python has its own String Format Operator as%
print('The value of Pl is %5.3f' % 3.1417)
print('The value of Pl is approximately %5.2f.' % 3.1417)
print( "Latest Python Version is: %d" % 3.5)
print ("%20s : %d" % ('Python', 3000.34 ))
Output:
The value of Pl is 3.142
The value of Pl is approximately 3.14.
Latest Python Version is: 3
Python : 3000
User Input in Python
name = input("Enter your name")
print("Welcome to session on Programming in Python,", name)
Guided Activity 1: Using Jupyter Notebook to create and execute Python Program
Daksh Gurukul, IIT Guwahati 5
Programming Constructs in Python
• Given a real world problem, to solve the problem using a program, we need:
- Logic
- High level programming language
• Programming Fundamentals
- Identifiers
- Variables
- Data types
- Operators etc
Daksh Gurukul, IIT Guwahati 6
Basic Syntax – Identifiers and Keywords
• Python Identifier
• To identify a variable, function,
class, module, or other object.
• Starts with a letter A to Z or a to z,
or an underscore (_) followed by
zero or more letters, underscores
and digits (0 to 9).
• Python Keywords
• Reserved words and you cannot use
them as constant or variable or any
other identifier names.
• All the Python keywords contain
lowercase letters only.
Daksh Gurukul, IIT Guwahati 7
Variables
• An identifier for the data and it holds data in your program
• Is a location (or set of locations) in memory where a value can be stored
• A quantity that can change during program execution
• No declaration of variables
• Data type of a variable can change during program execution compared to
other strongly typed languages such as Java, C++, C
customer id = 101 # Integer
customer name = "John" # String
bill amount = 675.45 # Floating-point
X = 5.3 + 0.9j # complex number
print(customer_id, customer_name, bill_amount) #prints 101 John 675.45
print(x.real) #prints 5.3
print(x.imag + 3) #prints 3.9
Daksh Gurukul, IIT Guwahati 8
Basic Syntax – Lines and Indentation I 1s
Types of Comments:
• A single line comment starts with
hash symbol '#' and end as the
line ends.
- These lines are never executed and
are ignored by the interpreter.
• Single # This is a single line
comment
""" • Multi-line comments starts and
Contents here can be used ends with triple single quotes "'
for documentation or triple """ double quotes
"""
"' - Used for documentation
An example for multi-line • Triple "' or"""
comments with single quotes
"'
Daksh Gurukul, IIT Guwahati 9
Operators (1 of 7)
• Used to perform specific operations on one or more operands (or variables) and
provide a result
Daksh Gurukul, IIT Guwahati 10
Operators (2 of 7)
• Arithmetic Operators
- Used for performing arithmetic operations
Operators Description
Example
+ Additive operator (also used for String concatenation) 2+3=5
- Subtraction operator 5-3=2
* Multiplication operator 5*3=15
I Division operator 6I2 = 3
% Modulus operator 7%2=1
II Truncation division (also known as floor division) 10113=3
10.0 II 3 = 3.0
** Exponentiation 10 ** 1000
Daksh Gurukul, IIT Guwahati 11
Operators (3 of 7)
• Relational Operators
- Also known as Comparison operators
- Used in conditional statements to compare values and take action depending on the
result
Operators Description
-- Equal to
< Less than
> Greater than
<= Lesser than or equal to
>= Greater than or equal to
I= Not equal to
<> Similar to Not equal to
Daksh Gurukul, IIT Guwahati 12
Operators (4 of 7)
• Assignment Operators
Operators Description Example Equivalent
= Assignment from right side operand to left side C = 50· C = a·
' '
+= Add & assigns result to left operand C += a c=c+a
-- Subtract & assigns result to left operand C -= a c=c-a
*- Multiply & assigns result to left operand C *= a C =C*a
I= Divide & assigns result to left operand CI= a c =cI a
Oof-c- Calculates remainder & assigns result to left C %= a C =C%a
operand
II= Performs floor division & assigns result to left c II= a c = c II a
operand
**- Performs exponential calculation & assigns C **= a C = C ** a
result to left operand
• Multiple Assignments - Same value can be assigned to more than one variable
Ex.1: Students Ram, Sham, John belong to semester 6 Ex.2: a, b, c = 10, 20, 30 is same
Ram = Sham = John = 6 as a = 10, b = 20, c = 30
Daksh Gurukul, IIT Guwahati 13
Operators (5 of 7)
• Bitwise Operators
- performs bit by bit operation on bits
Operators Description
& Binary AND
I Binary OR
I\
Binary XOR
~ Binary Ones Complement
<< Binary Left Shift
>> Binary Right Shift
Daksh Gurukul, IIT Guwahati 14
Operators (6 of 7)
• Logical Operators
- Are based on Boolean Algebra
- Returns result as either True or False
Operator Meaning
and Short Circuit-AND
or Short Circuit-OR
not Unary NOT
Guided Activity 2: Programming constructs in Python
Daksh Gurukul, IIT Guwahati 15
Operators (7 of 7)
• Membership Operators
- Checks for membership in a sequence of Strings, Lists, Dictionaries or Tuples
Operators Description
In Returns to true if it finds a variable in given sequence else false
Returns to true if it does not find a variable in given sequence
not in
else false
• Identity Operators
- Are used to compare memory locations of 2 objects
Operators Description
Returns to true if variables on either side of operator are
IS
referring to same object else false
Returns to false if variables on either side of operator are
is not
referring to same object else true
Daksh Gurukul, IIT Guwahati 16
Built-in function: id()
• Id(object)
- Returns identity of an object. It is the address of object in memory
- It will be unique and constant throughout the lifetime of an object
Example: Output
a= 10 Value of a and b before increment
b=a id of a: 1815592664
print("Value of a and b before increment")
id of b: 1815592664
print("id of a: ",id(a))
Value of a and b after increment
print("id of b: ",id(b)) id of a: 1815592664
b=a+l id of b: 1815592680
print("Value of a and b after increment")
print("id of a: ",id(a)) Note the change in
address of variable 'b'
print("id of b: ",id(b)) after increment
Daksh Gurukul, IIT Guwahati 17
Built-in function: type()
• Used to identify the type of object
Example:
int a= 10
print("Type of 'int_a':", type(int_a))
str b = "Hello"
Output:
print("Type of 'str_b':", type(str_b))
Type of 'int_a': <class 'int'>
Type of 'str_b': <class 'str'>
list_c = []
Type of 'list_c': <class 'list'>
print("Type of 'list_c':", type(list_c))
Note: Every variable in Python is a object
Guided Activity 3: id() and type{) functions - Quiz
Daksh Gurukul, IIT Guwahati 18
Coding Standards in Python
Bad Code Good Code
a= 10 marks1 = 10
b = 23 marks2 = 23
C = 24 marks3 = 24
I Usage of keyword sum of m a r k s = 10 + 23 + 24
'sum' as variable
a v g = n/3 name will lead to avg_of_marks = sum_of_marks / 3
warning
print("Average: ", avg) print ("Average: ", avg_of_marks)
Guided Activity 4: Coding Standards
Daksh Gurukul, IIT Guwahati 19
Control Structures
Guided Activity 5: Control Structures
• Decision making statements
- if statement:
• if statement checks for a condition and if that is found true a particular set of
instructions gets executed
Syntax:
Example:
x=8
if condition1:
if X < 10: statement( s)
print("Value of x is %d" %x) else:
v a r = 10 statement( s)
if v a r > 5:
print ("Hi") # line belongs to if block
print("l'm out of if")
Output:
Value of x is 8
Hi
I'm out of if
Daksh Gurukul, IIT Guwahati 20
Control Structures ...
• elif statement:
- elif statement is used when there is more than Syntax:
one condition to be checked separately if condition1:
Example: statement( s)
elif condition2:
var=10 statement( s)
if var> 10 :
print("Hello")
else:
print(var) statement( s)
elif var < 10:
Output:
print("Hola in Spanish for Hello")
print(var) Hi
else: 10
print("Hi") End of Program
print(var)
print("End of Program") Note: There is no switch case statement
in Python unlike CIC++ language
Daksh Gurukul, IIT Guwahati 21
Iterative Statements
• Loop statements:
- Allows us to execute a statement or group of statements multiple times.
• While Loop
• For Loop
• Range
• Loop Control Statements:
- Are used to change flow of execution from its normal sequence.
• Break
• Continue
• Pass
Daksh Gurukul, IIT Guwahati 22
Iterative Statements
- while loop:
• Repeats a statement or group of statements while a given condition is TRUE.
• Tests the condition before executing the loop body.
Syntax:
while condition:
Example: statement( s)
var=5
while var>O: Output:
print ("I'm in iteration",var) I'm in iteration 5
var-=1 I'm still in while
if var==2: I'm in iteration 4
break I'm still in while
print ("I'm still in while") I'm in iteration 3
print ("I'm out of while loop") I'm out of while loop
Daksh Gurukul, IIT Guwahati 23
Iterative Statements
- for loop:
• Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
Syntax:
for iterating_var in sequence:
statement(s)
Output:
1
Example: 2
Sita
for counter in 1,2,'Sita', 7,'Ram',5: 7
print(counter) Ram
5
Daksh Gurukul, IIT Guwahati 24
Iterative Statements
- range function in loops
• Used in case the need is to iterate over a specific number of times within a given range in
steps/intervals mentioned
Syntax: I range(lower limit, upper limit, Increment/decrement by)
Loop Output Remarks
for value in range(1,6): print(value) 12345 Prints all the values in given
range exclusive of upper limit
for value in range(0,6,2): print(value) 024 Prints values in given range in
increments of 2
for value in range(6,1,-2): print(value) 642 Prints values in given range in
decrements of 2
for ch in "Hello World": print(ch.upper()) HELLO Prints all the characters in the
W O R LO string converting them to upper
case
Guided Activity 6: Iterative Statements
Daksh Gurukul, IIT Guwahati 25
Iterative Statements-
- Loop Control Statements - break and continue
break
• When an external condition is triggered, Exits a loop immediately.
• Break Statement:
- Terminates the loop statement and transfers execution to the statement immediately
following the loop.
Example:
var =3
while var> 0: Output:
print ("I'm in iteration ",var) I'm in iteration 3
var-= 1 I'm out of while loop
if var ==2:
break
print ("I'm still in while")
print ("I'm out of while loop")
Daksh Gurukul, IIT Guwahati 26
Iterative Statements- continue
- continue statement:
• Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
Example:
var= 3
while var > 0: Output:
print ("I'm in iteration ", var)
I'm in iteration 3
var-= 1
I'm in iteration 2
if var ==2:
I'm still in while
continue
I'm in iteration 1
print ("I'm still in if block")
I'm still in while
print ("I'm still in while")
print ("I'm out of while loop") I'm out of while loop
Daksh Gurukul, IIT Guwahati 27
Iterative Statements- pass
• pass statement:
- pass statement is never executed.
- Used when a statement is required syntactically but do not want any command
or code to execute or if the code need to be implemented in future.
- Behaves like a placeholder for future code
Example:
X = "Joy"
if x == "John": Output:
print ("Name:",x)
elif x == "Joy": INo Output
pass
else:
print ("in else")
Daksh Gurukul, IIT Guwahati 28