Python: Conditional and Looping Statements

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which control structure is most appropriate for executing a block of code a specific number of times?

  • `for` loop (correct)
  • `try-except` block
  • `while` loop
  • `if-else` statement

What will be the output of the following Python code?

x = 5 while x > 0: print(x) x -= 1 else: print("Finished")

  • Finished
  • 5 4 3 2 1
  • Error
  • 5 4 3 2 1 Finished (correct)

What is the purpose of the break statement in a loop?

  • To skip the current iteration and continue with the next.
  • To execute the `else` block of the loop.
  • To terminate the loop prematurely. (correct)
  • To begin the loop from the start.

Which of the following methods can be used to convert a string to lowercase in Python?

<p><code>string.lower()</code> (A)</p> Signup and view all the answers

What is the result of the following Python expression?

"Python"[2:5]

<p><code>&quot;yth&quot;</code> (C)</p> Signup and view all the answers

Which string method is used to check if a string starts with a specific prefix?

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

How can you add an element to the end of a list in Python?

<p><code>list.append(element)</code> (A)</p> Signup and view all the answers

What is the output of the following code?

my_list = [1, 2, 3, 4, 5] my_list.remove(3) print(my_list)

<p><code>[1, 2, 4, 5]</code> (B)</p> Signup and view all the answers

Which list operation is used to combine two lists into one?

<p><code>list1.extend(list2)</code> (A)</p> Signup and view all the answers

Which of the following is a key difference between lists and tuples in Python?

<p>Lists are mutable, while tuples are immutable. (D)</p> Signup and view all the answers

How do you create an empty tuple in Python?

<p><code>my_tuple = ()</code> (C)</p> Signup and view all the answers

What happens when you try to modify an element of a tuple?

<p>A <code>TypeError</code> exception is raised. (A)</p> Signup and view all the answers

What is the primary purpose of a dictionary in Python?

<p>To store key-value pairs. (C)</p> Signup and view all the answers

How do you access a value in a dictionary, given its key?

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

What happens if you try to access a key that does not exist in a dictionary using square brackets?

<p>An error is raised. (B)</p> Signup and view all the answers

What will be the output of following code?

s = 'hello' s[1] = 'a' print(s)

<p>Error (C)</p> Signup and view all the answers

Which of the following is the correct way to create a dictionary in Python?

<p><code>my_dict = { 'key1' : 'value1', 'key2' : 'value2' }</code> (B)</p> Signup and view all the answers

What does the .get() method do when called on a dictionary with key that doesn't exist?

<p>Returns a default value specified in the <code>.get()</code> call, or <code>None</code> if there is no default value. (C)</p> Signup and view all the answers

Given the list numbers = [1, 2, 2, 3, 4, 4, 5], how would you remove the duplicate entries to obtain [1, 2, 3, 4, 5] using only list and set operations?

<p><code>list(set(numbers))</code> (C)</p> Signup and view all the answers

Which of the following loop statements is most appropriate to iterate through all the items in a dictionary?

<p><code>for key, value in my_dictionary.items():</code> (A)</p> Signup and view all the answers

Which statement about Python strings is correct?

<p>Strings are immutable sequences of characters. (D)</p> Signup and view all the answers

Consider the code:

def modify_list(my_list): my_list.append(4)

numbers = [1, 2, 3] modify_list(numbers) print(numbers)

What will be printed to the console?

<p><code>[1, 2, 3, 4]</code> (B)</p> Signup and view all the answers

Which of the following operations correctly checks if the key 'name' exists in the dictionary student?

<p><code>'name' in student.keys()</code> (C)</p> Signup and view all the answers

What is the correct way to get only the keys from a dictionary?

<p><code>dict.keys()</code> (B)</p> Signup and view all the answers

What is the output of this code?

my_tuple = (1, 2, [3, 4]) my_tuple[2][0] = 5 print(my_tuple)

<p>(1, 2, [5, 4]) (C)</p> Signup and view all the answers

Given the following code, what is the loop's output?

for i in range(2, 10, 2): print(i)

<p>2 4 6 8 (A)</p> Signup and view all the answers

Given my_string = "Hello, World!", what would my_string[-5:] evaluate to?

<p><code>World!</code> (A)</p> Signup and view all the answers

What is the result of the expression [x**2 for x in range(5) if x % 2 == 0]?

<p><code>[0, 4, 16]</code> (A)</p> Signup and view all the answers

If you have my_dict = {'a': 1, 'b': 2}, what is the result of my_dict.update({'c': 3, 'a': 4})?

<p><code>{'a': 4, 'b': 2, 'c': 3}</code> (D)</p> Signup and view all the answers

Signup and view all the answers

Flashcards

Conditional Statement

A statement that executes a block of code only if a certain condition is true.

Looping Statement

A statement that repeatedly executes a block of code as long as a certain condition is true.

String

A sequence of characters.

List

An ordered, mutable collection of items.

Signup and view all the flashcards

Tuple

An ordered, immutable collection of items.

Signup and view all the flashcards

Dictionary

A collection of key-value pairs.

Signup and view all the flashcards

Simplest Conditional

The 'if' statement.

Signup and view all the flashcards

'elif' statement

