0% found this document useful (0 votes)
4 views16 pages

? Functions in Python

The document provides detailed explanations and examples of various Python concepts, including functions, string manipulation, and argument types. It covers topics such as the definition and purpose of functions, types of functions, handling variable arguments, string immutability, and different string formatting methods. Each concept is presented with definitions, explanations, and code examples suitable for exam preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

? Functions in Python

The document provides detailed explanations and examples of various Python concepts, including functions, string manipulation, and argument types. It covers topics such as the definition and purpose of functions, types of functions, handling variable arguments, string immutability, and different string formatting methods. Each concept is presented with definitions, explanations, and code examples suitable for exam preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

some python questions are for my mid sem exam preparetion.

Answer it in details with necessary


code.

Sure Hardik 👍
Send me the Python questions one by one (or paste all together), and I will:

✅ Explain the concept clearly


✅ Give proper detailed answers (theory for exam writing)
✅ Provide necessary Python code
✅ Add example output
✅ Keep it suitable for mid-sem writing format
Since this is for your mid-sem exam preparation, I’ll structure answers in a way that you can directly
write them in exam.

Send the first question 📘💻

1. What are function in python? Explain their purpose?


2. What are the types of functions in python?
3. What are astric args and double astric args in python?
4. What is the difference between return and print in a function?
5. Can functions return multiple values? If yes then how.
6. What is default, positional and keyword argument in function?
7. What is recursive function and how do you create it?
8. What are string in python and how are they created?
9. What is the difference between single, double and triple quotes in python?
10. How are strings immutable in python? What does it mean?
11. How can you check the length of a string in python?
12. How to remove any leading and trailing white space from a string?
13. How do you convert a string to uppercase and lowercase in python?
14. How to replace all occurences of a substring in a string?
15. How to check if a string starts and ends with specified prefix and suffix?
16. How does string indexing works in python.
17. What is string slicing and how it is used provide example?
18. Does slicing modify the original string?
19. How would you reverse a string in python?
20. How can you extract a substring from a string?
21. What are the different ways to format string in python?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/16
Great Hardik 👍 This is very important for your mid-sem.
I’ll write answers in exam-ready format with explanation + examples + code + output.

🔹 FUNCTIONS IN PYTHON
1️⃣ What are functions in Python? Explain their purpose.
✅ Definition:
A function is a block of reusable code that performs a specific task. It is defined using the def keyword.

✅ Purpose:
Avoid code repetition (reusability)

Make program modular

Improve readability

Easy debugging and maintenance

✅ Syntax:
def function_name(parameters):
statement
return value

✅ Example:
def greet(name):
return "Hello " + name

print(greet("Hardik"))

Output:
Hello Hardik

2️⃣ Types of functions in Python


1. Built-in Functions – Predefined (e.g., print(), len(), type())

2. User-defined Functions – Created using def

3. Recursive Functions – Function calling itself

4. Lambda Functions – Anonymous one-line functions

Example:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/16
# Built-in
print(len("Python"))

# User-defined
def add(a, b):
return a + b

3️⃣ What are *args and **kwargs?


✅ *args (Asterisk Arguments)
Allows passing multiple positional arguments.
def add(*args):
return sum(args)

print(add(1, 2, 3, 4))

Output:
10

✅ **kwargs (Double Asterisk)


Allows passing multiple keyword arguments as dictionary.
def display(**kwargs):
print(kwargs)

display(name="Hardik", age=20)

Output:
{'name': 'Hardik', 'age': 20}

4️⃣ Difference between return and print


return print

Sends value back to caller Displays output


Ends function execution Does not stop execution

Can be stored in variable Cannot store output directly

Example:
def test():
print("Hello")
return "World"

x = test()
print(x)

5️⃣ Can functions return multiple values?


✅ Yes. Python returns multiple values as a tuple.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/16
def calculate(a, b):
return a+b, a-b

x, y = calculate(10, 5)
print(x, y)

Output:
15 5

6️⃣ Default, Positional and Keyword arguments


✅ Positional Argument
Order matters.
def greet(name, age):
print(name, age)

greet("Hardik", 20)

✅ Keyword Argument
Order does not matter.
greet(age=20, name="Hardik")

✅ Default Argument
Default value given in function.
def greet(name="Guest"):
print("Hello", name)

greet()

Output:
Hello Guest

7️⃣ What is a Recursive Function?


A function that calls itself.

Example (Factorial):
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)

print(factorial(5))

Output:
120

