/
Python Basics and Recursion
Save to my account
Sign up
Python Basics and Recursion
Python Basics and Recursion
Study
1
Question
What is a variable in Python and give an example?
Answer
A named location for data; e.g., x = 10.
2
Question
Write code to assign sum of 5 and 10 to total in Python.
Answer
total = 5 + 10.
3
Question
What does the print() function do in Python?
Answer
Outputs data to the console for display.
4
Question
What is a list in Python? Provide an example.
Answer
An ordered, mutable collection; e.g., ['apple', 'banana', 'cherry'].
5
Question
Write code to append 'orange' to a list of fruits.
Answer
fruits.append('orange').
6
Question
Differentiate between a list and a tuple in Python.
Answer
Lists are mutable; tuples are immutable.
7
Question
Define a function in Python and give an example of squaring a number.
Answer
A reusable code block; e.g., def square(n): return n * n.
8
Question
How do you call a function in Python? Provide an example.
Answer
result = square(4).
9
Question
What is the purpose of the return statement in a Python function?
Answer
Sends back a result to the caller.
10
Question
Name three Python data types with examples.
Answer
int: x=10; float: pi=3.14; str: name='John'.
11
Question
Write a program to check if a number is even or odd.
Answer
Use num % 2 == 0 for even, else odd.
12
Question
What are conditional statements in Python? Give an example.
Answer
Decide actions; e.g., if x > 0: print('Positive').
13
Question
Explain what loops are and compare for and while loops with examples.
Answer
Repeat code; for iterates over sequences, while repeats on condition.
14
Question
Write a for loop to print numbers 1 to 5.
Answer
for i in range(1, 6): print(i).
15
Question
Write a recursive function to sum numbers 1 to n and call with n=5.
Answer
def recursive_sum(n): if n == 1: return 1 else: return n + recursive_sum(n - 1) Result: 15.
16
Question
What are base case and recursive case in recursion? Provide an example.
Answer
Base case stops recursion, e.g., if n==1: return 1; recursive case breaks problem down, e.g., return n + recursive_sum(n-1).
17
Question
Implement a recursive function to check if a string is a palindrome.
Answer
def is_palindrome(s): s = s.lower() if len(s) <= 1: return True elif s[0] != s[-1]: return False else: return is_palindrome(s[1:-1]).
18
Question
Generate a countdown list from n to 1 recursively and print it.
Answer
def countdown_list(n): if n == 0: return [] else: return [n] + countdown_list(n - 1) Result for 5: [5, 4, 3, 2, 1].