Functions and Classes in Python

Table of contents

Mohamed Niang
2 min readMay 20, 2021

Functions

How to create a function

def Car(n):
print('My car is Toyota!'+n)

Car('health ')
My car is Toyota!def Car(carname):
print('My car is ' + carname + '!')

Car('Ford')
My car is Ford!

Write a Car function with price as a parameter that performs the following conditional actions:

  • if price is above 20,000, print “It is expensive!”.
  • if price is less than 20,000 and above 10,000 print “It is reasonable!”.
  • Otherwise, print “It is cheap!”.
def Car(price):
if price >= 20000:
print("It is expensive!")
elif price >= 10000:
print("It is reasonable!")
else:
print("It is cheap!")

price = 9000
Car(price)

Write a function to compute factorial of a number. The factorial of a number is the product of all the integers from 1 to that number.

def factorial(x):
f = 1

for i in range(1,x+1):
f = f*i
return f

factorial(4)

Classes

How to create a class

class Car:
pass

car = Car() # instantiate the class Car and assign it to the variable car
print(car)

Attributes in class

class Car:
name = "Toyota" # set an attribute `name` of the class

car = Car()

print(car.name) # access the class attribute name inside the class Car

Methods in class

class Car:
name = "Toyota"

def change_name(self, new_name): # note that the first argument is self
self.name = new_name # access the class attribute with the self keyword


car = Car()

print(car.name)

car.change_name("Ford")
print(car.name)
Toyota
Ford
class Car:
self.name = "Toyota"


car = Car()

print(car.name)

The init method

class Car:

def __init__(self, name): # In order to provide values for the attributes at runtime
self.name = name

def change_name(self, new_name):
self.name = new_name

car_t = Car('Toyota')
print(car_t.name)

car_f = Car('Ford')
print(car_f.name)

car_f.change_name("Benz")
print(car_f.name)

Write a Car class with an instance variable, price, and a constructor that takes a float, base_price, as a parameter. The constructor must assign base_price to price after confirming the argument passed as base_price is not negative; if a negative argument is passed as base_price, the constructor should set price to 0 and print “price is not valid, setting price to 0”. In addition, write Is_it_expensive() instance method that performs the following conditional actions:

  • if price is above 20,000, print “It is expensive!”.
  • if price is less than 20,000 and above 10,000 print “It is reasonable!”.
  • Otherwise, print “It is cheap!”.
class Car:
def __init__(self, base_price):
if base_price > 0:
self.price = base_price
else:
print("price is not valid, setting price to 0")
self.price = 0

def Is_it_expensive(self):

if self.price >= 20000:
print("It is expensive!")
elif self.price >= 10000:
print("It is reasonable!")
else:
print("It is cheap!")

price = 11000
car = Car(price)
car.Is_it_expensive()

--

--