🔹 STRINGS IN PYTHON
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/16
8️⃣ What are strings and how created?
A string is a sequence of characters enclosed in quotes.
s1 = 'Hello'
s2 = "Python"
s3 = '''Multi line string'''

9️⃣ Difference between single, double and triple quotes


Single (' ') Double (" ") Triple (''' ''')
Same as double Same as single Multi-line string

Example:
print("He said 'Hello'")

🔟 How are strings immutable?


Immutable means strings cannot be changed after creation.
s = "Python"
s[0] = 'J' # Error

Instead:
s = "Python"
s = "J" + s[1:]
print(s)

Output:
Jython

1️⃣1️⃣ Length of string


s = "Python"
print(len(s))

Output:
6

1️⃣2️⃣ Remove leading & trailing spaces


Use strip()
s = " Hello "
print([Link]())

1️⃣3️⃣ Convert to uppercase & lowercase


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/16
s = "Python"
print([Link]())
print([Link]())

1️⃣4️⃣ Replace substring


s = "I like Java"
print([Link]("Java", "Python"))

1️⃣5️⃣ Check start and end


s = "Python Programming"

print([Link]("Python"))
print([Link]("Programming"))

1️⃣6️⃣ String Indexing


Index starts from 0.
s = "Python"
print(s[0]) # P
print(s[-1]) # n

1️⃣7️⃣ String Slicing


Syntax:
string[start:end:step]

Example:
s = "Python"
print(s[0:4]) # Pyth
print(s[::2]) # Pto

1️⃣8️⃣ Does slicing modify original string?


❌ No. It creates a new string.
s = "Python"
new_s = s[0:4]
print(s)

Original remains unchanged.

1️⃣9️⃣ Reverse a string


s = "Python"
print(s[::-1])

Output:
nohtyP

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/16
2️⃣0️⃣ Extract substring
Using slicing:
s = "Python Programming"
sub = s[0:6]
print(sub)

2️⃣1️⃣ Different ways to format string


1. Using % operator
name = "Hardik"
print("Hello %s" % name)

2. Using format()
print("Hello {}".format(name))

3. f-string (Best method)


print(f"Hello {name}")

✅ Tip for Your Mid-Sem


For theory questions:

First write definition


Then 2-3 points explanation

Then small code example

If you want, I can now give:

🔥 30 Important Viva Questions from these topics


📘 Short notes (2–3 marks format)
🧠 Practice MCQs
Tell me what you need next, Hardik 🙂

For theory questions:


First write definition
Then 2-3 points explanation
Then small code example

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/16
Perfect Hardik 👍
Now I will rewrite all answers in proper mid-sem theory format:

👉 1. Definition
👉 2–3 Explanation Points
👉 3. Small Code Example
🔹 FUNCTIONS IN PYTHON
1️⃣ What are functions in Python?
Definition:

A function in Python is a block of reusable code that performs a specific task and is defined using the def
keyword.

Explanation:

It helps in code reusability.

It makes the program modular and organized.

It reduces repetition of code.

Example:
def greet(name):
return "Hello " + name

print(greet("Hardik"))

2️⃣ Types of functions in Python


Definition:

Functions in Python are categorized based on how they are created and used.

Explanation:

Built-in Functions – Already defined (e.g., len(), print()).


User-defined Functions – Created using def.

Recursive Functions – Function calling itself.

Lambda Functions – Anonymous one-line functions.

Example:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/16
# Built-in
print(len("Python"))

# User-defined
def add(a, b):
return a + b

3️⃣ What are *args and **kwargs?


Definition:

*args and **kwargs are special parameters used to pass variable number of arguments to a function.

Explanation:

*args allows multiple positional arguments.


**kwargs allows multiple keyword arguments.

They make functions flexible.

Example:
def show(*args):
print(args)

show(1, 2, 3)

def info(**kwargs):
print(kwargs)

info(name="Hardik", age=20)

4️⃣ Difference between return and print


Definition:

return sends a value back to the caller function, while print() displays output on the screen.

Explanation:

return ends function execution.

return value can be stored in variable.

print() only displays output.

Example:
def test():
print("Hello")
return "World"

x = test()
print(x)

5️⃣ Can functions return multiple values?


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/16
Definition:

Yes, Python functions can return multiple values using tuples.

Explanation:

Multiple values are separated by commas.

Python automatically converts them into a tuple.


Values can be unpacked into variables.

Example:
def calc(a, b):
return a+b, a-b

x, y = calc(10, 5)
print(x, y)

6️⃣ Default, Positional and Keyword arguments


Definition:

Arguments are values passed to a function to perform operations.

