Made with ScholarlyMake flashcards like these from your own notes
Question:What is a variable in Python and give an example?
Answer:A named location for data; e.g., x = 10.
Question:Write code to assign sum of 5 and 10 to total in Python.
Answer:total = 5 + 10.
Question:What does the print() function do in Python?
Answer:Outputs data to the console for display.
Question:What is a list in Python? Provide an example.
Answer:An ordered, mutable collection; e.g., ['apple', 'banana', 'cherry'].
Question:Write code to append 'orange' to a list of fruits.
Answer:fruits.append('orange').
Question:Differentiate between a list and a tuple in Python.
Answer:Lists are mutable; tuples are immutable.
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.
Question:How do you call a function in Python? Provide an example.
Answer:result = square(4).
Question:What is the purpose of the return statement in a Python function?
Answer:Sends back a result to the caller.
Question:Name three Python data types with examples.
Answer:int: x=10; float: pi=3.14; str: name='John'.
Question:Write a program to check if a number is even or odd.
Answer:Use num % 2 == 0 for even, else odd.
Question:What are conditional statements in Python? Give an example.
Answer:Decide actions; e.g., if x > 0: print('Positive').
Question:Explain what loops are and compare for and while loops with examples.
Answer:Repeat code; for iterates over sequences, while repeats on condition.
Question:Write a for loop to print numbers 1 to 5.
Answer:for i in range(1, 6): print(i).
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.
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).
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]).
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].