- Loops
This script demonstrates various looping mechanisms and control structures in Python, focusing on for and while loops. It covers iteration over sequences, condition checking, and loop controls like break and continue. Below is a detailed explanation of the key components and their functionality.
Loops in Python are control structures used to repeat a block of code multiple times, either for a specified number of iterations or until a certain condition is met. Python provides two types of loops:
- For loop: Iterates over a sequence (like a list or a range).
- While loop: Repeats the block of code as long as a condition is
True.
Simple Repetition:
print('Hello World!')This basic block prints "Hello World!" multiple times to the console. Instead of repeating the statement manually, this can be achieved more efficiently using a loop.
For Loop with Range:
- For loop: Iterates over a sequence (like a list or a range).
for element in sequence: # code block
nums = range(0, 10)
for num in nums:
print(num, 'Hello world!')range(1, 6): Generates numbers from 1 to 5.- Odd number check: The loop prints "Hello world!" only for odd numbers (numbers not divisible by 2).
Iterating Over Lists:
names = ['Mikko','Matti','Elena', 'Olga','Lauri','Kimm0','Mehrnaz','Jevgeni','Goodluck','Pullo','Asabeneh']
for name in names:
if len(name) > 6:
print(f'{name} is a long name.')
else:
print(f'{name} is a short name')- This loop iterates over the list of
namesand checks the length of each name. - If the length of the name is greater than 6, it categorizes it as a "long name"; otherwise, it's considered a "short name."
Working with Country Names:
The list countries holds a collection of country names. Several loops demonstrate different tasks such as:
-
Finding countries containing "land":
countries_with_land = [] for country in countries: if 'land' in country: countries_with_land.append(country) print(countries_with_land, len(countries_with_land))
-
Countries ending with "ia":
for country in countries: if country.endswith('ia'): print(country)
-
Countries starting with the letter 'B':
countries_starts_with_s = [] for country in countries: if country.startswith('B'): countries_starts_with_s.append(country) print(countries_starts_with_s, len(countries_starts_with_s))
Summing and Categorizing Numbers:
This section explores how to sum numbers and categorize them into positive and negative lists.
nums = [-10, 5, 0, 20, 4.5, 20, -14, 25, -3]
total = 0
for num in nums:
total += num
print(total)-
A total sum of numbers is calculated.
-
Numbers are further split into positive and negative categories:
positive_nums = [] negative_nums = [] for num in nums: if num > 0: positive_nums.append(num) else: negative_nums.append(num) print(positive_nums) print(negative_nums)
The while loop runs as long as the condition remains True. It checks the condition before executing the block of code.
Syntax:
while condition:
# code blockExample 1: Using a while loop to print a countdown:
count = 5
while count > -1:
print(count)
count -= 1This loop continues to print the count variable until it reaches 6. It demonstrates how to use a while loop to perform repetitive tasks until a condition is met.
Example 2: Using while loop with a break condition
names = []
while True:
name = input('Enter name: ')
if name == 'quit' or name == '':
break
names.append(name)
print(names)-
Skip Negative Values:
for num in nums: if num <= 0: continue print(num)
The
continuestatement is used to skip negative numbers and proceed with the next iteration. -
Stop Looping at Zero:
for num in nums: if num == 0: break print(num)
The
breakstatement stops the loop when the number0is encountered.
Multiplication Table:
A simple loop to print the multiplication table of numbers from 0 to 10:
for i in range(11):
print(f'{i} x {i} = {i * i}')This script demonstrates several fundamental concepts in Python looping and control structures, including:
- Iterating over sequences with
forloops. - Repeating tasks with
whileloops. - Using
continueto skip certain iterations. - Using
breakto exit a loop prematurely.
These concepts are crucial for understanding more advanced Python programming, especially in data processing, algorithm implementation, and automation tasks.
Sets are a powerful and versatile data structure in Python, designed to hold collections of unique items. This reading material will explore the fundamental characteristics of sets, demonstrate how to create and manipulate them, and explain their various operations.
A set is an unordered collection of items. The key features of sets include:
- Unordered: The items in a set do not maintain any specific order, meaning that indexing is not supported.
- Unique Items: Sets automatically eliminate duplicate entries, ensuring all items are unique.
- Mutable: You can add or remove items from a set after its creation.
Example: Creating an Empty Set
# Creating an empty set
empty_set = set()
print(empty_set, len(empty_set)) # Output: set() 0
print(dir(empty_set)) # Lists available methods for the setIn this example, an empty set is created, and its length is printed, showing that it currently contains no items.
You can add items to a set using the add() method.
Example: Adding Items
empty_set.add('Milk')
empty_set.add('Coffee')
print(empty_set) # Output: {'Milk', 'Coffee'}Sets support various mathematical operations such as union, intersection, difference, and symmetric difference. Here’s how to perform these operations:
The union of two sets combines all unique items from both sets.
A = {1, 2, 3, 4, 5, 6}
B = {3, 4, 7, 8}
# Union
print(A.union(B)) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(B.union(A)) # Output: {1, 2, 3, 4, 5, 6, 7, 8}The intersection returns only the items present in both sets.
# Intersection
print(A.intersection(B)) # Output: {3, 4}
print(B.intersection(A)) # Output: {3, 4}The difference returns items that are in one set but not the other.
# Difference
print(A.difference(B)) # Output: {1, 2, 5, 6}
print(B.difference(A)) # Output: {7, 8}The symmetric difference returns items that are in either set but not in both.
# Symmetric Difference
print(A.symmetric_difference(B)) # Output: {1, 2, 5, 6, 7, 8}You can check if an item is present in a set using the in keyword.
fruits = {'banana', 'orange', 'mango', 'lemon'}
print('kiwi' in fruits) # Output: False
print('orange' in fruits) # Output: TrueYou can use a loop to iterate through the items in a set:
for fruit in fruits:
print(fruit)You can modify a set by adding multiple items using the update() method or removing items using the remove() and pop() methods.
Example: Adding and Removing Items
fruits.add('guava')
fruits.add('papaya')
print(fruits) # Output: {'banana', 'orange', 'mango', 'lemon', 'guava', 'papaya'}
# Remove an item
fruits.remove('orange')
print(fruits) # Output: {'banana', 'mango', 'lemon', 'guava', 'papaya'}
# Clear all items
fruits.clear()
print(fruits) # Output: set()You can convert a list to a set to eliminate duplicate entries:
print(set(['Finland', 'Sweden', 'Denmark', 'Sweden'])) # Output: {'Finland', 'Sweden', 'Denmark'}You can combine multiple sets into one using the union() method.
vegetables = {'tomato', 'potato', 'cabbage', 'onion', 'carrot'}
combined_items = fruits.union(vegetables)
print(combined_items) # Combines fruits and vegetablesSets can also be checked for subset or superset relationships:
A = {1, 2, 3, 4}
B = {1, 2, 3, 3, 4, 5, 6}
print(A.issubset(B)) # Output: True
print(A.isdisjoint(B)) # Output: False (they share common elements)
print(B.issuperset(A)) # Output: TrueSets are a powerful feature of Python, enabling the storage of unique items and providing various operations for data manipulation. Understanding how to create and work with sets is essential for effective programming in Python, especially when dealing with collections of items where uniqueness and mathematical set operations are required.
Tuples are one of the fundamental data types in Python, offering a versatile way to store collections of items. This reading material will provide an in-depth look at tuples, their properties, operations, and usage examples.
A tuple is an immutable data structure that can hold a collection of items. The key characteristics of tuples include:
- Immutable: Once a tuple is created, its contents cannot be changed (i.e., you cannot add, remove, or modify elements).
- Ordered: The items in a tuple maintain the order in which they were defined.
- Indexable: Each item in a tuple can be accessed using an index.
Example: Creating an Empty Tuple
# Creating an empty tuple
empty_tpl = tuple() # Alternatively: empty_tpl = ()
print(type(empty_tpl)) # Output: <class 'tuple'>In this example, an empty tuple is created, and its type is printed.
Example: Creating a Tuple
You can create a tuple with multiple items:
nums = (1, 2, 3, 4)
print(len(nums), type(nums)) # Output: 4 <class 'tuple'>The len() function returns the number of elements in the tuple, while type() confirms that it is a tuple.
You can iterate over the items in a tuple using a loop:
for num in nums:
print(num)This will print each number in the nums tuple.
You can access specific elements or slices of a tuple using indexing:
fruits = ('banana', 'orange', 'mango', 'lemon')
print(fruits[1:]) # Output: ('orange', 'mango', 'lemon')
print(fruits[1:3]) # Output: ('orange', 'mango')Example: Tuple Unpacking
You can unpack tuple elements into multiple variables:
o, m = fruits[1:3]
print(o, m) # Output: orange mangoYou can combine multiple tuples using the + operator:
fruits = ('banana', 'orange', 'mango', 'lemon', 'orange')
vegetables = ('Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot')
fruits_and_vegest = fruits + vegetables
print(fruits_and_vegest)This concatenates the fruits and vegetables tuples into a single tuple.
Example: Counting Occurrences
You can count how many times an item appears in a tuple:
print(fruits.count('lemon')) # Output: 1You can iterate over the combined tuple just like any other iterable:
for item in fruits_and_vegest:
print(item)This prints each item from the combined fruits_and_vegest tuple.
Although tuples are immutable, you can convert them into lists if you need to modify their contents:
fruits_lst = list(fruits)
print(fruits_lst) # Output: ['banana', 'orange', 'mango', 'lemon', 'orange']Example: Enumerating a List
You can also use the enumerate() function to get both the index and value while iterating:
print(list(enumerate(fruits_lst)))
# Output: [(0, 'banana'), (1, 'orange'), (2, 'mango'), (3, 'lemon'), (4, 'orange')]You can specify a starting index when using enumerate():
for index, value in enumerate(['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']):
print(f'{index + 1}. {value}')This will output the countries with a custom starting index:
1. Finland
2. Sweden
3. Norway
4. Denmark
5. IcelandTuples are a crucial data structure in Python, offering a way to store collections of items that are ordered and immutable. Understanding how to create, access, and manipulate tuples is essential for effective programming in Python, especially when working with fixed collections of data.
Dictionaries are one of the fundamental data structures in Python, allowing you to store data in key-value pairs. This reading material will provide a comprehensive overview of dictionaries, including their properties, methods, and usage through examples.
A dictionary is a mutable, unordered collection of items, where each item is stored as a key-value pair. This structure allows for efficient data retrieval and manipulation based on unique keys.
Example: Creating an Empty Dictionary
# Creating an empty dictionary
empty_dict = {} # Alternatively: empty_dict = dict()
print(type(empty_dict), len(empty_dict)) # Output: <class 'dict'> 0In this example, an empty dictionary is created, and its type and length are printed.
Each item in a dictionary consists of a key and its associated value. You can think of it as a real-life dictionary, where each word (key) has a definition (value).
Example: Defining a Person Dictionary
person = {
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 250,
'is_married': True,
'address': {
'country': 'Finland',
'city': 'Espoo',
'zipcode': '02770',
'street': 'Space street'
},
'skills': ['HTML', 'CSS', 'JavaScript', 'Python', 'NumPy', 'TextBlob', 'Flask', 'MySQL'],
'educations': [
{
'name': 'Helsinki Metropolia University of Applied Science',
'qualification': 'BEng.',
'field': 'Information Technology',
'starting_year': 2012,
'ending_year': 2017
},
{
'name': 'Helsinki University',
'qualification': 'MSc.',
'field': 'Computer Science',
'starting_year': 2017,
'ending_year': 2017
}
]
}In this example, a dictionary named person is defined, containing various key-value pairs, including nested dictionaries and lists.
You can access the values in a dictionary by using their keys:
print(person) # Prints the entire dictionary
print(len(person)) # Output: Number of key-value pairs in the dictionary
print(person['first_name']) # Output: Asabeneh
print(person['address']['country']) # Output: FinlandYou can also use the get() method to access values. This method returns None if the key is not found, instead of raising an error:
print(person.get('nationality')) # Output: NoneYou can add new items to the dictionary by assigning a value to a new key:
person['nationality'] = 'Ethiopian'
print(person) # Prints the updated dictionaryYou can modify existing values or append new data to lists within the dictionary:
print(person.get('nationality')) # Output: Ethiopian
print(len(person)) # Output: Updated count of key-value pairs
person['hobbies'] = [] # Adding a new key with an empty list
print(person)
# Appending items to the hobbies list
person['hobbies'].append('Ice skating')
person['hobbies'].append('Running')
print(person) # Prints the dictionary with updated hobbiesYou can iterate through the keys and values of a dictionary using a loop:
for item in person:
print(item, person[item])Example: Using the items() Method
The items() method returns a view object displaying a list of a dictionary's key-value tuple pairs:
items = person.items()
print(items)
for key, value in items:
print(key, value) # Prints each key-value pairYou can retrieve all the keys or values from a dictionary using the keys() and values() methods, respectively:
keys = person.keys()
print(keys) # Prints all keys in the dictionary
values = person.values()
print(values) # Prints all values in the dictionaryDictionaries are a powerful and flexible data structure in Python, allowing for the storage of key-value pairs. Their mutability and ability to nest other data structures make them an essential tool for managing and organizing data effectively. Understanding how to create, access, and manipulate dictionaries is crucial for effective programming in Python.