Lesson 03 Python Programming Fundamentals
Lesson 03 Python Programming Fundamentals
Control or conditional statements allow to check the conditions and change the behavior of a program.
Abilities:
• Run a selected section
• Control the flow of a program
• Cover different scenarios
Example:
if x>0:
print “x is positive”
If Statement
The if statement changes the flow of control in a Python program. This is used to run conditional statements.
Example:
if x > 0:
print “x is positive”
If…Else Statements
These are used to control the flow of a program and run conditional blocks.
Example 1
age = 20
if age == 20:
print “age is 20 years”
else:
print “age is not 20”
Example 2
Can be innumerable
Example:
marks= 95
If marks > 90:
print “A grade”
elif marks >= 80:
print “B grade”
elif marks >= 60
print “C grade
If…Else If…Else Statements
These are combined statements. The else statement is executed when none of the conditions are met.
Example:
marks= 95
If marks > 90:
print “A grade”
elif marks >= 80:
print “B grade”
elif marks >= 60
print “C grade”
Else:
print “fail
If, Elif, Else Statements: Example
The if, elif, and else statements are the most commonly used control flow statements.
If condition
Else block
Ternary operators, also known as conditional statements, test a condition in a single line, replacing the
multiline if-else, making the code compact.
Example
max = (a>b) ? A : b
Check the Scores of a Course
Objective: Write a program to check the scores of a course. Take the following considerations while
writing the program: Subject name, score in theory, score in practical.
Check for the following conditions:
• If the selected course is math
• If the score in theory is more than 60 or score in practical is more than 50
• Print the score of the subject
• If the selected course is science
• If the score in theory is more than 60 or score in practical is more than 40
• Print the score of the subject
Access: To execute the practice, follow these steps:
• Go to the PRACTICE LABS tab on your LMS
• Click the START LAB button
• Click the LAUNCH LAB button to start the lab
Loops in Python
While Loop
Example
Syntax : a=0
statements print a
print ‘All Done’
While Loop: Example
While condition
While Loop with Else
Example
• While loop in Python can have an optional else part. to_be_guessed = 5
• The statements in the else part are executed when the condition is not guess = 0
fulfilled anymore. while guess != to_be_guessed:
• If the statements of the additional else part are placed right after the guess = int(input("New number: "))
while loop without an else, they will be executed anyway. if guess > 0:
if guess > to_be_guessed:
print("Number too large")
elif guess < to_be_guessed:
print("Number too small")
else:
print("Sorry that you're giving up!")
break
else:
print("Congratulation. You made it!")
Find Even Digits Numbers
Objective: Write a program that will find all the numbers between 1000 and 3000 (both included) such that each
digit of a number is an even number. The numbers obtained should be printed in a comma-separated sequence
on a single line.
Output
For Loop
Python for loop is an iterator-based for loop. It steps through the items of lists, tuples, strings,
keys of dictionaries, and other iterables.
Example
Syntax :
for <variable> in <sequence>: country=["India","USA","UK","China"]
<statements> for c in country:
else: print(c)
<statements>
Range Function
In Python, the range function is usually used with the loop statements which provides a list of
numbers, starting from zero to a given number minus one.
Example
print(list(range(3,10)))
Output : [3, 4, 5, 6, 7, 8, 9]
Example
print(list(range(10)))
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
For Loop with Range: Example
for x in range(10):
print x
For Loop with List: Example
Example
edibles = ["ham", "spam","eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
break
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")
Break Statement
The break statement breaks out of the innermost enclosing for or while loop. The
break statement may only occur syntactically nested in a for or while loop.
Example
counter = 1
while counter <= 10:
if(counter % 2 ==0 and counter %3 == 0):
break
print(counter)
counter = counter+1
Continue Statement
The continue statement may only occur syntactically nested in a for or while loop. It
continues with the next cycle of the nearest enclosing loop.
Example
counter = 1
while counter <= 10:
if(counter % 5 ==0):
continue
print(counter)
counter = counter+1
Calculate the Number of Letters and Digits
Objective: Write a program that accepts a sentence and calculates the number of letters and digits.
Example: if the entered string is: Python0325
Then the output will be:
LETTERS: 6
DIGITS:4
*
***
*****
*******
*********
Output
Functions
Functions
Functions are the primary and most important method of code organization and reuse in Python.
Syntax Properties
def <name>(arg1, arg2, ..., argN): • Outcome of the function is communicated by return
<statements> statement
return <value> • Arguments in parenthesis are basically assignments
Return type
Call function
Functions: Returning Values
Create function
Call function
Create function
Multiple return
Call function
Built-in Sequence Functions
Enumerate
Indexes data to keep track of indices and corresponding data mapping
Sorted
Returns the new sorted list for the given sequence
Reversed
Iterates the data in reverse order
Zip
Creates lists of tuples by pairing up elements of lists, tuples, or other sequence
Built-in Sequence Functions: Enumerate
List of food
stores
Create a data
element and index
map using dict
Sort numbers
Sort a string
value
Built-in Sequence Functions: Reversed and Zip
Create a list of
numbers for range 15
View type
Search a Specific Element From a Sorted List
Objective: Data of XYZ company is stored in a sorted list. Write a program for searching
specific data from that list.
Objective: Design a software for bank system. There should be options such as cash
withdraw, cash credit, and change password. According to user input, the software should
provide required output.
Output
Objects and Classes
Classes
A class is a special data type which defines how to build a certain kind of object.
You can create multiple objects of a class and each object can have different values for its
variables.
Examples:
• car1 = Car()
• car2 = Car(“Test model” , “Test Brand” )
Defining a Basic Class
Example:
class Vehicle:
model_name = “model x”
brand_name = “Brand y”
Once an object is created, the dot operator is used to access the values stored in different variables of that object.
Print the mode name variable of the car1 object Print a brand name
Example: Example:
>>> print car1.model_name >>> print car1.brand_name
output : model x output : brand y
Object and Class: Example Code
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello’)
Example:
class Vehicle:
model_name = “model x”
brand_name = “Brand y”
def start(self):
print “Starting Vehicle...”
def stop(self):
print “Stop Vehicle...”
Built-In Class Attributes
Every Python class follows built-in attributes, which can be accessed using the dot operator like any other attribute. The
various types of built-in attributes are:
Provides a Provides a class Provides a class Gives the module Returns a possibly
dictionary documentation name name in which the empty tuple
containing the string or nothing, if class is defined containing the base
class's namespace undefined ("__main__" in classes
interactive mode)
__Init__ Function
Here is an example of the class “Student” to understand how to define and use a class.
Example:
class Student(object) :
name = “”
pass = True
def __int__(self, name):
self.name=name
def is_pass(self):
return self.pass
Defining and Using a Class: Example
Example:
class Student(object) :
name = “”
pass = True
def __int__(self, name):
self.name=name
def is_pass(self):
return self.pass
Define a Class for a Computer Science Student
Objective: Define a class for a computer science student with attributes like roll number and name.
Objective: Define a class for car descriptions of two cars with attributes like brand name, car name,
color, and type. Also, input the price of the two cars.
a. Structured Programming
b. Aspect-Oriented Programming
c. Service-Oriented Architecture
d. Object-Oriented Programming
Knowledge
Check
Name the programming model that consists of objects.
1
a. Structured Programming
b. Aspect-Oriented Programming
c. Service-Oriented Architecture
d. Object-Oriented Programming
Object-Oriented Programming revolves around objects and the data and behavior associated with them.
Knowledge
Check
What is used to mark a block of code in Python?
2
a. {}
b. []
c. Indentation
d. ;
Knowledge
Check
What is used to mark a block of code in Python?
2
a. {}
b. []
c. Indentation
d. ;
a. Break
b. Exit
c. Return
d. Back
Knowledge
Check
Name the statement that allows to exit the control from a function in Python.
3
a. Break
b. Exit
c. Return
d. Back
d. To reuse codes
Knowledge
Check
When is “*args” used?
4
d. To reuse codes
Problem Statement:
Write a programming logic to check whether someone has won a game of
tic-tac-toe, without considering the moves.
Instructions to perform the assignment:
You are given a 3 by 3 list of lists that represents a tic-tac-toe game board.
You must find whether anyone has won, and tell which player won, if any.
A tic-tac-toe win is 3 in a row - either in a row, a column, or a diagonal.
Don’t worry about the case where TWO people have won; assume that in
every board there will only be one winner.
Thank You