You are on page 1of 69

Data Analytics with Python

Python Programming Fundamentals


Learning Objectives

By the end of this lesson, you will be able to:

Use conditions and branching in Python programs

Create Python programs using loops

Construct functions in Python programs

Create classes and objects in Python programs


Conditions and Branching
Conditional Statements

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.

If Condition = True The code runs

If Condition = False Nothing happens

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

if age > 18:


print “person is adult”
else:
print “person is not adult”
If…Else If Statements

These are used to combine multiple if statements. These statements:

Execute only one branch

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

Nested if, elif, and else


Ternary Operators

Ternary operators, also known as conditional statements, test a condition in a single line, replacing the
multiline if-else, making the code compact.

Syntax: [on_true] if [expression] else [on_false]

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

The while statement is used for repeated execution if an expression is true.

Example

Syntax : a=0

<start value> while a < 3:

while condition: a=a+1

statements print a
print ‘All Done’
While Loop: Example

Example code of a while loop:

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.

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
Fibonacci Series Using While Loop

Objective: Write a program to print the Fibonacci series up to a certain number.

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
Unassisted Practice: Fibonacci Series Using While Loop

Number till where you want to print the Fibonacci series


First number of a Fibonacci is zero
Second number in a Fibonacci series is one

while loop to print the Fibonacci series until the ‘fib_num’

Print the Fibonacci number


Print the Fibonacci number

Update the values of first number and second number

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

Example of for loop with range:

Range Example List Example

for x in range(10):
print x
For Loop with List: Example

Example of for loop with list:

Range Example List Example

fruits = ['apple' , 'mango' , 'orange' , 'banana']


for fruit in fruits:
print fruit
For Loop: Example

Example code of a for loop:

For loop iterator

The continue statement

The break statement


For Loop with Else

• It works exactly as the optional else of a while loop.


• It will be executed only if the loop hasn't been broken by a break statement.
• So, it will only be executed after all the items of the sequence in the header have been used.

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

Hint: Use the built-in functions of string

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
Create a Pyramid of Stars

Objective: Write a program to print the pyramid of stars.


Example:

*
***
*****
*******
*********

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
Unassisted Practice: Create a Pyramid of Stars

Number of rows in the pyramid

Loop for the rows


Loop to print the number of space
A while loop to print the odd
number of stars in each row
Print the stars and append a space

New line after each row to display pattern correctly

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

Use def to create a function and assign it a name.


Functions: Considerations

Some important points to consider while defining functions:

• A function should always have a return value.


• If return is not defined, then it returns None.
• Function overloading is not permitted.
Function name

Create function Argument

Return type

Call function
Functions: Returning Values

You can use a function to return a single value or multiple 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

Print data element and


index using enumerate
method

Create a data
element and index
map using dict

View the store map in the


form of key-value pair
Built-in Sequence Functions: Sorted

Sort numbers

Sort a string
value
Built-in Sequence Functions: Reversed and Zip

Create a list of
numbers for range 15

Use reversed function


to reverse the order

Define list of subjects


and count

Zip function to pair


the data elements of
lists
Return list of tuples

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.

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
Create a Bank System Using Functions

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.

Hint: Use if else statements and functions

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
Unassisted Practice: Create a Bank System Using Functions

Initial balance in the bank account

Function defined to withdraw amount

Function defined to credit an amount

Function defined to change the password of an account


Unassisted Practice: Create a Bank System Using Functions

Output
Objects and Classes
Classes

A class is a special data type which defines how to build a certain kind of object.

These are user-defined data types which are:


▪ Used as a blueprint to create multiple objects
▪ Made of variables and functions
▪ Used to depict real-world objects in programming languages

Represent the properties of a real-world entity (such as a car)


Variables in a Class
Examples: model number, build year, brand name

Functions in a Class Represent the possible activities performed by an entity


Examples: start(), stop(), apply break()
Objects

Objects are variables of classes. Everything in Python is a class.

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

For example, let’s learn to define a class called “Vehicle”.

Example:
class Vehicle:
model_name = “model x”
brand_name = “Brand y”

An object of this class will be:


>>>car1 = Vehicle()
Accessing Variables of a Class

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’)

# define a new MyClass


ob = MyClass()

# Output: <function MyClass.func at 0x000000000335B0D0>


print(MyClass.func)

# Output: <bound method MyClass.func of <__main__.MyClass object at 0x000000000332DEF0>>


print(ob.func)

# Calling function func()


# Output: Hello
ob.func()
Adding Functions to a Class

Functions add behavior to a class. Here’s an example to add function to a


class:

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:

__dict__ __doc__ __name__ __module__ __bases__

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

It is the constructor of a class.

• Gets executed in a code when an object is created


• Allocates space for objects
• Initializes the variables of a class
Defining and Using a Class: Example

Here is an example of the class “Student” to understand how to define and use a class.

Defining a Class Using that 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

The code below uses the class “Student”.

Defining a Class Using that Class

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.

Hint: Use class and functions

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
Define a Class for Car Descriptions

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.

Hint: Use class and functions

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
Unassisted Practice: Create a Class for Car Descriptions

Class for car description

Method defined for car description

Object of the class


Access the class variables

Assign values to the class variables for car1

Input the price of car1


Unassisted Practice: Create a Class for Car Descriptions

Object of the class

Assign values to the class variables for car2

Input the price of car2

Print the values of car1


Print the values of car2
Key Takeaways

You are now able to:

Use conditions and branching in Python programs

Create Python programs using loops

Construct functions in Python programs

Create classes and objects in Python programs


Knowledge Check
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
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

The correct answer is d

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. ;

The correct answer is c

Indentation marks the blocks of code.


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
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

The correct answer is c

The return statement allows to exit the control from a function.


Knowledge
Check
When is “*args” used?
4

a. To create a recursive function

b. To pass arbitrary number of arguments to a function

c. To set the default value of a function argument

d. To reuse codes
Knowledge
Check
When is “*args” used?
4

a. To create a recursive function

b. To pass arbitrary number of arguments to a function

c. To set the default value of a function argument

d. To reuse codes

The correct answer is b

“*args” is used to pass arbitrary number of arguments to a function.


Tic-Tac-Toe Game

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

You might also like