Chapter 6 - Conditional Expressions: Syntax
Chapter 6 - Conditional Expressions: Syntax
Chapter 6 - Conditional Expressions: Syntax
All these are decisions that depend on the condition being met.
If else and elif statements are a multiway decision taken by our program
due to certain conditions in our code.
Syntax:
'''
if (condition1): // if condition 1 is true
print(“yes”)
elif (condition2): // if condition 2 is true
print(“No”)
else: // otherwise
print(“May be”)
'''
Copy
Code example:
a = 22
if (a>9):
print(“Greater”)
else:
print(“lesser”)
Copy
Quick Quiz: Write a program to print yes when the age entered by the
user is greater than or equal to 18.
Relational Operators
Relational operators are used to evaluate conditions inside if statements.
Some examples of relational operators are:
= = -> equals
<=, etc.
Copy
Logical Operators
elif clause
elif in python means [else if]. If statement can be chained together with a
lot of these elif statements followed by an else statement.
'''
if (condition1):
#code
elif (condition 2):
#code
elif (condition 2):
#code
….
else:
#code '''
Copy
“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a
program to detect these spams.
90-100 Ex
80-90 A
70-80 B
60-70 C
50-60 D
<50 F
Loops make it easy for a programmer to tell the computer, which set of
instructions to repeat, and how!
1. While loop
2. For loop
While loop
An Example:
i = 0
while i<5:
print(“Harry”)
i = i+1
Copy
(Above program will print Harry 5 times)
Note: if the condition never becomes false, the loop keeps getting
executed.
Quick Quiz: Write a program to print the content of a list using while
loops.
For loop
A for loop is used to iterate through a sequence like a list, tuple, or string
(iterables)
The syntax of a for loop looks like this:
l = [1, 7, 8]
for item in l:
print(item)
Copy
(Above program will print 1, 7, and 8)
An optional else can be used with a for loop if the code is to be executed
when the loop exhausts.
Example:
l = [1, 7, 8]
for item in l:
print(item)
else:
print(“Done”) #This is printed when the loop exhausts!
Copy
Output:
1
7
Done
Copy
‘break’ is used to come out of the loop when encountered. It instructs the
program to – Exit the loop now.
Example:
‘continue’ is used to stop the current iteration of the loop and continue
with the next one. It instructs the program to “skip this iteration.”
Example:
for i in range(4):
print(“printing”)
if i == 2: #if i is 2, the iteration is skipped
continue
print(i)
Copy
pass statement
Example:
l = [1, 7, 8]
for item in l:
pass #without pass, the program will throw an error
Copy
***
**
*** for n = 3
Copy
When a program gets bigger in size and its complexity grows, it gets
difficult for a programmer to keep track of which piece of code is doing
what!
Function call
The part containing the exact set of instructions that are executed during
the function call.
Quick Quiz: Write a program to greet a user with “Good day” using
functions.
A function can accept some values it can work with. We can put these
values in the parenthesis. A function can also return values as shown
below:
def greet(name):
gr = “Hello” + name
return gr
Copy
a = greet(“Harry”) #“Harry” is passed to greet in name
For Example:
def greet(name=’stranger’):
#function body
Copy
greet() #Name will be ‘stranger’ in function
body(default)
Recursion
Recursion is a function which calls itself.
factorial(n) = n * factorial(n-1)
Copy
This function can be defined as follows:
def factorial(n):
if i == 0 or i == 1 : #Base condition which doesn’t call the
function any further
return i
else:
return n*factorial(n-1) #Function calling itself
Copy
This works as follows:
** #For n = 3
*
Copy
A file is data stored in a storage device. A python program can talk to the
file by reading content from it and writing content to it.
Types of Files
Python has a lot of functions for reading, updating, and deleting files.
Opening a file
We can also use f.readline() function to read one full line at a time.
f.readline() #Reads one line from the file
Copy
Modes of opening a file
f.close()
Copy
With statement
The best way to open and close the file automatically is the “with”
statement.
with open(“this.txt”) as f:
f.read()
Copy
#There is no need to write f.close() as it is done automatically
1. Write a program to read the text from a given file, “poems.txt” and
find out whether it contains the word ‘twinkle’.
2. The game() function in a program lets a user play a game and
returns the score as an integer. You need to read a file
“Hiscore.txt” which is either blank or contains the previous Hi-
score. You need to write a program to update the Hi-score
whenever game() breaks the Hi-Score.
3. Write a program to generate multiplication tables from 2 to 20 and
write it to the different files. Place these files in a folder for a 13-
year old boy.
4. A file contains the word “Donkey” multiple times. You need to write
a program which replaces this word with ###### by updating the
same file.
5. Repeat program 4 for a list of such words to be censored.
6. Write a program to mine a log file and find out whether it contains
‘python’.
7. Write a program to find out the line number where python is
present from question 6.
8. Write a program to make a copy of a text file “this.txt.”
9. Write a program to find out whether a file is identical and matches
the content of another file.
10. Write a program to wipe out the contents of a file using
python.
11. Write a python program to rename a file to
“renamed_by_python.txt.”
Class
Object
Class Attributes
An attribute that belongs to the class rather than a particular object.
Example:
Class Employee:
company = “Google” #Specific to each class
harry = Employee() #Object instantiation
harry.company
Employee.company = “YouTube” #changing class attribute
Copy
Instance Attributes
harry.attribute1 :
‘self’ parameter
harry.getSalary()
Copy
here, self is harry, and the above line of code is equivalent to
Employee.getSalary(harry)
For Example:
class Employee:
def __init__(self,name):
self.name = name
def getSalary(self):
#Some code…
harry = Employee(“Harry”) #Object can be instantiated using
constructor like this!
Copy
Syntax:
Type of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
Single Inheritance
Single inheritance occurs when a child class inherits only a single parent
class.
Multiple Inheritance
Multiple inheritances occurs when the child class inherits from more than
one parent class.
Multilevel Inheritance
Super() method
A class method is a method which is bound to the class and not the
object of the class.
class Employee:
@property
def name(self):
return self.ename
Copy
if e = Employee() is an object of class employee, we can print (e.name)
top print the ename/call name() function.
@name.setter
def name(self, value):
self.ename = value
Copy
Operator overloading in Python
These methods are called when a given operator is used on the objects.
p1 – p2 -> p1.__sub__(p2)
p1 * p2 -> p1.__mul__(p2)
p1 / p2 -> p1.__truediv__(p2)
p1 // p2 -> p1.__floordiv__(p2)
Copy
Other dunder/magic methods in Python
__str__() -> used to set what gets displayed upon calling str(obj)
__len__() -> used to set what gets displayed upon calling .__len__()
or len(obj)
Copy
7i + 8j + 10k
Copy
Assume vector of dimension 3 for this problem.
If the player’s guess is higher than the actual number, the program
displays “Lower number please”. Similarly, if the user’s guess is too low,
the program prints “higher number please”.
When the user guesses the correct number, the program displays the
number of guesses the player used to arrive at the number.