CT
CT
CT
1
Python Indentation
• Python programming provides no braces to indicate blocks of code for class
and function de nitions or ow control.
• Blocks of code are denoted by line indentation
• Indentation refers to the spaces at the beginning of a code line.
• In other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
if 5 > 2: if 5 > 2:
print("Five is greater than two!") print("Five is greater than two!")
2
fi
fl
Python Comments
#This is a comment.
print("Hello, World!")
3
Python Variables
x=5
x=5 y = "John"
y = "Hello, World!" print(x)
print(y)
4
Variable Names- Naming Convention
A variable can have a short name (like x or y) or a more descriptive name (age,
carname, total_volume).
5
VALID INVALID
myvar = "John"
my_var = "John" 2myvar = "John"
_my_var John my-var = "John"
myVar = "John" my var = "John"
MYVAR = "John"
myvar2 = "John"
6
Many Values to Multiple Variables
7
One Value to Multiple Variable
You can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
8
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to
extract the values into variables. This is called unpacking.
9
Output Variables
x = "Python is awesome"
print(x) Output: Python is awesome
x = "Python"
y = "is"
z = "awesome" Output: Python is awesome
print(x, y, z)
10
You can also use the + operator to output multiple variables:
x = “Python "
y = “is "
z = "awesome"
print(x+y+z)
Notice the space character after "Python " and "is ", without
them the result would be "Pythonisawesome".
11
For numbers, the + character works as a mathematical operator:
VALID INVALID
X =5 X=5
Y = 10 Y = “John”
print(X+Y) print(X + Y)
12
The best way to output multiple variables in the print() function is to
separate them with commas, which support different data types:
X=5
Y = “John”
print(X, Y)
13
Case-Sensitivity of Python Variables
Python variables are case sensitive which means Age and age are
two different variables:
age = 20
Age = 30
age = 20
Age = 30
14
Python Local Variables
15
Python Data Types
• Python data types are actually classes, and the de ned variables are their
instances or objects.
• Since Python is dynamically typed, the data type of a variable is determined at
runtime based on the assigned value.
• Variables can store data of different types, and different types can do different
things.
16
fi
Python Numeric Data Types
var1 = 1 — Int
var2 = True — Boolean
var3 = 10.023 — Float
var4 = 10+3j — Complex
17
Python String Data Type
18
str = “Hello World!”
Output
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
19
Type Casting
If you want to specify the data type of a variable, this can be done with casting.
You can get the data type of a variable with the type() function.
x=5 Output:
y = "John"
print(type(x)) Int
print(type(y)) Str
20
fl
Python Operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
21
Arithmetic Operators
22
Assignment Operators
23
Comparison Operators
24
Logical Operators
25
Bitwise Operators
26
Operator
Precedence
27
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))
28
Strings
Strings in python are surrounded by either single quotation marks,
or double quotation marks.
Example
print("Hello")
Output
print('Hello')
Hello
Hello
29
Quotes Inside Quotes
We can use quotes inside a string, as long as they don't match the quotes
surrounding the string
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Output
It's alright
He is called 'Johnny'
He is called “Johnny"
30
Assign String to a Variable
Example
a = "Hello"
print(a)
Output
Hello
31
Multiline Strings
We can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes
a = """Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string"""
print(a) Output
Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string
32
Or three single quotes
a = ‘’’Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string’’’
print(a)
Output
Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string
33
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of
bytes representing unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Example
Get the character at position 1 (remember that the rst character has the position 0):
Output
a = "Hello, World!"
print(a[1])
e 34
fi
Looping Through a String
Since strings are arrays, we can loop through the characters in a string,
with a for loop.
Example
Loop through the letters in the word "BANANA"
for x in "BANANA":
print(x) Output
B
A
N
A
N
A
35
String Length
Example
a = "Hello, World!"
print(len(a))
Output
13
36
Check String
Example
Check if "free" is present in the following text: Output
Use it in an if statement
37
Check if NOT
Example
Check if "expensive" is NOT present in the following text:
3. Given two strings, s1 and s2. Write a program to create a new string s3
by appending s2 in the middle of s1.
39
fi
Python - Slicing Strings
Specify the start index and the end index, separated by a colon, to return a part of
the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5]) Output
llo
The first character has index 0.
40
Slice From the Start
b = "Hello, World!"
print(b[:5])
Output
Hello
41
Slice To the End
By leaving out the end index, the range will go to the end:
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Output
llo, World!
42
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
b = "Hello, World!"
print(b[-5:-2])
43
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
1. Upper Case
44
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
45
Replace String
Example
a = " Hello, World! " Output
print(a.replace(“H”, “J”))
Jello, World!
46
Split String
The split() method returns a list where the text between the speci ed separator
becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the
separator:
47
fi
String Concatenation
Example
Merge variable a with variable b into variable c:
a = “Hello" Output
b = “World!”
c = a + b HelloWorld!
print(c)
To add a space between them, add a " ":
a = “Hello" Output
b = “World!”
c = a + “ ” +b Hello World!
print(c)
48
String Format
F-Strings
To specify a string as an f-string, simply put an f in front of the string literal,
and add curly brackets { } as placeholders for variables and other operations.
Example
Create an f-string:
Age = 36
txt = f"My name is John, I am {Age}”
print(txt)
Output
My name is John, I am 36
49
Placeholders and Modi ers
A placeholder can contain variables, operations, functions, and modi ers to
format the value.
Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)
50
fi
fi
A placeholder can include a modi er to format the value.
A modi er is included by adding a colon : followed by a legal formatting type, like
.2f which means xed point number with 2 decimals:
Example
Display the price with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Output
51
fi
fi
fi
A placeholder can contain Python code, like math operations:
Output
52
Escape Character
You will get an error if you use double quotes inside a string that is surrounded
by double quotes:
53
To x this problem, use the escape character \"
Example
The escape character allows you to use double quotes when you
normally would not be allowed:
54
fi
55
PRACTICE PROBLEMS
1. Introduce Yourself
You have a few Python variables that describe your age, name, and
favorite food:
name = "Rohan"
age = 27
favourite_food = "Pizza"
56
Solution
name = "Rohan"
age = 27
favourite_food = "Pizza"
print(intro_string)
# output:
57
2. Letters in a Name
Create a code that asks the user for their full name. Then it should count the
number of letters in their name, ignoring spaces. Finally, it should greet the
user and inform them of the length of their name.
58
Solution
59
PRACTICE PROBLEMS
1.Write a program to create a new string made of an input string’s rst, middle,
and last character.
2.Write a program to create a new string made of the middle three characters of
an input string.
3.Given two strings, s1 and s2. Write a program to create a new string s3 by
concatenating s1 and s2
60
fi
Python If Statement
Syntax
if expression:
# statement(s) to be executed
61
62
63
Python if else Statement
Syntax
if expression:
# code block to be executed
#
else:
# code block to be executed
#
64
65
66
Python if…elif…else Statement
• The if elif else statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE.
• Similar to the else block, the elif block is also optional.
• However, a program can contains only one else block whereas there can be an
arbitrary number of elif blocks following an if block.
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s) 67
68
PRACTICE PROBLEMS
1. Write a program to check whether the given input number is divisible by 3 or else
show a message “Number is not divisible by 3”.
2. Write a program that checks whether the given input is an even number or an odd
number.
3. Write an if/else statement with the following condition: If the variable age is
greater than 18, output "Old enough", otherwise output "Too young”.
4. Write a program that takes input a number from user & state whether the number
is positive, negative or zero.
5. Write a program that takes a character (i.e. string of length 1) and returns true if it
is a vowel, false otherwise.
69
Python for Loop
Syntax
for val in sequence:
# body of the loop
70
Example:
Output:
apple
banana
cherry
71
Example: Loop Through a String
for x in “BANANA":
print(x)
Output:
B
A
N
A
N
A
72
The break Statement
With the break statement we can stop the loop before it has
looped through all the items:
Example:
Output:
apple
banana
73
Exit the loop when x is "banana", but this time the break comes
before the print:
Output:
apple
74
The continue Statement
With the continue statement we can stop the current iteration of the loop,
and continue with the next:
Example
Do not print banana:
75
for Loop with Python range()
76
fi
fi
The range() function defaults to 0 as a starting value, however it is
possible to specify the starting value by adding a parameter: range(2,
6), which means values from 2 to 6 (but not including 6):
Example
Output:
for x in range(2, 6): 2
print(x) 3
4
5
77
The range() function defaults to increment the sequence by 1,
however it is possible to specify the increment value by adding a third
parameter: range(2, 30, 3):
Output:
2
Example
5
8
Increment the sequence with 3 (default is 1):
11
14
for x in range(2, 25, 3): 17
print(x) 20
23
78
Else in For Loop
Example
Print all numbers from 0 to 5, and print a message
when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
79
The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
80
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Output:
Print each adjective for every fruit:
81
The pass Statement
for loops cannot be empty, but if you for some reason have a for loop
with no content, put in the pass statement to avoid getting an error.
Example:
for x in [0, 1, 2]:
pass
82
PRACTICE PROBLEMS
83
fi
PRACTICE PROBLEMS
1.Write a python program to Iterate through the list, ['Python', 'Numpy','Pandas','Django',
'Flask'] using a for loop and print out the items.
2.Write a python program to iterate from 0 to 100 and print only even numbers
3.Write a python program to iterate from 0 to 100 and print only odd numbers
4.Print the following pattern
#
##
###
####
#####
6. Write a program for printing Multiplication Table of 10 Using Python nested loops.
84
Syntax
while condition:
statements
The while Loop
With the while loop we can execute a set of statements as long as a
condition is true.
Example
Output
Print i as long as i is less than 10: 1
2
i=1 3
while i < 10: 4
5
print(i)
i += 1
Remember to increment i, or else the loop will continue forever.
With the break statement we can stop the loop even if the while
condition is true:
Example
Exit the loop when i is 3:
i=1 Output
while i < 10: 1
2
print(i) 3
if i == 3:
break
i += 1
86
The continue Statement
Example
Continue to the next iteration if i is 3:
i=0
Output
while i < 6: 1
i += 1 2
if i == 3: 4
5
continue 6
print(i)
87
The else Statement
With the else statement we can run a block of code once when the
condition no longer is true:
Example
Print a message once the condition is false:
i=1 Output
while i < 6: 1
2
print(i) 3
i += 1 4
else: 5
print("i is no longer less than 6") I is no longer less than 6
88
Python Functions
• The idea is to put some commonly or repeatedly done tasks together and
make a function.
• instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.
fi
89
Types of Functions in Python
1. Built-in library function: These are Standard functions in Python that are
available to use.
2. User-de ned function: We can create our own functions based on our
requirements.
90
fi
Creating a Function in Python
def fun():
print(“Hello world”)
91
fi
Calling a Function in Python
• After creating a function in Python we can call it by using the name of the
functions followed by parenthesis containing parameters of that particular
function.
Example:
Output:
# A simple Python function
Hello world
def fun():
print(“Hello world”))
92
Python Function with Parameters
• Similar to the return type of functions and data type of arguments in C/C++, this is also
possible in Python (speci cally in Python 3.5 and later).
• Information can be passed into functions as arguments.
• Arguments are speci ed after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
93
fi
fi
The following example has a function with one argument (fname). When the
function is called, we pass along a rst name, which is used inside the function to
print the full name:
Example:
Output:
def my_function(fname):
print(fname + " John”)
Emil John
my_function("Emil") Tobias John
my_function("Tobias") Linus John
my_function("Linus")
95
fi
Number of Arguments
Example: Output:
def my_function(fname, lname):
print(fname + " " + lname)
Emil John
my_function("Emil", “John")
96
Example:
97
Arbitrary Arguments, *args
- If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function de nition.
- This way the function will receive a tuple of arguments, and can access
the items accordingly:
Example:
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2]) Output:
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Output:
The youngest child is Linus
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
99
Arbitrary Keyword Arguments, **kwargs
- If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function de nition.
- This way the function will receive a dictionary of arguments, and can access the
items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
fi
Default Parameter Value
Example:
def my_function(country = "Norway"):
print("I am from " + country)
Output:
my_function("Sweden")
my_function("India") I am from Sweden
my_function() I am from India
my_function("Brazil") I am from Norway
I am from Brazil
101
Passing a List as an Argument
- You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
Eg: if you send a List as an argument, it will still be a List when it reaches the
function
Example
Output:
def my_function(food):
for x in food:
print(x) Apple
Banana
fruits = ["Apple", "Banana", "Cherry"]
Cherry
my_function(fruits)
102
Return Values
Example:
print(my_function(3)) 15
print(my_function(5)) 25
print(my_function(9)) 45
103
The pass Statement
Example
def myfunction():
pass
104
fi
fi
Positional Arguments
Example: Output:
105
fi
fi
Keyword Arguments
Example:
Output:
106
Positional-Only Arguments
- You can specify that a function can have ONLY positional arguments, or ONLY
keyword arguments.
- To specify that a function can have only positional arguments, add , / after the
arguments.
Example
Output:
def my_function(x, /):
print(x) 3
my_function(3)
def my_function(x):
Output:
print(x)
my_function(x = 3) Error
107
Keyword-Only Arguments
- To specify that a function can have only positional arguments, add *, after the
arguments.
def my_function(*,x):
Example print(x)
my_function(3)
def my_function(*, x):
print(x)
Output:
my_function(x = 3) Error
Output:
3
108
Combine Positional-Only and Keyword-Only
You can combine the two argument types in the same function.
Any argument before the / , are positional-only, and any argument after the *,
are keyword-only.
Example
Output:
def my_function(a, b, /, *, c, d): 26
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)
109
Recursion
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the bene t of meaning that you can loop through data to reach a result.
Example
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial(n - 1)
# Example usage
n= factorial(5)
print(f"The factorial is {n}")
110
fi