Explanation:

Positional Argument – Order matters.

Keyword Argument – Passed using parameter name.

Default Argument – Has predefined value.

Example:
def greet(name="Guest"):
print("Hello", name)

greet("Hardik") # Positional
greet(name="Ram") # Keyword
greet() # Default

7️⃣ Recursive Function


Definition:

A recursive function is a function that calls itself.

Explanation:

Must have a base condition.

Used in problems like factorial, Fibonacci.

Simplifies complex problems.


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/16
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)

print(factorial(5))

🔹 STRINGS IN PYTHON
8️⃣ What are strings in Python?
Definition:

A string is a sequence of characters enclosed in quotes.

Explanation:

Can be created using single, double, or triple quotes.

Strings are immutable.

Stored as Unicode characters.

Example:
s = "Python"
print(s)

9️⃣ Difference between single, double and triple quotes


Definition:

Quotes are used to create strings in Python.

Explanation:

Single and double quotes work the same.

Triple quotes allow multi-line strings.


Useful for paragraphs or documentation.

Example:
s1 = 'Hello'
s2 = "World"
s3 = '''This is
multi-line'''

🔟 What does immutable mean in strings?


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/16
Definition:

Immutable means once a string is created, it cannot be changed.

Explanation:

Characters cannot be modified directly.


Any change creates a new string.

Ensures data safety.

Example:
s = "Python"
s = "J" + s[1:]
print(s)

1️⃣1️⃣ Length of a string


Definition:

Length means number of characters in a string.

Explanation:

Calculated using len() function.

Includes spaces.
Returns integer value.

Example:
s = "Python"
print(len(s))

1️⃣2️⃣ Remove leading and trailing spaces


Definition:

strip() removes extra spaces from beginning and end.

Explanation:

lstrip() removes left spaces.


rstrip() removes right spaces.
strip() removes both sides.

Example:
s = " Hello "
print([Link]())
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/16
1️⃣3️⃣ Convert string to uppercase and lowercase
Definition:

Case conversion changes letters between upper and lower case.

Explanation:

upper() converts to uppercase.


lower() converts to lowercase.

Does not modify original string.

Example:
s = "Python"
print([Link]())
print([Link]())

1️⃣4️⃣ Replace substring


Definition:

replace() method replaces one substring with another.

Explanation:

Takes old and new value.

Returns new string.


Original remains unchanged.

Example:
s = "I like Java"
print([Link]("Java", "Python"))

1️⃣5️⃣ Check start and end of string


Definition:

Used to check whether a string starts or ends with specific characters.

Explanation:

startswith() checks prefix.


endswith() checks suffix.
Returns True or False.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/16
Example:
s = "Python Programming"
print([Link]("Python"))
print([Link]("Programming"))

1️⃣6️⃣ String Indexing


Definition:

Indexing means accessing characters using position.

Explanation:

Index starts from 0.


Negative indexing starts from -1.

Used to access single character.

Example:
s = "Python"
print(s[0])
print(s[-1])

1️⃣7️⃣ String Slicing


Definition:

Slicing extracts a portion of a string.

Explanation:

Syntax: string[start:end]

End index is excluded.


Can use step value.

Example:
s = "Python"
print(s[0:4])
print(s[::-1])

1️⃣8️⃣ Does slicing modify original string?


Definition:

No, slicing does not modify the original string.

Explanation:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/16
Strings are immutable.
Slicing creates a new string.
Original remains unchanged.

Example:
s = "Python"
new = s[0:4]
print(s)

1️⃣9️⃣ Reverse a string


Definition:

Reversing means arranging characters in opposite order.

Explanation:

Done using slicing with step -1.


Creates new string.

Simple and efficient.

Example:
s = "Python"
print(s[::-1])

2️⃣0️⃣ Extract substring


Definition:

A substring is a part of a string.

Explanation:

Extracted using slicing.

Specify start and end index.


Returns new string.

Example:
s = "Python Programming"
print(s[0:6])

2️⃣1️⃣ Different ways to format string


Definition:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/16
String formatting inserts variables inside a string.

Explanation:

% operator (old method)


format() method
f-strings (modern and recommended)

Example:
name = "Hardik"

print("Hello %s" % name)


print("Hello {}".format(name))
print(f"Hello {name}")

If you want, I can now:

📘 Convert these into 2–3 marks short answers


🧠 Make important viva questions
🔥 Give expected 5–10 mark long answers
🎯 Provide practice programs for lab exam
Tell me what you need next 😊

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/16

You might also like