[Go to site: main page, start]

0% found this document useful (0 votes)
6 views8 pages

Python Basics: Even/Odd, Swapping, Data Types

The document provides Python programs for checking if a number is even or odd and for swapping values of two variables. It also explains data types, focusing on tuples, which are immutable and ordered collections. Additionally, it discusses loop control statements in Python, such as 'break', which allows for premature termination of loops.

Uploaded by

tamahesh411
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)
6 views8 pages

Python Basics: Even/Odd, Swapping, Data Types

The document provides Python programs for checking if a number is even or odd and for swapping values of two variables. It also explains data types, focusing on tuples, which are immutable and ordered collections. Additionally, it discusses loop control statements in Python, such as 'break', which allows for premature termination of loops.

Uploaded by

tamahesh411
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

1.

Python Program to Check Whether a Number defined by enclosing the items (elements) in
is Even or Odd parentheses ().
num = int(input("Enter a number: ")) Key Characteristics:
# Checking even or odd using modulus operator 1. Ordered: The items have a defined order, and
if num % 2 == 0: that order will not change.
print(f"{num} is Even") 2. Immutable: This is the most important feature.
else: Once a tuple is created, its elements cannot be
print(f"{num} is Odd") added, removed, or changed. This makes
Explanation: tuples fixed.
• % (modulus) gives the remainder. 3. Indexable & Sliceable: You can access
• If a number divided by 2 gives remainder elements by their index (e.g., my_tuple[0]) or
0, it is even; otherwise, it is odd. get a subset of elements using slicing
2. Python Program to Swap Values of Two (e.g., my_tuple[1:3]).
Variables Using a Third Variable Why Use a Tuple?
# Taking input from the user • Faster than Lists: Due to their immutability,
a = input("Enter first value (a): ") tuples can be processed faster than lists.
b = input("Enter second value (b): ") • Write-Protection: Immutability provides a
print(f"\nBefore swapping: a = {a}, b = {b}") guarantee that the data will remain constant and
# Swapping using a third variable safe from accidental modification.
temp = a # store a in temp • Valid Dictionary Key: Because they are
a=b # assign b to a immutable, tuples can be used as keys in a
b = temp # assign temp (old a) to b dictionary, whereas lists cannot.
print(f"After swapping: a = {a}, b = {b}") Example:
3. Short Note on Data Types # Creating a tuple
A data type is a fundamental concept in my_tuple = (10, "hello", 45.2)
programming that defines the type of data a variable print(my_tuple[1]) # Output: hello
can hold and the operations that can be performed on Loop Control Statements in Python
it. It essentially tells the computer how to interpret Loop control statements are used to change the
and manipulate a piece of data. normal flow of execution in a loop (like
Key Purposes: a for or while loop). They give you more precise
1. Memory Allocation: It determines how much control over how your loops operate. Python
memory space is allocated for a variable (e.g., provides three main loop control
an integer typically uses less memory than a statements: break, continue, and pass.
floating-point number). 1. break Statement
2. Operation Specification: It defines what The break statement is used to terminate or exit the
operations are valid (e.g., you can add two loop prematurely, before it has looped through all its
integers, but it doesn't make sense to add an items. When a break statement is encountered inside
integer to a text string). a loop, the loop is immediately stopped, and the
3. Data Integrity: It helps prevent errors by program continues with the code following the loop.
ensuring data is used consistently (e.g., you Example:
can't accidentally store a name in a variable # Stop the loop when the number 5 is found
meant for a date). numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Common Examples: for num in numbers:
• Integer (int): Whole numbers (e.g., -5, 0, 42). if num == 5:
• Floating-Point (float): Decimal numbers print("Number 5 found! Stopping the loop.")
(e.g., 3.14, -0.001). break # Exit the loop immediately
• String (str): Sequence of characters print(f"Current number is: {num}")
representing text (e.g., "Hello", 'A'). print("Loop has ended.")
• Boolean (bool): Represents logical # Output:
values, True or False. # Current number is: 1
• List (list): An ordered, mutable (changeable) # Current number is: 2
collection of items. # Current number is: 3
4. Short Note on Tuple # Current number is: 4
A tuple is a fundamental data structure in Python # Number 5 found! Stopping the loop.
used to store an ordered collection of items. It is # Loop has ended.
1. Python Program to Check Whether a Number defined by enclosing the items (elements) in
is Even or Odd parentheses ().
num = int(input("Enter a number: ")) Key Characteristics:
# Checking even or odd using modulus operator 4. Ordered: The items have a defined order, and
if num % 2 == 0: that order will not change.
print(f"{num} is Even") 5. Immutable: This is the most important feature.
else: Once a tuple is created, its elements cannot be
print(f"{num} is Odd") added, removed, or changed. This makes
Explanation: tuples fixed.
• % (modulus) gives the remainder. 6. Indexable & Sliceable: You can access
• If a number divided by 2 gives remainder elements by their index (e.g., my_tuple[0]) or
0, it is even; otherwise, it is odd. get a subset of elements using slicing
2. Python Program to Swap Values of Two (e.g., my_tuple[1:3]).
Variables Using a Third Variable Why Use a Tuple?
# Taking input from the user • Faster than Lists: Due to their immutability,
a = input("Enter first value (a): ") tuples can be processed faster than lists.
b = input("Enter second value (b): ") • Write-Protection: Immutability provides a
print(f"\nBefore swapping: a = {a}, b = {b}") guarantee that the data will remain constant and
# Swapping using a third variable safe from accidental modification.
temp = a # store a in temp • Valid Dictionary Key: Because they are
a=b # assign b to a immutable, tuples can be used as keys in a
b = temp # assign temp (old a) to b dictionary, whereas lists cannot.
print(f"After swapping: a = {a}, b = {b}") Example:
3. Short Note on Data Types # Creating a tuple
A data type is a fundamental concept in my_tuple = (10, "hello", 45.2)
programming that defines the type of data a variable print(my_tuple[1]) # Output: hello
can hold and the operations that can be performed on Loop Control Statements in Python
it. It essentially tells the computer how to interpret Loop control statements are used to change the
and manipulate a piece of data. normal flow of execution in a loop (like
Key Purposes: a for or while loop). They give you more precise
4. Memory Allocation: It determines how much control over how your loops operate. Python
memory space is allocated for a variable (e.g., provides three main loop control
an integer typically uses less memory than a statements: break, continue, and pass.
floating-point number). 1. break Statement
5. Operation Specification: It defines what The break statement is used to terminate or exit the
operations are valid (e.g., you can add two loop prematurely, before it has looped through all its
integers, but it doesn't make sense to add an items. When a break statement is encountered inside
integer to a text string). a loop, the loop is immediately stopped, and the
6. Data Integrity: It helps prevent errors by program continues with the code following the loop.
ensuring data is used consistently (e.g., you Example:
can't accidentally store a name in a variable # Stop the loop when the number 5 is found
meant for a date). numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Common Examples: for num in numbers:
• Integer (int): Whole numbers (e.g., -5, 0, 42). if num == 5:
• Floating-Point (float): Decimal numbers print("Number 5 found! Stopping the loop.")
(e.g., 3.14, -0.001). break # Exit the loop immediately
• String (str): Sequence of characters print(f"Current number is: {num}")
representing text (e.g., "Hello", 'A'). print("Loop has ended.")
• Boolean (bool): Represents logical # Output:
values, True or False. # Current number is: 1
• List (list): An ordered, mutable (changeable) # Current number is: 2
collection of items. # Current number is: 3
4. Short Note on Tuple # Current number is: 4
A tuple is a fundamental data structure in Python # Number 5 found! Stopping the loop.
used to store an ordered collection of items. It is # Loop has ended.
1. Python Program to Check Whether a Number defined by enclosing the items (elements) in
is Even or Odd parentheses ().
num = int(input("Enter a number: ")) Key Characteristics:
# Checking even or odd using modulus operator 7. Ordered: The items have a defined order, and
if num % 2 == 0: that order will not change.
print(f"{num} is Even") 8. Immutable: This is the most important feature.
else: Once a tuple is created, its elements cannot be
print(f"{num} is Odd") added, removed, or changed. This makes
Explanation: tuples fixed.
• % (modulus) gives the remainder. 9. Indexable & Sliceable: You can access
• If a number divided by 2 gives remainder elements by their index (e.g., my_tuple[0]) or
0, it is even; otherwise, it is odd. get a subset of elements using slicing
2. Python Program to Swap Values of Two (e.g., my_tuple[1:3]).
Variables Using a Third Variable Why Use a Tuple?
# Taking input from the user • Faster than Lists: Due to their immutability,
a = input("Enter first value (a): ") tuples can be processed faster than lists.
b = input("Enter second value (b): ") • Write-Protection: Immutability provides a
print(f"\nBefore swapping: a = {a}, b = {b}") guarantee that the data will remain constant and
# Swapping using a third variable safe from accidental modification.
temp = a # store a in temp • Valid Dictionary Key: Because they are
a=b # assign b to a immutable, tuples can be used as keys in a
b = temp # assign temp (old a) to b dictionary, whereas lists cannot.
print(f"After swapping: a = {a}, b = {b}") Example:
3. Short Note on Data Types # Creating a tuple
A data type is a fundamental concept in my_tuple = (10, "hello", 45.2)
programming that defines the type of data a variable print(my_tuple[1]) # Output: hello
can hold and the operations that can be performed on Loop Control Statements in Python
it. It essentially tells the computer how to interpret Loop control statements are used to change the
and manipulate a piece of data. normal flow of execution in a loop (like
Key Purposes: a for or while loop). They give you more precise
7. Memory Allocation: It determines how much control over how your loops operate. Python
memory space is allocated for a variable (e.g., provides three main loop control
an integer typically uses less memory than a statements: break, continue, and pass.
floating-point number). 1. break Statement
8. Operation Specification: It defines what The break statement is used to terminate or exit the
operations are valid (e.g., you can add two loop prematurely, before it has looped through all its
integers, but it doesn't make sense to add an items. When a break statement is encountered inside
integer to a text string). a loop, the loop is immediately stopped, and the
9. Data Integrity: It helps prevent errors by program continues with the code following the loop.
ensuring data is used consistently (e.g., you Example:
can't accidentally store a name in a variable # Stop the loop when the number 5 is found
meant for a date). numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Common Examples: for num in numbers:
• Integer (int): Whole numbers (e.g., -5, 0, 42). if num == 5:
• Floating-Point (float): Decimal numbers print("Number 5 found! Stopping the loop.")
(e.g., 3.14, -0.001). break # Exit the loop immediately
• String (str): Sequence of characters print(f"Current number is: {num}")
representing text (e.g., "Hello", 'A'). print("Loop has ended.")
• Boolean (bool): Represents logical # Output:
values, True or False. # Current number is: 1
• List (list): An ordered, mutable (changeable) # Current number is: 2
collection of items. # Current number is: 3
4. Short Note on Tuple # Current number is: 4
A tuple is a fundamental data structure in Python # Number 5 found! Stopping the loop.
used to store an ordered collection of items. It is # Loop has ended.
1. Python Program to Check Whether a Number defined by enclosing the items (elements) in
is Even or Odd parentheses ().
num = int(input("Enter a number: ")) Key Characteristics:
# Checking even or odd using modulus operator 10. Ordered: The items have a defined order, and
if num % 2 == 0: that order will not change.
print(f"{num} is Even") 11. Immutable: This is the most important feature.
else: Once a tuple is created, its elements cannot be
print(f"{num} is Odd") added, removed, or changed. This makes
Explanation: tuples fixed.
• % (modulus) gives the remainder. 12. Indexable & Sliceable: You can access
• If a number divided by 2 gives remainder elements by their index (e.g., my_tuple[0]) or
0, it is even; otherwise, it is odd. get a subset of elements using slicing
2. Python Program to Swap Values of Two (e.g., my_tuple[1:3]).
Variables Using a Third Variable Why Use a Tuple?
# Taking input from the user • Faster than Lists: Due to their immutability,
a = input("Enter first value (a): ") tuples can be processed faster than lists.
b = input("Enter second value (b): ") • Write-Protection: Immutability provides a
print(f"\nBefore swapping: a = {a}, b = {b}") guarantee that the data will remain constant and
# Swapping using a third variable safe from accidental modification.
temp = a # store a in temp • Valid Dictionary Key: Because they are
a=b # assign b to a immutable, tuples can be used as keys in a
b = temp # assign temp (old a) to b dictionary, whereas lists cannot.
print(f"After swapping: a = {a}, b = {b}") Example:
3. Short Note on Data Types # Creating a tuple
A data type is a fundamental concept in my_tuple = (10, "hello", 45.2)
programming that defines the type of data a variable print(my_tuple[1]) # Output: hello
can hold and the operations that can be performed on Loop Control Statements in Python
it. It essentially tells the computer how to interpret Loop control statements are used to change the
and manipulate a piece of data. normal flow of execution in a loop (like
Key Purposes: a for or while loop). They give you more precise
10. Memory Allocation: It determines how much control over how your loops operate. Python
memory space is allocated for a variable (e.g., provides three main loop control
an integer typically uses less memory than a statements: break, continue, and pass.
floating-point number). 1. break Statement
11. Operation Specification: It defines what The break statement is used to terminate or exit the
operations are valid (e.g., you can add two loop prematurely, before it has looped through all its
integers, but it doesn't make sense to add an items. When a break statement is encountered inside
integer to a text string). a loop, the loop is immediately stopped, and the
12. Data Integrity: It helps prevent errors by program continues with the code following the loop.
ensuring data is used consistently (e.g., you Example:
can't accidentally store a name in a variable # Stop the loop when the number 5 is found
meant for a date). numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Common Examples: for num in numbers:
• Integer (int): Whole numbers (e.g., -5, 0, 42). if num == 5:
• Floating-Point (float): Decimal numbers print("Number 5 found! Stopping the loop.")
(e.g., 3.14, -0.001). break # Exit the loop immediately
• String (str): Sequence of characters print(f"Current number is: {num}")
representing text (e.g., "Hello", 'A'). print("Loop has ended.")
• Boolean (bool): Represents logical # Output:
values, True or False. # Current number is: 1
• List (list): An ordered, mutable (changeable) # Current number is: 2
collection of items. # Current number is: 3
4. Short Note on Tuple # Current number is: 4
A tuple is a fundamental data structure in Python # Number 5 found! Stopping the loop.
used to store an ordered collection of items. It is # Loop has ended.
2. continue Statement }
The continue statement is used to skip the current # Access elements using keys
iteration of the loop and move directly to the next print(student["name"]) # Output: Alice
one. It does not terminate the loop; it just "jumps print(student["age"]) # Output: 21
over" the rest of the code inside the loop for the # This will cause a KeyError because 'grade' key
current value and continues with the next value. doesn't exist
Example: # print(student["grade"])
# Print only the odd numbers by skipping even 2. Using the .get() Method (Safer Method)
numbers This method is safer than using square brackets. You
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] specify the key as the first argument. If the key is
for num in numbers: found, it returns the corresponding value. If the key
if num % 2 == 0: # Check if the number is even is not found, it returns None by default, or a custom
continue # Skip the rest of the code for this default value you specify.
iteration Syntax: [Link](key, default_value)
print(f"Odd number: {num}") Example:
print("Loop has ended.") student = {"name": "Alice", "age": 21}
# Output: # Odd number: 1 # Access an existing key
# Odd number: 3 # Odd number: 5 name = [Link]("name")
# Odd number: 7 # Odd number: 9 print(name) # Output: Alice
# Loop has ended. # Access a non-existing key (returns None by
3. pass Statement default)
The pass statement is a null operation or grade = [Link]("grade")
a placeholder. It does nothing when executed. It is print(grade) # Output: None
used when a statement is syntactically required (to grade = [Link]("grade", "N/A") # "N/A" is the
avoid an indentation error) but you don't want any default value
code to run. print(grade) # Output: N/A
Example: 3. Using the .setdefault() Method (Access & Set)
# Using pass in an empty function or a condition This method is similar to .get(), but with an added
for num in range(5): behavior: if the key is not found, it not only returns
if num == 3: your default value but also inserts the new key with
pass # Do nothing, just a placeholder for future that default value into the dictionary.
code Syntax: [Link](key, default_value)
else: Example:
print(f"Number is: {num}") student = {"name": "Alice", "age": 21}
print("Loop has ended.") # Key exists - behaves like .get()
# Output: age = [Link]("age", 0)
# Number is: 0 # Number is: 1 print(age) # Output: 21
# Number is: 2 # Number is: 4 print(student) # Output: {'name': 'Alice', 'age': 21}
# Loop has ended. grade = [Link]("grade", "A")
6. How to access dictionary elements with example print(grade) # Output: A
in python print(student) # Output: {'name': 'Alice', 'age': 21,
What is a Dictionary? 'grade': 'A'}
A dictionary in Python is an unordered collection 4. Accessing All Elements (Keys, Values, Items)
of key-value pairs. Each element is accessed by You can also access all keys, values, or key-value
its key, not by an index. Keys must be unique and pairs at once to loop through them.
immutable (like strings, numbers, or tuples). Example:
Methods to Access Dictionary Elements student = {"name": "Bob", "age": 22, "major":
1. Using Square Brackets [key] (Most Common) "Physics"}
This is the most straightforward method. You print([Link]()) # Output: dict_keys(['name',
specify the key inside square brackets. 'age', 'major'])
Example: print([Link]()) # Output: dict_values(['Bob',
# Create a dictionary 22, 'Physics'])
student = { for key, value in [Link]():
"name": "Alice", print(f"{key}: {value}")
"age": 21, # Output: # name: Bob
"major": "Computer Science" # age: 22 # major: Physics
2. continue Statement }
The continue statement is used to skip the current # Access elements using keys
iteration of the loop and move directly to the next print(student["name"]) # Output: Alice
one. It does not terminate the loop; it just "jumps print(student["age"]) # Output: 21
over" the rest of the code inside the loop for the # This will cause a KeyError because 'grade' key
current value and continues with the next value. doesn't exist
Example: # print(student["grade"])
# Print only the odd numbers by skipping even 2. Using the .get() Method (Safer Method)
numbers This method is safer than using square brackets. You
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] specify the key as the first argument. If the key is
for num in numbers: found, it returns the corresponding value. If the key
if num % 2 == 0: # Check if the number is even is not found, it returns None by default, or a custom
continue # Skip the rest of the code for this default value you specify.
iteration Syntax: [Link](key, default_value)
print(f"Odd number: {num}") Example:
print("Loop has ended.") student = {"name": "Alice", "age": 21}
# Output: # Odd number: 1 # Access an existing key
# Odd number: 3 # Odd number: 5 name = [Link]("name")
# Odd number: 7 # Odd number: 9 print(name) # Output: Alice
# Loop has ended. # Access a non-existing key (returns None by
3. pass Statement default)
The pass statement is a null operation or grade = [Link]("grade")
a placeholder. It does nothing when executed. It is print(grade) # Output: None
used when a statement is syntactically required (to grade = [Link]("grade", "N/A") # "N/A" is the
avoid an indentation error) but you don't want any default value
code to run. print(grade) # Output: N/A
Example: 3. Using the .setdefault() Method (Access & Set)
# Using pass in an empty function or a condition This method is similar to .get(), but with an added
for num in range(5): behavior: if the key is not found, it not only returns
if num == 3: your default value but also inserts the new key with
pass # Do nothing, just a placeholder for future that default value into the dictionary.
code Syntax: [Link](key, default_value)
else: Example:
print(f"Number is: {num}") student = {"name": "Alice", "age": 21}
print("Loop has ended.") # Key exists - behaves like .get()
# Output: age = [Link]("age", 0)
# Number is: 0 # Number is: 1 print(age) # Output: 21
# Number is: 2 # Number is: 4 print(student) # Output: {'name': 'Alice', 'age': 21}
# Loop has ended. grade = [Link]("grade", "A")
6. How to access dictionary elements with example print(grade) # Output: A
in python print(student) # Output: {'name': 'Alice', 'age': 21,
What is a Dictionary? 'grade': 'A'}
A dictionary in Python is an unordered collection 4. Accessing All Elements (Keys, Values, Items)
of key-value pairs. Each element is accessed by You can also access all keys, values, or key-value
its key, not by an index. Keys must be unique and pairs at once to loop through them.
immutable (like strings, numbers, or tuples). Example:
Methods to Access Dictionary Elements student = {"name": "Bob", "age": 22, "major":
1. Using Square Brackets [key] (Most Common) "Physics"}
This is the most straightforward method. You print([Link]()) # Output: dict_keys(['name',
specify the key inside square brackets. 'age', 'major'])
Example: print([Link]()) # Output: dict_values(['Bob',
# Create a dictionary 22, 'Physics'])
student = { for key, value in [Link]():
"name": "Alice", print(f"{key}: {value}")
"age": 21, # Output: # name: Bob
"major": "Computer Science" # age: 22 # major: Physics
2. continue Statement }
The continue statement is used to skip the current # Access elements using keys
iteration of the loop and move directly to the next print(student["name"]) # Output: Alice
one. It does not terminate the loop; it just "jumps print(student["age"]) # Output: 21
over" the rest of the code inside the loop for the # This will cause a KeyError because 'grade' key
current value and continues with the next value. doesn't exist
Example: # print(student["grade"])
# Print only the odd numbers by skipping even 2. Using the .get() Method (Safer Method)
numbers This method is safer than using square brackets. You
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] specify the key as the first argument. If the key is
for num in numbers: found, it returns the corresponding value. If the key
if num % 2 == 0: # Check if the number is even is not found, it returns None by default, or a custom
continue # Skip the rest of the code for this default value you specify.
iteration Syntax: [Link](key, default_value)
print(f"Odd number: {num}") Example:
print("Loop has ended.") student = {"name": "Alice", "age": 21}
# Output: # Odd number: 1 # Access an existing key
# Odd number: 3 # Odd number: 5 name = [Link]("name")
# Odd number: 7 # Odd number: 9 print(name) # Output: Alice
# Loop has ended. # Access a non-existing key (returns None by
3. pass Statement default)
The pass statement is a null operation or grade = [Link]("grade")
a placeholder. It does nothing when executed. It is print(grade) # Output: None
used when a statement is syntactically required (to grade = [Link]("grade", "N/A") # "N/A" is the
avoid an indentation error) but you don't want any default value
code to run. print(grade) # Output: N/A
Example: 3. Using the .setdefault() Method (Access & Set)
# Using pass in an empty function or a condition This method is similar to .get(), but with an added
for num in range(5): behavior: if the key is not found, it not only returns
if num == 3: your default value but also inserts the new key with
pass # Do nothing, just a placeholder for future that default value into the dictionary.
code Syntax: [Link](key, default_value)
else: Example:
print(f"Number is: {num}") student = {"name": "Alice", "age": 21}
print("Loop has ended.") # Key exists - behaves like .get()
# Output: age = [Link]("age", 0)
# Number is: 0 # Number is: 1 print(age) # Output: 21
# Number is: 2 # Number is: 4 print(student) # Output: {'name': 'Alice', 'age': 21}
# Loop has ended. grade = [Link]("grade", "A")
6. How to access dictionary elements with example print(grade) # Output: A
in python print(student) # Output: {'name': 'Alice', 'age': 21,
What is a Dictionary? 'grade': 'A'}
A dictionary in Python is an unordered collection 4. Accessing All Elements (Keys, Values, Items)
of key-value pairs. Each element is accessed by You can also access all keys, values, or key-value
its key, not by an index. Keys must be unique and pairs at once to loop through them.
immutable (like strings, numbers, or tuples). Example:
Methods to Access Dictionary Elements student = {"name": "Bob", "age": 22, "major":
1. Using Square Brackets [key] (Most Common) "Physics"}
This is the most straightforward method. You print([Link]()) # Output: dict_keys(['name',
specify the key inside square brackets. 'age', 'major'])
Example: print([Link]()) # Output: dict_values(['Bob',
# Create a dictionary 22, 'Physics'])
student = { for key, value in [Link]():
"name": "Alice", print(f"{key}: {value}")
"age": 21, # Output: # name: Bob
"major": "Computer Science" # age: 22 # major: Physics
2. continue Statement }
The continue statement is used to skip the current # Access elements using keys
iteration of the loop and move directly to the next print(student["name"]) # Output: Alice
one. It does not terminate the loop; it just "jumps print(student["age"]) # Output: 21
over" the rest of the code inside the loop for the # This will cause a KeyError because 'grade' key
current value and continues with the next value. doesn't exist
Example: # print(student["grade"])
# Print only the odd numbers by skipping even 2. Using the .get() Method (Safer Method)
numbers This method is safer than using square brackets. You
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] specify the key as the first argument. If the key is
for num in numbers: found, it returns the corresponding value. If the key
if num % 2 == 0: # Check if the number is even is not found, it returns None by default, or a custom
continue # Skip the rest of the code for this default value you specify.
iteration Syntax: [Link](key, default_value)
print(f"Odd number: {num}") Example:
print("Loop has ended.") student = {"name": "Alice", "age": 21}
# Output: # Odd number: 1 # Access an existing key
# Odd number: 3 # Odd number: 5 name = [Link]("name")
# Odd number: 7 # Odd number: 9 print(name) # Output: Alice
# Loop has ended. # Access a non-existing key (returns None by
3. pass Statement default)
The pass statement is a null operation or grade = [Link]("grade")
a placeholder. It does nothing when executed. It is print(grade) # Output: None
used when a statement is syntactically required (to grade = [Link]("grade", "N/A") # "N/A" is the
avoid an indentation error) but you don't want any default value
code to run. print(grade) # Output: N/A
Example: 3. Using the .setdefault() Method (Access & Set)
# Using pass in an empty function or a condition This method is similar to .get(), but with an added
for num in range(5): behavior: if the key is not found, it not only returns
if num == 3: your default value but also inserts the new key with
pass # Do nothing, just a placeholder for future that default value into the dictionary.
code Syntax: [Link](key, default_value)
else: Example:
print(f"Number is: {num}") student = {"name": "Alice", "age": 21}
print("Loop has ended.") # Key exists - behaves like .get()
# Output: age = [Link]("age", 0)
# Number is: 0 # Number is: 1 print(age) # Output: 21
# Number is: 2 # Number is: 4 print(student) # Output: {'name': 'Alice', 'age': 21}
# Loop has ended. grade = [Link]("grade", "A")
6. How to access dictionary elements with example print(grade) # Output: A
in python print(student) # Output: {'name': 'Alice', 'age': 21,
What is a Dictionary? 'grade': 'A'}
A dictionary in Python is an unordered collection 4. Accessing All Elements (Keys, Values, Items)
of key-value pairs. Each element is accessed by You can also access all keys, values, or key-value
its key, not by an index. Keys must be unique and pairs at once to loop through them.
immutable (like strings, numbers, or tuples). Example:
Methods to Access Dictionary Elements student = {"name": "Bob", "age": 22, "major":
1. Using Square Brackets [key] (Most Common) "Physics"}
This is the most straightforward method. You print([Link]()) # Output: dict_keys(['name',
specify the key inside square brackets. 'age', 'major'])
Example: print([Link]()) # Output: dict_values(['Bob',
# Create a dictionary 22, 'Physics'])
student = { for key, value in [Link]():
"name": "Alice", print(f"{key}: {value}")
"age": 21, # Output: # name: Bob
"major": "Computer Science" # age: 22 # major: Physics

You might also like