Recursion and While Loops in Python

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What condition defines a recursive function in Python?

  • It defines a new class within the function body.
  • It calls another function within the same program.
  • It includes a loop to iterate over a set of instructions.
  • It calls itself to solve smaller instances of the same problem. (correct)

Which of the following is a key characteristic of the call stack in the context of recursive functions?

  • It stores function calls in a random order.
  • It follows a First In, First Out (FIFO) principle.
  • It follows a Last In, First Out (LIFO) principle. (correct)
  • It prioritizes function calls based on their execution time.

Consider a recursive function to calculate the factorial of a number. What is the base case typically?

  • When the number is even.
  • When the number is zero or one. (correct)
  • When the number is a large prime.
  • When the number is negative.

What is the purpose of a stack diagram in understanding recursion?

<p>To visualize how function calls are stored in memory. (D)</p> Signup and view all the answers

What happens when the base case is reached in a recursive function?

<p>The function returns a value, and the call stack starts to unwind. (B)</p> Signup and view all the answers

Which of the following will stop a while loop?

<p>The condition becoming False. (A)</p> Signup and view all the answers

What is the primary purpose of the break statement within a loop?

<p>To terminate the loop immediately. (D)</p> Signup and view all the answers

What is the function of the continue statement in a loop?

<p>It skips the rest of the current iteration and proceeds to the next. (D)</p> Signup and view all the answers

In the context of a while loop with an else block, when does the else block execute?

<p>Only if the loop completes normally without encountering a <code>break</code> statement. (A)</p> Signup and view all the answers

Which of the following data structures is best suited for representing a two-dimensional table in Python, offering both flexibility and ease of use?

<p>Lists of lists (B)</p> Signup and view all the answers

When using lists of lists to represent a table, how would you access the element in the second row and third column?

<p>table[1][2] (B)</p> Signup and view all the answers

What characteristic defines strings in Python?

<p>Immutable sequences of characters (B)</p> Signup and view all the answers

Which of the following is true about string indexing in Python?

<p>It starts from 0. (A)</p> Signup and view all the answers

What will the expression my_string[1:5] return if my_string = 'Hello, World!'?

<p>ello (B)</p> Signup and view all the answers

When comparing strings in Python, what is the basis for the comparison?

<p>Lexicographical order (A)</p> Signup and view all the answers

Flashcards

Recursion

A function calling itself to solve smaller instances of a problem.

Stack Diagram

A way to visualise function calls stored in memory during recursion, following LIFO.

While Loop

Executes a block of code repeatedly as long as a condition is true.

Break Statement

A statement that immediately terminates a loop.

Signup and view all the flashcards

Continue Statement

A statement that skips the rest of the loop's body for the current iteration.

Signup and view all the flashcards

Two-Dimensional Table

Data structure with rows and columns.

Signup and view all the flashcards

List of Lists

Simplest way to store a table in Python.

Signup and view all the flashcards

Tabulate

Python library to format tables in a readable way.

Signup and view all the flashcards

Dictionaries

Allow more structured data representation with column name access.

Signup and view all the flashcards

Pandas

A Python library useful for filtering, sorting, and analyzing data in tables.

Signup and view all the flashcards

NumPy

Python library ideal for numerical data and matrix operations in tables.

Signup and view all the flashcards

Python String

Collection of characters surrounded by quotes.

Signup and view all the flashcards

Strings are Immutable

Strings contents cannot be changed once created.

Signup and view all the flashcards

String Slices

Extracting parts of a string using string[start:end:step].

Signup and view all the flashcards

find() function

Returns the first index where a substring is found.

Signup and view all the flashcards

Study Notes

Recursion in Python

  • Recursion is when a function calls itself to solve a problem.
  • Useful for problems that can be divided into smaller subproblems like factorial computation, Fibonacci sequences, and tree traversals.
  • Recursive functions are a construct where a function can call itself.

Factorial Calculation

  • Base case: if n == 0 or n == 1, return 1
  • Recursive case: return n * factorial(n - 1)

Stack Diagrams for Recursive Functions

  • A stack diagram visualizes how function calls are stored in memory.
  • Call stack follows the Last In, First Out (LIFO) principle.
  • The last function call must finish before the previous one can continue.
  • After factorial(4) completes, the call stack is emptied.

The while Statement in Python

  • A while loop executes a block of code repeatedly as long as a condition is true.
  • It is used when the number of iterations is unknown in advance.
  • The loop runs while the condition is True, or stops if False.

Using break to Exit Early

  • The break statement stops the loop immediately.

Using continue to Skip an Iteration

  • The continue statement skips the rest of the loop's body for that iteration.

Infinite while Loop

  • An infinite loop runs forever until a break statement is executed.
  • The loop runs forever until the user types "exit".

while with else

  • The else block runs only if the loop is not exited using break.

Two-Dimensional Tables in Python

  • A 2D table is a data structure with rows and columns, similar to a spreadsheet or database table.
  • You can create and manipulate 2D tables using lists of lists, dictionaries, NumPy arrays, or pandas DataFrames.

Using Lists of Lists (Basic Approach)

  • A list of lists is the simplest way to store a table in Python.

Accessing Specific Elements

  • Elements can be accessed using their row and column indices.

Using Tabulate for Pretty Tables

  • The tabulate library helps format tables in a readable way.
  • pip install tabulate

Using Dictionaries (Access by Column Name)

  • Dictionaries allow more structured data representation.

Using Pandas for Powerful Table Operations

  • Pandas is useful for filtering, sorting, and analyzing table data.
  • pip install pandas

Advantages of Pandas

  • Pandas is useful for filtering, sorting, and analyzing table data.

Using NumPy for Numerical 2D Tables

  • NumPy is ideal for numerical data and matrix operations.
  • pip install numpy

Strings

  • A Python string is a collection of characters surrounded by single, double, or triple quotes.
  • The computer stores strings as a combination of 0s and 1s internally.
  • Each character is encoded in ASCII or Unicode.
  • Strings can be created using single, double, or triple quotes.
  • Strings are immutable, meaning their contents cannot be changed after creation.
  • Type of a string variable can be checked using type(str)

Strings Indexing and Splitting

  • Indexing of Python strings starts from 0.
  • An IndexError occurs when trying to access an index that doesn't exist.

Reassigning Strings

  • String objects do not support item assignment.
  • Strings are immutable in Python.
  • Can be reassigned completely to a new content.

Deleting the String

  • Strings are immutable, so characters cannot be deleted or removed from string.
  • An entire string can be deleted using the del keyword.

Length of a String

  • Use the len() function to find the number of characters in a string.

Traversing a String with a for Loop

  • Iterate through each character in a string using a for loop.

String Slices

  • Slicing extracts parts of a string using the syntax string[start:end:step].
  • Default start is 0, default end is length of string.
  • A reversed string can be obtained using a step of -1.

String Comparison

  • Strings are compared using relational operators (==, !=, <, >, <=, >=).
  • Comparison is based on lexicographical order (dictionary order).

Finding a Substring (find Function)

  • find(substring) returns the first index where the substring is found, otherwise -1.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser