0% found this document useful (0 votes)
21 views12 pages

Function, Class, Methods, Args

The document explains the concepts of objects, functions, methods, and constructors in Python, highlighting their definitions and differences. It includes examples of function and class definitions, as well as multiple-choice questions and flashcards for review. Additionally, it discusses the benefits of using functions and classes for code organization and reusability.

Uploaded by

Kabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views12 pages

Function, Class, Methods, Args

The document explains the concepts of objects, functions, methods, and constructors in Python, highlighting their definitions and differences. It includes examples of function and class definitions, as well as multiple-choice questions and flashcards for review. Additionally, it discusses the benefits of using functions and classes for code organization and reusability.

Uploaded by

Kabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Main Questions

What is an object?

-An object is an instance of a class.


-It holds data in the form of attributes
-Has functions (called methods) to perform actions. -Each object has its own copy of data, but shares
the structure defined by the class. -For example, if Car is a class, car1 = Car("Toyota", "Red") creates
an object named car1.

How is a function defined?

-A function is defined using the def keyword followed by the function name, parentheses for
parameters, and a colon.

-The function contains code that performs a specific task and can be called whenever needed.

-Example:

python
def greet():
print("Hello")

Functions can also return values using the return keyword.

How is a method defined?

-A method is defined just like a function, using def, but it is written inside a class.

-It always takes self as its first parameter, which refers to the object calling the method.

-Methods can use or change the object’s data.

-Example:

python
class Car:
def describe(self):
print("This is a car")

What does constructor mean?

-A constructor is a special method that automatically runs when a new object is created.
-In Python, the constructor is named __init__(). It initializes (sets) the object's attributes with given
values.

-Example:

python
def __init__(self, brand, color):
self.brand = brand
self.color = color

Difference between function and method

* A function is a block of code defined outside any class. It does not have self and can be called
directly.

* A method is a function defined inside a class. It always takes self as the first parameter and works
with the object's data.

Example of function:

python
def greet():
print("Hello")

Example of method:

python
class Car:
def describe(self):
print("This is a car")

MCQS
1. *What is the main benefit of using functions in Python?*
A. Slows down execution
B. Increases redundancy
C. Increases code reusability and readability ✅
D. None of the above

2. *Which keyword is used to define a function in Python?*


A. function
B. define
C. fun
D. def ✅

3. *Which of these is NOT a type of function in Python?*


A. User-defined
B. Pre-defined
C. Built-in
D. Default ✅

4. *What is the correct syntax for a simple function in Python?*


A. function myFun():
B. def myFun(): ✅
C. define myFun():
D. fun myFun():

5. *What is a default argument?*


A. An argument passed as keyword
B. An argument that must always be specified
C. An argument that assumes a default value if not provided ✅
D. None of the above

6. *Which function call uses a default argument correctly?*


A. myFun(10, 20)
B. myFun(y=20)
C. myFun(10) ✅
D. myFun()

7. *What happens if you pass arguments in the wrong order using positional arguments?*
A. You get a syntax error
B. Values are assigned incorrectly ✅
C. Python auto-corrects
D. Nothing changes

8. *What is the purpose of keyword arguments?*


A. You must pass all values
B. You don’t need to remember the order ✅
C. Keywords must be strings
D. Arguments become optional
9. **What does *args allow in a function?**
A. No arguments
B. Unlimited keyword arguments
C. Unlimited non-keyword arguments ✅
D. Passing default arguments

10. **What does **kwargs allow in a function?**


A. No arguments
B. Multiple return values
C. Unlimited keyword arguments ✅
D. Only one default

11. *What is a class in Python?*


A. A type of list
B. A set of values
C. A blueprint for creating objects ✅
D. A method group

12. *Why do we use classes?*


A. Increases repetition
B. Keeps code disorganized
C. Keeps data and functions together ✅
D. Makes code longer

13. *What is the correct way to define a constructor in Python?*


A. def constructor()
B. def init()
C. def *init*() ✅
D. def new()

14. **How do you create an object of a class called Student?**


A. student = Student.create()
B. student = new Student()
C. student = Student("Ali", 101) ✅
D. object = Student

15. *What is a method?*


A. A variable
B. A loop
C. A function inside a class ✅
D. A keyword

16. What will be the output of the following function call?

def nameAge(name, age):


print("Hi, I am", name)
print("My age is", age)

nameAge(27, "ARSI")

A. Hi, I am 27
My age is ARSI ✅
B. Hi, I am ARSI
My age is 27
C. Error: Type mismatch
D. Error: Wrong argument order

17. Which of the following calls will produce the correct output for nameAge(name, age)?

A. nameAge("age", "name")
B. nameAge(age=27, name="ARSI") ✅
C. nameAge(27, name="ARSI")

D. nameAge("ARSI")

18. Which function call will result in an error if the function is defined as def nameAge(name,
age):?

A. nameAge("Ali", 25)
B. nameAge(age=25, name="Ali")
C. nameAge("Ali", age=25) ❌ (✅ This one is correct usage — trick!)
D. nameAge(age=25) ✅

19) If the order of arguments matters, what kind of arguments are being used?

A. Keyword arguments
B. Default arguments
C. Arbitrary arguments
D. Positional arguments ✅

