Best Practice
-
DRY: Dont Repeat Yourself
-
Sample program to print numbers which are even and which are odd from 1 to n
max_value = int(input('Enter the max value'))
print(f'Even numbers from 1 to {max_value} are')
for index in range(1,max_value):
if index%2 = 0:
print(index)
print(f'Odd numbers from 1 to {max_value} are')
for index in range(1,max_value):
if index%2 = 1:
print(index)
-
Mistake done at source will impact multiple places and you need to apply fix at multiple places/lines in your code.
-
Solution: Rather than redundant code make it reusable.
-
Basic programming construct to make code reusable is called as function.
Python functions
- function is a reusable code block
- syntax of function
def <nameofthefunction>(<args>):
<function implementation>
- Example:
def add(number1, number2):
result = number1 + number2
print(f"{number1} + {number2} = {result}")
- Calling a function is just call by name of the function and pass arguments if any
def add(number1, number2):
result = number1 + number2
print(f"{number1} + {number2} = {result}")
add(3,5) # calling a function
add(number2= 5, number1= 3) # calling a function using named arguments.
Debugging Terms
- Step Into:
- Step into will take the control inside the function
- Call Stack:
- Stack consiting of trace information from where the code is called.
Adding Simple functions to our own POS
menu = """
Enter the number
0 => View Products
1 => Add Product
2 => Update Product
3 => Delete Product
4 => Sell Items
5 => Report
6 => Exit
"""
# structure of dictionary will be
# {
# '<code>' : {
# 'name': '<product name>',
# 'quantity': <product quantity>
# }
# }
# example:
# products = {
# 'dell': { 'name': 'dell', 'cp': 30000, 'sp': 34000, 'quantity': 20, 'model': 'latitude'},
# 'hp': { 'name': 'hp', 'cp': 30000, 'sp': 34000, 'quantity': 20, 'model': 'elitebook'},
# }
products = {}
def ask_user_input(purpose):
# This function asks for user input with custom message and returns the values
user_input = input(f"Enter the {purpose} = ")
return user_input
def does_product_exists(code):
# returns whether the code exists or not
return code in products.keys()
while True:
choice = input(menu)
if choice == '0':
for code, product in products.items():
print(f"{code} = {product}")
elif choice == '1':
code = input('Enter the product code name = ')
if code in products:
print(f'{code} already exists')
continue
product = {}
product['name'] = ask_user_input('product name')
product['model'] = ask_user_input('model')
product['cp'] = float(ask_user_input('cost price'))
product['sp'] = float(ask_user_input('selling price'))
product['quantity'] = int(ask_user_input('available quantity'))
products[code] = product
elif choice == '2':
code = ask_user_input('product code name')
if code not in products.keys():
print('Invalid code entered. Please check the code')
continue
quantity = int(ask_user_input('quantity to be added'))
new_quantity = quantity + products[code]['quantity']
products[code]['quantity'] = new_quantity
print(f'quantity updated and new quantity is {new_quantity}')
elif choice == '3':
code = ask_user_input('product code name')
if code not in products.keys():
print('Invalid code entered. Please check the code')
continue
return_product = products.pop(code)
print(f"{return_product} has been deleted")
else:
exit(0)
Function Types as of now
- We have two function types as of now
- Functions which return value:
- These functions have return statement
def add(number1, number2): return (number1+number2) x = add(3,5) # x will have 8
- Functions which return value:
- Functions which donot
- These functions don’t have return statement
- But if you assign the function to variable as shown below, it will have None (variable not assigned to any memory)
def add(number1, number2):
print(number1+number2)
x = add(3,5)
# x will have None
Functions with default arguments
- To understand this lets use Project Euler Problem 1
def project_euler_1(max_number, number1=3, number2=5):
# This function has two default arguments number1 and number2
# if you pass the value the value will be overwritten, if you dont pass the
# value, This functions takes default
# example: project_euler_1(1000,5,3) => number1=> 5, number2 = 3
# project_euler_1(1000) => number1 => 3, number2 => 5
result = 0
for index in range(1,max_number):
is_divisible = (index%number1 == 0 or index%number2 ==0)
if is_divisible:
result = result+index
return result
print(project_euler_1(1000))
Exercise: Create one module Projecteuler.py and create functions called as problem1, problem2 and so on
- Solve this
Project Euler 3 with Functions
def is_prime(number):
# This function will return true if the number is prime, false otherwise
is_prime_number = True
for index in range(2,(number//2+1)):
if number%index == 0:
is_prime_number = False
break
return is_prime_number
def largest_prime_factor(number):
# This function returns largest prime factor
for index in range(number//2,2,-1):
if number%index == 0 and is_prime(index):
return index
print(largest_prime_factor(600851475143))