Allows for multiple conditions to be checked in sequence.

Signup and view all the flashcards

'else' statement

Executes if none of the preceding 'if' or 'elif' conditions are true.

Signup and view all the flashcards

'while' loop

Repeatedly executes a block of code while a condition is true.

Signup and view all the flashcards

'for' loop

Iterates over a sequence (like a list or string).

Signup and view all the flashcards

'continue' statement

Stops the current iteration and continues with the next.

Signup and view all the flashcards

'break' statement

Terminates the loop entirely.

Signup and view all the flashcards

String Literal

A sequence of characters enclosed in single or double quotes.

Signup and view all the flashcards

String Concatenation

Joining two or more strings together.

Signup and view all the flashcards

String Slicing

Extracting a portion of a string.

Signup and view all the flashcards

'len()' function (strings)

Finding the length of a string.

Signup and view all the flashcards

String Case Conversion

Changing the case of a string (upper or lower).

Signup and view all the flashcards

Lists : changeable

Mutable.

Signup and view all the flashcards

Lists : Indexes matter

Ordered.

Signup and view all the flashcards

Lists

Enclosed in square brackets [].

Signup and view all the flashcards

list.append()

Used to add an item to the end of a list.

Signup and view all the flashcards

list.remove()

Used to remove an item from a list.

Signup and view all the flashcards

list.insert()

Used to insert an item at a specific position in a list.

Signup and view all the flashcards

Tuples : unchangeable

Immutable.

Signup and view all the flashcards

Tuples : Indexes matter

Ordered.

Signup and view all the flashcards

Tuples

Enclosed in parentheses ().

Signup and view all the flashcards

Dictionaries : Key-Value

Pairs of keys and values.

Signup and view all the flashcards

Dictionaries : Chaneable

Mutable.

Signup and view all the flashcards

Dictionaries

Enclosed in curly braces {}.

Signup and view all the flashcards

Study Notes

  • Python offers conditional statements (if, elif, else) to execute code blocks based on conditions.
  • Looping constructs (for, while) facilitate repeated execution of code blocks.

Conditional Statements

  • if statement evaluates a condition; if true, the indented code block is executed.
  • elif (else if) allows checking multiple conditions sequentially.
  • else block executes if none of the preceding if or elif conditions are true.
  • Conditions are boolean expressions that evaluate to either True or False.
  • Comparison operators (e.g., ==, !=, >, <) are used to form conditions.
  • Logical operators (and, or, not) combine or negate conditions.

Looping Statements

  • for loop iterates over a sequence (e.g., list, string, range) or other iterable.
  • while loop repeatedly executes a block as long as a condition remains true.
  • break statement exits the loop prematurely.
  • continue statement skips the current iteration and proceeds to the next.
  • range() function generates a sequence of numbers for for loop iteration.
  • Nested loops are possible, where one loop is placed inside another.

Strings in Python

  • Strings are immutable sequences of characters.
  • Strings are defined using single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or """...""") for multiline strings.
  • Individual characters can be accessed using indexing (e.g., string[0]).
  • Slicing extracts a portion of a string (e.g., string[1:5]).
  • String concatenation joins strings using the + operator.
  • String methods provide various functionalities, like upper(), lower(), strip(), replace(), find(), and split().
  • String formatting uses placeholders to insert values into strings (e.g., f"The value is {value}").
  • Escape sequences represent special characters (e.g., \n for newline, \t for tab).

Lists in Python

  • Lists are mutable, ordered sequences of items.
  • Lists are defined using square brackets [...].
  • List items can be of different data types.
  • Items can be accessed by index.
  • Lists can be sliced.
  • Lists are mutable; items can be added, removed, or modified.
  • Methods like append(), insert(), remove(), pop(), sort(), and reverse() modify lists.
  • len() returns the number of items in a list.
  • List comprehension provides a concise way to create new lists based on existing iterables.

Tuples in Python

  • Tuples are immutable, ordered sequences of items.
  • Tuples are defined using parentheses (...).
  • Tuple items can be of different data types.
  • Items are accessed by index.
  • Tuples can be sliced.
  • Tuples are immutable; items cannot be changed after creation.
  • Tuples generally consume less memory than lists.
  • Methods like count() and index() are available for tuples.
  • Tuples are often used to represent fixed collections of items.
  • Tuple packing and unpacking allow assigning multiple values at once.

Dictionaries in Python

  • Dictionaries are mutable, unordered collections of key-value pairs.
  • Dictionaries are defined using curly braces {...}.
  • Keys must be unique and immutable (e.g., strings, numbers, tuples).
  • Values can be of any data type.
  • Items are accessed by key (e.g., dictionary["key"]).
  • Methods like keys(), values(), items(), get(), update(), and pop() are used to manipulate dictionaries.
  • len() returns the number of key-value pairs in a dictionary.
  • Dictionary comprehension offers a concise way to create dictionaries.
  • Dictionaries are useful for representing mappings and associations between data.

Studying That Suits You

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

Quiz Team

More Like This

Python Conditional and Looping Constructs Quiz
10 questions
PHP Conditional Statements Quiz
17 questions
Conditional Statements Flashcards
8 questions
Use Quizgecko on...
Browser
Browser