20) What is the advantage of using keyword arguments in a function call?

A. No need to define parameters


B. Avoids syntax errors
C. You don’t need to remember the order of parameters ✅
D. Variables become global

FlashCards

Q: What is a Python function?


A: A block of statements designed to perform a specific task and increase code reuse.

Q: What are the two main types of Python functions?


A: Built-in library functions and user-defined functions.

Q: What keyword is used to define a function in Python?


A: def

Q: What are default arguments?


A: Parameters with default values that are used if no value is passed during function call.
Q: What are positional arguments?
A: Arguments assigned based on their position in the function call.

Q: What are keyword arguments?


A: Arguments passed by explicitly stating parameter names.

Q: What is *args used for?


A: Passing a variable number of *non-keyword* arguments.

Q: What is **kwargs used for?


A: Passing a variable number of *keyword* arguments.

Q: What is a class?
A: A blueprint for creating objects, bundling data and functions together.

Q: Why use classes?


A: To avoid repetition, organize data/functions, and simplify large projects.

Q: How is a class created?


A: Using the class keyword followed by methods like __init__.

Q: What is a method?
A: A function defined inside a class that uses self to access object data.

Q: Types of Python Function Arguments


A: Default argument, Keyword arguments (named arguments), Positional arguments, Arbitrary
arguments

Q: What is the risk of using positional arguments incorrectly?

A: The values might be assigned to the wrong parameters, leading to logic errors without any
syntax errors.

Q: How can you fix a function call where the arguments are in the wrong order?

A: Use keyword arguments to explicitly assign values to parameter names (e.g.,


nameAge(name="Ali", age=25)).

Q: Which type of argument helps you write function calls in any order?

A: Keyword arguments.

Q: If a function requires two arguments but you only pass one, what happens?

A: A TypeError occurs unless the missing argument has a default value.


Q: What does Python prioritize: positional or keyword arguments?

A: Python fills positional arguments first, then matches keyword arguments. Mixing them must
be done carefully.

Examples
Function:

def add(num1, num2):


num3 = num1 + num2
return num3

num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

Class:

Class → A blueprint (like a plan).


Objects → The actual things created using the class.
Methods → The actions that the object can do.
Attributes → The information/data stored inside the object.

1)

class Car:
def _init_(self, brand, color):
self.brand = brand # Save brand name in object
self.color = color # Save color in object

def describe(self):
print(f"This is a {self.color} {self.brand}")

# Create first car object


car1 = Car("Toyota", "Red")

# Create second car object


car2 = Car("Honda", "Blue")

# Call the describe method for both cars


car1.describe()
car2.describe()

Output:
This is a Red Toyota
This is a Blue Honda

2)

class Student:
def _init_(self, name, roll):
self.name = name
self.roll = roll

def introduce(self):
print(f"My name is {self.name} and my roll number is {self.roll}")

student1 = Student("Ali", 101)


student2 = Student("Sara", 102)

student1.introduce()
student2.introduce()

Output:
My name is Ali and my roll number is 101
My name is Sara and my roll number is 102

The _init_ method:


This is a special method (called constructor).
It runs automatically when you create a student object.

3)
class Car:
def __init__(self, brand, color, year):
self.brand = brand
self.color = color
self.year = year # New feature added

def describe(self):
print(f"This is a {self.color} {self.brand} from {self.year}")

Output:
car1 = Car("Toyota", "Red", 2022)
car2 = Car("Honda", "Blue", 2021)

car1.describe()
car2.describe()

*Args and **kwargs

1) Args

def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to’, Ksbl')

Output:
Hello
Welcome
to
Ksbl

2) Kwargs

def myFun(**kwargs):
for key, value in kwargs.items():
print(key, “:”, value)

myFun(first=hello', mid=‘Class', last=‘of KSBL')


Output:
first == hello
mid == Class
last == of KSBL

Default Argument

def myFun(x, y=50): print("%s == %s" % (key, value))

print("x: ", x) and


print("y: ", y)
print(key, "==", value)

myFun(10) both produce the same output here.

Output:
x: 10
y: 50

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)

myFun(10)

Output:
x: 10
y: 20

Positional Argument

def nameAge(name, age):


print("Hi, I am", name)
print("My age is ", age)

print("Case-1:")
nameAge(“ARSI", 27)

print("\nCase-2:")
nameAge(27, “ARSI")
Output:

Case-1:
Hi, I am ARSI
My age is 27

Case-2:
Hi, I am 27
My age is ARSI

Keyword Argument

def student(firstname, lastname):


print(firstname, lastname)

student(firstname=hello', lastname=world')
student(lastname=world', firstname=hello')

Output:
hello world
hello world

Extra Info

Benefits of Using Functions


• Increase Code Readability
• Increase Code Reusability

Benefits of Using Class:


• Avoids writing repetitive code.
• Keeps related data and functions together.
• Makes big projects manageable.
• Easy to update or modify later.
• Example: Instead of writing separate code for each player in a game, create one Player class

Benefits of Using Classes and Methods:

• Keeps code organized and logical.


• Makes it easier to add features later.
• Reusable across multiple parts of your project.
• Great for building games, websites, apps, and more.

You might also like