Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Um Python Training Part 2

The document provides an overview of Python programming concepts, including reserved words, string manipulation techniques such as indexing, slicing, and concatenation, as well as string methods and file handling. It includes practical examples related to data analysis and inventory management, demonstrating how to use loops and string functions effectively. Additionally, it offers beginner prompts for learning Python basics, emphasizing clear instructions and foundational concepts.

Uploaded by

commguy5295
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Um Python Training Part 2

The document provides an overview of Python programming concepts, including reserved words, string manipulation techniques such as indexing, slicing, and concatenation, as well as string methods and file handling. It includes practical examples related to data analysis and inventory management, demonstrating how to use loops and string functions effectively. Additionally, it offers beginner prompts for learning Python basics, emphasizing clear instructions and foundational concepts.

Uploaded by

commguy5295
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

University of Michigan Python Part 2

The reserved words in the language where humans talk to Python include the following:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

The index operator in string manipulation is used to access individual characters within a string. In Python, this operator is represented by square brackets []. Here's how it works: Indexing
starts at 0: The first character of a string is at index 0, the second character is at index 1, and so on. For example, in the string "banana":
'b' is at index 0
'a' is at index 1
'n' is at index 2
'a' is at index 3
'n' is at index 4
'a' is at index 5
Accessing a character: You can retrieve a character by specifying its index. For example, fruit[1] would return 'a' from the string "banana".
Negative indexing: You can also use negative numbers to access characters from the end of the string. For example , fruit[-1] would return 'a', which is the last character of "banana".
Using the index operator allows you to manipulate and analyze strings effectively.

The len() function in string manipulation is used to determine the length of a string, which means it counts the number of characters in that string. Here’s how it works:
Counting characters: When you pass a string to the len() function, it returns an integer representing the total number of characters, including letters, numbers, spaces, and punctuation. For
example: len("banana") would return 6 because there are six characters in the word "banana".
Useful for validation: Knowing the length of a string can help you validate input, check for empty strings, or control loops that process each character in the string.
Using the len() function is a simple and effective way to work with strings in Python.

Here’s an example of a loop that iterates through each character in the string fruit = 'BANANA' and prints each character along with its index:
fruit = 'BANANA'

# Using a for loop to iterate through each character


for index in range(len(fruit)):
print(f"Index {index}: {fruit[index]}")
Output:

Index 0: B
Here’s a real-life example related to the concept of using loops with strings, specifically using the string fruit = 'BANANA'. This example can be connected to your role in network systems support,
where you might need to analyze data or logs.

Example: Analyzing a Fruit Inventory

Imagine you work in a grocery store that keeps track of fruit inventory. You have a list of fruits, and you want to check how many times a specific fruit appears in your inventory. Let's say you
have the string fruit = 'BANANA', and you want to count how many times 'A' appears in it.

Step-by-Step Breakdown:

Inventory String: You have a string representing the fruit inventory.


Loop through the string: You can use a loop to go through each character in the string.
Count occurrences: Each time you find 'A', you increase a counter.
Code Example:

fruit = 'BANANA'
count_a = 0

# Loop through each character in the string


for letter in fruit:
if letter == 'A':
count_a += 1

print(f"The letter 'A' appears {count_a} times in the inventory.")


Output:

The letter 'A' appears 3 times in the inventory.


Relevance:

Data Analysis: This example shows how you can analyze data (like inventory) using string manipulation and loops.
Problem-Solving: It demonstrates a practical application of programming concepts to solve real-world problems, such as counting items in a list.
String slicing can be very useful in data analysis, especially when dealing with textual data. Here are a couple of ways you might apply string slicing in a data analysis context:

1. Extracting Substrings

When analyzing data, you may need to extract specific parts of a string. For example, if you have a dataset of email addresses and you want to extract the domain name:

Example:
email = "user@example.com"
domain = email[email.index('@') + 1:] # Slicing to get the domain
print(domain) # Output: example.com

2. Analyzing Log Files

In network systems support, you might analyze log files where each log entry is a string. If each entry has a fixed format, you can use slicing to extract relevant information, such as timestamps or
error codes.

Example:
log_entry = "2023-10-01 12:00:00 ERROR: Connection failed"
timestamp = log_entry[:19] # Extracting the timestamp
error_message = log_entry[25:] # Extracting the error message
print(timestamp) # Output: 2023-10-01 12:00:00
print(error_message) # Output: ERROR: Connection failed

3. Data Cleaning
When preparing data for analysis, you might need to clean or format strings. For instance, if you have a list of product codes that include prefixes or suffixes, you can slice them to get the core
code.

Example:
product_code = "ABC-12345-XYZ"
core_code = product_code[4:9] # Extracting the core product code
print(core_code) # Output: 12345

Summary - Extracting specific information: Slicing allows you to pull out relevant parts of strings for further analysis.
Data cleaning and formatting: It helps in preparing data by removing unnecessary parts of strings.
String slicing can be an effective tool for cleaning data, especially when dealing with structured text data. Here are a few ways you can use string slicing for data cleaning:
1. Removing Unwanted Prefixes or Suffixes
If your data contains strings with consistent prefixes or suffixes that you want to remove, you can use slicing to extract only the relevant part.
Example:
product_code = "SKU-12345-XYZ"
clean_code = product_code[4:9] # Removing the prefix 'SKU-' and suffix '-XYZ'
print(clean_code) # Output: 12345
2. Standardizing Formats
When dealing with dates or other formatted strings, you might need to standardize them. For instance, if you have dates in the format "MM-DD-YYYY" and want to convert them to "YYYY-MM-
DD": Example:
date = "10-01-2023"
standardized_date = date[6:] + "-" + date[0:5] # Rearranging the date format
print(standardized_date) # Output: 2023-10-01
3. Extracting Relevant Information
In cases where you have strings with mixed information, slicing can help you extract only the necessary parts. For example, if you have a string with a user ID and a name: Example:
user_info = "ID:12345;Name:John Doe"
user_id = user_info[3:8] # Extracting the user ID
name = user_info[14:] # Extracting the name
print(user_id) # Output: 12345
print(name) # Output: John Doe
4. Trimming Whitespace
If your data has leading or trailing whitespace, you can slice the string to remove it. While Python has built-in methods like strip(), slicing can also be used if you know the exact positions.
Example:
raw_string = " Hello, World! "
clean_string = raw_string[3:-3] # Removing leading and trailing spaces
print(clean_string) # Output: Hello, World!

Summary -
Removing unwanted parts: Slicing helps in extracting only the relevant portions of strings.
Standardizing formats: It allows you to rearrange or format strings consistently.
Extracting specific data: You can isolate necessary information from mixed strings.
String concatenation in Python is the process of joining two or more strings together to form a single string. You can achieve this using the + operator.

Here’s how it works:

When you use the + operator between two strings, Python combines them without adding any spaces automatically. If you want a space between the strings, you need to include it explicitly.
Example:

string1 = "Hello"
string2 = "World"
result = string1 + " " + string2 # Adding a space in between
print(result) # Output: Hello World
In this example:

string1 is "Hello"
string2 is "World"
The result of the concatenation is "Hello World".

Question 7
How would you print out the following variable in all upper case in Python?
greet = 'Hello Bob'
print(greet.upper())

HELLO BOB
Method Name Description
capitalize() Converts the first character of the string to uppercase and the rest to lowercase.
casefold() Converts the string to lowercase, considering all case variants (e.g., micro-sign).
center(width, fillchar) Returns a centered string of the specified width, padded with the given fill character (default is space).
count(sub[, start[, end]]) Counts the number of non-overlapping occurrences of substring sub within the string.
encode(encoding='utf-8', errors='strict') Encodes the string using the specified encoding.
endswith(suffix[, start[, end]]) Checks if the string ends with the specified suffix.
expandtabs(tabsize=8) Replaces 1 tab characters with spaces, with each tab stop at the specified tabsize.
find(sub[, start[, end]]) Returns the lowest index where substring sub is found, or -1 if not found.
**format(*args, kwargs) Performs string formatting using positional and keyword arguments.
format_map(mapping) Performs string formatting using a dictionary.
index(sub[, start[, end]]) Similar to find(), but raises a ValueError if the substring is not found.
isalnum() Returns True if the string consists of alphanumeric characters only.
isalpha() Returns True if the string consists of alphabetic characters only.
isascii() Returns True if all characters in the string are ASCII.
isdigit() Returns True if the string consists of digits only.
islower() Returns True if all cased characters in the string are lowercase.
isnumeric() Returns True if the string consists of only numeric characters.
isprintable() Returns True if the string consists of printable characters only.
isspace() Returns True if the string consists of whitespace characters only.
istitle() Returns True if the string is in title case (first character of each word is uppercase).
isupper() Returns True if all cased characters in the string are uppercase.
join(iterable) Concatenates the elements of an iterable, inserting the string between them.
ljust(width, fillchar=' ') Returns a left-justified string of the specified width, padded with the given fill character.
lower() Converts all uppercase characters in the string to lowercase.
lstrip([chars]) Removes leading characters from the string (default is whitespace).
maketrans(x[, y[, z]]) Returns a translation table for use with the translate() method.
partition(sep) Splits the string at the first occurrence of the separator.
replace(old, new[, count]) Replaces all occurrences of the old substring with the new substring.
rfind(sub[, start[, end]]) Returns the highest index where substring sub is found, or -1 if not found.
rindex(sub[, start[, end]]) Similar to rfind(), but raises a ValueError if the substring is not found.
rjust(width, fillchar=' ') Returns a right-justified string of the specified width, padded with the given fill character.
rpartition(sep) Splits the string at the last occurrence of the separator.
rstrip([chars]) Removes trailing characters from the string (default is whitespace).
split(sep=None, maxsplit=-1) Splits the string into a list of substrings based on the separator.
splitlines(keepends=False) Splits the string into a list of lines.
startswith(prefix[, start[, end]]) Checks if the string starts with the specified prefix.
strip([chars]) Removes leading and trailing characters 2 from the string (default is whitespace).
swapcase() Swaps the case of all letters in the string (uppercase to lowercase and vice versa).
title() Converts the string to title case (first character of each word is uppercase).
translate(table) Translates characters using a translation table.
upper() Converts all lowercase characters in the string to uppercase.
zfill(width) Returns a right-padded string with zeros to fill the specified width.
Sources

https://github.com/EmekaEnshinyan/CS-Compendium
What does the following Python Program print out? Hellothere
str1 = "Hello"
str2 = 'there'
bob = str1 + str2
print(bob)

What does the following Python program print out? 42


x = '40'
y = int(x) + 2
print(y)

How would you use the index operator [] to print out the letter q from the following string? print(x[8])
x = 'From marquard@uct.ac.za'

How would you use string slicing [:] to print out 'uct' from the following string? print(x[14:17])
x = 'From marquard@uct.ac.za'

What is the iteration variable in the following Python code? letter


for letter in 'banana' :
print(letter)

What does the following Python code print out? 42


print(len('banana')*7)

How would you print out the following variable in all upper case in Python? print(greet.upper())
greet = 'Hello Bob'

Which of the following is not a valid string method in Python? boldface()

What will the following Python code print out? .ma


data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
pos = data.find('.')
print(data[pos:pos+3])

Which of the following string methods removes whitespace from both the beginning and end of a string?
strip()
Given the architecture and terminology we introduced in Chapter 1, where are files stored? Secondary memory

What is stored in a "file handle" that is returned from a successful open() call? The handle is a connection to the file's data

What do we use the second parameter of the open() call to indicate? Whether we want to read data from the file or write data to the file

What Python function would you use if you wanted to prompt the user for a file name to open? input()

What is the purpose of the newline character in text files? It indicates the end of one line of text and the beginning of another line of text

If we open a file as follows: xfile = open('mbox.txt’) What statement would we use to read the file one line at a time? for line in xfile:

What is the purpose of the following Python code? Count the lines in the file 'mbox.txt'
fhand = open('mbox.txt')
x=0
for line in fhand:
x=x+1
print(x)

If you write a Python program to read a text file and you see extra blank lines in the output that are not present in the file input as shown below, what Python string function will likely solve the problem? rstrip()
From: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu

The following code sequence fails with a traceback when the user enters a file that does not exist. How would you avoid the traceback and make it so you could print out your own error message when a bad file name was
entered? try / except
fname = input('Enter the file name: ')
fhand = open(fname)

What does the following Python code do? Reads the entire file into the variable inp as a string
fhand = open('mbox-short.txt')
inp = fhand.read()
Basic Python prompts for beginners could include:
Variable Assignment:
"Create a variable called 'name' and assign your name to it."
"Store the number 10 in a variable called 'age'."
Data Types:
"Write code to declare a variable that holds a string, an integer, and a floating-point number."
"Print the data type of the variable 'age' you created earlier."
Basic Arithmetic:
"Calculate and print the sum of two numbers entered by the user."
"Write code to find the remainder when 17 is divided by 5."
Input and Output:
"Ask the user for their name and then greet them using their input."
"Create a program that takes two numbers as input and prints their product."
Conditional Statements:
"Write code to check if a number is even or odd."
"Ask the user for their age and print a message depending on whether they are an adult or not."
Loops:
"Print the numbers from 1 to 10 using a 'for' loop."
"Create a loop that continues asking for a number until the user enters a negative value."
Functions:
"Define a function that calculates the area of a rectangle given its length and width."
"Write a function that takes a list of numbers and returns the average."
String Manipulation:
"Get the first letter of a user-inputted word."
"Write code to convert a string to uppercase."
Important points to remember when creating prompts:
Start with simple concepts: Focus on fundamental building blocks of Python before moving on to more complex topics.
Provide clear instructions: Clearly state what the user needs to achieve in the prompt.
Encourage explanation: Ask users to explain their code or reasoning behind certain choices.
Vary difficulty levels: Gradually increase the complexity of prompts as the learner progresses.
How are "collection" variables different from normal variables? Collection variables can store multiple values in a single variable
Collection Variables: These variables can hold a group of values, such as:Lists: Ordered collection (e.g., colors = ["red", "green", "blue"])Tuples: Ordered, immutable collection (e.g., coordinates = (10, 20))Sets: Unordered collection
of unique values (e.g., vowels = {"a", "e", "i", "o", "u"})Dictionaries: Collection of key-value pairs (e.g., student = {"name": "Bob", "age": 25})This ability to store multiple values within a single variable is a key feature of collection
variables, making them very useful for organizing and managing data efficiently.
What are the Python keywords used to construct a loop to iterate through a list? for / in

For the following list, how would you print out 'Sally’? print(friends['Sally’])

What would the following Python code print out? Nothing would print - the program fails with a traceback error. Strings in Python are immutable: This means they cannot be changed after they are created.fruit[0] = 'b' attempts
to modify the first character ('B') of the string 'Banana' to 'b'. However, since strings are immutable, this operation is not allowed.
fruit = 'Banana'
fruit[0] = 'b'
print(fruit)

Which of the following Python statements would print out the length of a list stored in the variable data? print(len(data)) - len(): This is a built-in Python function that returns the number of elements in a list, tuple, string, or
other iterable object.

What type of data is produced when you call the range() function? x = list(range(5)) A list of integers - range(5) specifically generates a list of integers from 0 (inclusive) up to 5 (exclusive), resulting in the list [0, 1, 2, 3, 4].The
list() function is used to convert the output of range() into an actual list object.

What does the following Python code print out? 6 - This code performs the following steps:Create lists:a is assigned a list containing the numbers 1, 2, and 3.b is assigned a list containing the numbers 4, 5, and 6.Concatenate
lists:c is assigned the result of adding lists a and b together. This creates a new list c that combines all the elements from both a and b. Calculate length:len(c) calculates the number of elements in the list c.print(len(c)) displays the
calculated length, which is 6.
a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(len(c))

Which of the following slicing operations will produce the list [12, 3]? t[2:4] - t[start:end]: This syntax extracts a portion of the list, starting from the index start (inclusive) and going up to the index end (exclusive).In this
case:start is 2, which corresponds to the element 12.end is 4, which corresponds to the element 74 (but the slice excludes this element).Therefore, the slice t[2:4] extracts the elements at indices 2 and 3, resulting in the list [12,
3].
t = [9, 41, 12, 3, 74, 15]

What list method adds a new item to the end of an existing list? append() my_list is a list containing the numbers 1, 2, and 3.my_list.append(4) adds the number 4 to the end of the list. The updated list is then printed, showing
that the number 4 has been successfully appended.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

What will the following Python code print out? Glenn - sort() method sorts the elements in the list in ascending order. After sorting, Glenn will be the first element in the list. The first element in the sorted list is Glenn.
friends = [ 'Joseph', 'Glenn', 'Sally' ]
friends.sort()
print(friends[0])
Python
fname = input("Enter file name: ")
try:
fh = open(fname)
except FileNotFoundError:
print("File cannot be opened:", fname)
exit()

lst = list()
for line in fh:
words = line.split()
for word in words:
if word not in lst:
lst.append(word)

lst.sort()
print(lst)

Explanation:
1.File Handling:
fname = input("Enter file name: "): Prompts the user to enter the filename.
try-except block:
fh = open(fname): Attempts to open the file.
except FileNotFoundError: Handles the case where the file is not found.
2.Word Extraction and List Building:
•lst = list(): Creates an empty list to store unique words.
•for line in fh: Iterates through each line in the file.
•words = line.split(): Splits the line into a list of words using whitespace as the delimiter.
•for word in words: Iterates through each word in the list of words.
•if word not in lst: Checks if the word is already present in the list.
•lst.append(word): If the word is not found, appends it to the list.
3.Sorting and Printing:
•lst.sort(): Sorts the list of words in alphabetical order.
•print(lst): Prints the sorted list of unique words.
This code effectively reads the file, extracts unique words, sorts them, and prints the resulting list.
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"

try:
fh = open(fname)
except FileNotFoundError:
print("File cannot be opened:", fname)
exit()

count = 0
for line in fh:
if line.startswith("From ") and not line.startswith("From:"): # Check for "From " and exclude "From:"
words = line.split()
if len(words) > 1: # Ensure there are at least 2 words after splitting
print(words[1])
count += 1

print("There were", count, "lines in the file with From as the first word")

Explanation:
File Handling: The code remains the same as before, prompting for a filename and handling potential file not found errors.

Processing Lines: The for loop iterates through each line in the file.
The condition if line.startswith("From ") and not line.startswith("From:") checks two things: line.startswith("From "):
Ensures the line starts with "From " (with a space). not line.startswith("From:"): Excludes lines that start with "From:" (colon indicates header field).

If the condition is true:


words = line.split(): Splits the line into a list of words.

if len(words) > 1: Checks if there are at least two words after splitting (to avoid index errors).

print(words[1]): Prints the second word (index 1), which is the email address.
count += 1: Increments the counter for valid lines.

Printing Results: The code remains the same, printing the final count of lines with "From " as the first word.
This code addresses the prompt's requirements by filtering out lines starting with "From:" and ensuring there are enough words before accessing the email address.
The significance of PHP's open-source development includes:
•Collaboration: It allows developers from around the world to contribute, share ideas, and improve the language collectively, leading to rapid
advancements and innovations.
•Community Ownership: By giving contributors control and ownership, it fosters a sense of investment and passion, which enhances the quality and
functionality of PHP.
•Low Barrier to Entry: Open-source PHP encourages new developers to participate easily, promoting a diverse range of contributions and ideas.
•Continuous Improvement: Bugs can be identified and fixed quickly by the community, ensuring that PHP remains robust and up-to-date with user needs.
•Flexibility: Developers can modify the source code to suit their specific requirements, making PHP adaptable for various applications.
These factors have contributed to PHP's widespread adoption and success in web development.

The main benefit of collaboration in open-source PHP is enhanced innovation and problem-solving. When developers from diverse backgrounds and experiences come together, they can:
•Share Knowledge: Different perspectives lead to new ideas and solutions, improving the overall quality of the code.
•Identify and Fix Bugs: A larger pool of contributors can quickly spot and resolve issues, leading to a more stable and reliable product.
•Accelerate Development: Collaborative efforts can speed up the development process, allowing for faster implementation of new features and updates.
This collaborative environment fosters a vibrant community that continuously improves PHP, making it a powerful tool for web development.

Contributors play a vital role in PHP development by:


•Code Contributions: They write and submit code patches, enhancements, and new features, which help improve the functionality of PHP.
•Bug Reporting and Fixing: Contributors identify bugs and issues, report them, and often provide fixes, ensuring the language remains stable and
reliable.
•Documentation: They help create and maintain documentation, making it easier for new users to understand and use PHP effectively.
•Community Support: Contributors often assist other users by answering questions, providing guidance, and sharing best practices within the community.
•Testing and Feedback: They test new features and provide feedback, which is crucial for refining and optimizing the language.
Overall, contributors help foster a collaborative environment that drives PHP's growth and evolution.

The significance of open source in PHP development includes:


•Accessibility: Open source allows anyone to use, modify, and distribute PHP, making it widely accessible to developers around the world.
•Community Collaboration: It fosters a collaborative environment where developers can contribute, share knowledge, and improve the language
collectively, leading to rapid advancements.
•Transparency: The open-source nature of PHP means that its code is publicly available, allowing users to inspect, understand, and trust the software.
•Cost-Effectiveness: Being free to use, open-source PHP reduces costs for developers and organizations, making it an attractive option for web
development.
•Continuous Improvement: Contributions from a diverse community lead to ongoing enhancements, bug fixes, and the introduction of new features,
ensuring PHP remains relevant and effective.
These factors have contributed to PHP's popularity and success in the web development landscape.

real-life example related to community engagement in PHP contributions: Example: PHP Community Contributions through Open Source Projects
Creating an Empty Dictionary: You can start with an empty dictionary and add items later:
my_dict = {}
my_dict['name'] = 'Alice'
my_dict['age'] = 30
my_dict['city'] = 'New York'
These methods allow you to create dictionaries to store and manage data effectively.

Dictionaries can be very useful in various projects. Here are two examples of how you might use a dictionary:
Storing User Information: In a web application, you could use a dictionary to store user profiles. Each user's profile can be represented as a dictionary where the keys are attributes like
'username', 'email', and 'age', and the values are the corresponding data. For example:
user_profile = {
'username': 'john_doe',
'email': 'john@example.com',
'age': 25
}
This allows you to easily access and update user information using the keys.

Counting Word Frequency: In a text analysis project, you could use a dictionary to count the frequency of words in a document. Each word can be a key, and its frequency can be the value. For
example:
text = "hello world hello"
word_count = {}
for word in text.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
After running this code, word_count would contain {'hello': 2, 'world': 1}, allowing you to see how often each word appears.
These examples illustrate how dictionaries can help organize and manage data efficiently in your projects.
Here's an example of using a dictionary for data storage in a simple inventory management system:
Example: Inventory Management
Imagine you are managing a small store's inventory. You can use a dictionary to store the items in the inventory, where each key is the item name and the value is another dictionary containing
details like quantity and price.

# Creating an inventory dictionary


inventory = {
'apple': {'quantity': 50, 'price': 0.60},
'banana': {'quantity': 30, 'price': 0.50},
'orange': {'quantity': 20, 'price': 0.80}
}

# Accessing data
print("Quantity of apples:", inventory['apple']['quantity']) # Output: 50
print("Price of bananas:", inventory['banana']['price']) # Output: 0.50

# Updating inventory
inventory['apple']['quantity'] -= 5 # Sold 5 apples
print("Updated quantity of apples:", inventory['apple']['quantity']) # Output: 45

# Adding a new item


inventory['grape'] = {'quantity': 25, 'price': 0.90}
print("New item added:", inventory['grape']) # Output: {'quantity': 25, 'price': 0.90}
using dictionaries in Python to create a histogram, which is a way to count how many times something appears.
Imagine you have a box of different colored marbles, and you want to know how many of each color you have. Instead of counting them one by one, you can use a piece of paper to keep track.
Each time you see a color, you make a tick mark next to that color on your paper. This is similar to how we use a dictionary in Python. In the dictionary, the color of the marble is like the "key,"
and the number of tick marks (or counts) is the "value." So, if you see a red marble, you add one to the count for red in your dictionary. This way, you can easily see how many of each color you
have without getting confused!
Here's a simple example in code:
# Create an empty dictionary to store counts
marble_counts = {}

# List of marbles we found


marbles = ['red', 'blue', 'red', 'green', 'blue', 'red']

# Count each marble


for marble in marbles:
if marble in marble_counts:
marble_counts[marble] += 1 # If it's already there, add one
else:
marble_counts[marble] = 1 # If it's new, start the count at one

print(marble_counts) # Output: {'red': 3, 'blue': 2, 'green': 1}

A histogram in Python is a way to represent the frequency distribution of data. It shows how many times each value or range of values occurs in a dataset. You can think of it as a visual
representation of counts, similar to the marble example we discussed earlier.
In Python, you can create a histogram using libraries like Matplotlib or Pandas. Here's a simple breakdown of how it works:
1.Data Collection: Gather the data you want to analyze. This could be numbers, names, or any other items.
2.Counting Occurrences: Use a dictionary to count how many times each unique item appears in your data.
3.Visualization: Use a plotting library to create a visual representation of these counts.
Example of Creating a Histogram
Here's a simple example using Matplotlib:
How are Python dictionaries different from Python lists? Python lists are indexed using integers and dictionaries can use strings as indexes
a dictionary stores data as key-value pairs, meaning you access values using unique keys, while a list stores data in an ordered sequence, accessed by numerical indexes; essentially,
dictionaries are for quick lookups based on specific keys, while lists are for ordered collections of data where you need to access elements based on their position in the sequence.
Key differences:
Accessing data: In a dictionary, you access data using a key (like a label), while in a list, you access data using an integer index.
Order: Lists maintain the order of their elements, while dictionaries do not.
Duplicate keys: Dictionaries cannot have duplicate keys, while lists can have duplicate values.
What is a term commonly used to describe the Python dictionary feature in other programming languages? Associative arrays
Key-value pairs:
Both dictionaries and associative arrays store data in key-value pairs, where a unique key is used to access a specific value.
Different names in different languages:
While Python explicitly calls it a "dictionary," other languages might use terms like "map" (Java) or simply "associative array" (JavaScript).

What would the following Python code print out? The program would fail with a traceback
Initialization:stuff = dict() creates an empty dictionary named stuff.Accessing a non-existent key:print(stuff['candy']) attempts to access the value associated with the key 'candy' in the
dictionary.However, since the dictionary is empty, there is no key 'candy' and no value associated with it.
stuff = dict()
print(stuff['candy'])

What would the following Python code print out? -1 initialize an empty dictionary and get the value for the key 'candy' using the get() method.
stuff = dict()
print(stuff.get('candy',-1))

What is a common use of Python dictionaries in a program? Building a histogram counting the occurrences of various strings in a file. Here's how it works:Initialization:Create an empty
dictionary to store the word counts. Iterating through the file:Read the file line by line. Split each line into a list of words. For each word: If the word is already a key in the dictionary,
increment its count. If the word is not in the dictionary, add it as a key with a count of 1.Result:The dictionary will now contain each unique word in the file as a key, and its corresponding
count as the value.

Which of the following lines of Python is equivalent to the following sequence of statements assuming that counts is a dictionary? counts[key] = counts.get(key, 0) + 1
Explanation: counts.get(key, 0):This part of the expression retrieves the value associated with the key in the counts dictionary. If the key exists in the dictionary, it returns the corresponding
value. If the key does not exist, it returns the default value 0. + 1:This increments the retrieved value (or the default value of 0) by 1.counts[key] = ...:This assigns the incremented value back
to the key in the counts dictionary. This single line effectively handles both cases: If the key exists: It retrieves the current count, increments it by 1, and updates the dictionary. If the key
doesn't exist: It uses the default value of 0, increments it to 1, and adds the key-value pair to the dictionary. This is a concise and efficient way to implement a counter in Python using
dictionaries.
if key in counts:
counts[key] = counts[key] + 1
else:
In the following Python, what does the for loop iterate through? It loops through the values in the dictionary
let's break down the given code snippet: 1. x = dict() This line creates an empty dictionary named x. A dictionary in Python is an unordered collection of key-value pairs.2. for y in x: This is the
start of a for loop. The for loop is designed to iterate over a sequence of elements. In this case, it iterates over the keys of the dictionary x. In each iteration: The current key of the dictionary is
assigned to the variable y.3. ... This represents the body of the loop. This is where you would place the code that you want to execute for each key in the dictionary. The code within this block
can access the value associated with the current key y using x[y].
x = dict()
...
for y in x :
...
This demonstrates how the loop iterates over the keys ('apple', 'banana', 'orange') and prints each key along with its corresponding value from the dictionary. Key Points: The for loop iterates
over the keys of the dictionary. The value associated with the current key can be accessed using x[y]. The order of iteration through the dictionary is not guaranteed.

Which method in a dictionary object gives you a list of the values in the dictionary? values() : This method returns a view object containing the values of the dictionary. Example:
my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
values_list = my_dict.values()
print(values_list) # Output: dict_values([3, 2, 1])

Other methods: keys(): Returns a view object containing the keys of the dictionary. items(): Returns a view object containing key-value pairs as tuples. each(): This method does not exist in
Python dictionaries. all(): This method checks if all the values in an iterable are True.

What is the purpose of the second parameter of the get() method for Python dictionaries? The second parameter of the get() method for Python dictionaries is used to: To provide a default
value if the key is not found. If the specified key does not exist in the dictionary, the get() method will return this default value instead of raising a Key Error. Example:
my_dict = {'apple': 3, 'banana': 2}

value1 = my_dict.get('apple') # Output: 3 (key exists)


value2 = my_dict.get('orange') # Output: None (key doesn't exist, no default)
value3 = my_dict.get('orange', 0) # Output: 0 (key doesn't exist, default value is 0)

print(value1)
print(value2)
print(value3)
3
None
0
In this example: value1 retrieves the value associated with the key 'apple' (which exists). value2 retrieves None because the key 'orange' is not found and no default value is provided. value3
retrieves 0 because the key 'orange' is not found, but a default value of 0 is specified. This feature of the get() method makes it safer and more convenient to handle cases where the key might
not be present in the dictionary.
the concept of dictionaries in Python, which is a powerful way to store and manage data.
A dictionary in Python is like a real-life dictionary where you have words (keys) and their meanings (values). Instead of just looking up a word, you can also store information about it. For
example, if you have a dictionary of fruits, you might have "apple" as a key and "a sweet red fruit" as its value. This allows you to quickly find the meaning or information associated with that key.
Here's a simple example of how you can create a dictionary in Python:
fruits = {
"apple": "a sweet red fruit",
"banana": "a long yellow fruit",
"cherry": "a small red fruit"
}
In this example, "apple", "banana", and "cherry" are the keys, and their descriptions are the values. You can easily access the description of any fruit by using its name as the key, like this:
fruits["apple"], which would return "a sweet red fruit".

Dictionaries are incredibly useful because they allow you to store and retrieve data efficiently, making your programs more organized and easier to manage.
The get method in Python dictionaries is a way to retrieve the value associated with a specific key. It has a couple of advantages over directly accessing the value using square brackets. How it
works:
Basic Usage: You call the get method on a dictionary and pass the key you want to look up.
Default Value: You can also provide a default value that will be returned if the key does not exist in the dictionary. Example:
fruits = {
"apple": "a sweet red fruit",
"banana": "a long yellow fruit"
}

# Using get to retrieve a value


apple_description = fruits.get("apple") # Returns: "a sweet red fruit"

# Using get with a default value


orange_description = fruits.get("orange", "not found") # Returns: "not found“

Key Points:

If the key exists, get returns the corresponding value.


If the key does not exist, it returns None by default or the specified default value if provided.
This method helps avoid errors that occur when trying to access a key that isn't present in the dictionary.
Using get is a safe way to access dictionary values without risking a KeyError
The syntax for using the get method in Python dictionaries is as follows:
dictionary.get(key, default_value)
Parameters:
key: The key you want to look up in the dictionary.
default_value (optional): The value to return if the key is not found. If not provided, it defaults to None.
Example:
fruits = {
"apple": "a sweet red fruit",
"banana": "a long yellow fruit"
}

# Using get method


description = fruits.get("apple") # Returns: "a sweet red fruit"
missing_description = fruits.get("orange", "not found") # Returns: "not found"
This method is useful for safely retrieving values without causing errors if the key is missing.

You can handle missing keys in a dictionary using the get method by providing a default value that will be returned if the specified key does not exist. This way, you can avoid errors and manage
your program flow more effectively. Example:
fruits = {
"apple": "a sweet red fruit",
"banana": "a long yellow fruit"
}
# Attempting to get a value for a missing key
orange_description = fruits.get("orange", "not found") # Returns: "not found"

# Using get without a default value


missing_description = fruits.get("grape") # Returns: None
Key Points:

With Default Value: If you use fruits.get("orange", "not found"), it will return "not found" since "orange" is not a key in the dictionary.
Without Default Value: If you use fruits.get("grape"), it will return None because "grape" is not found, and no default value is specified.
This approach allows you to handle missing keys gracefully without causing your program to crash
If you don't provide a default value in the get method and the specified key is not found in the dictionary, the method will return None. This means that you won't get an error, but you'll receive
a None value instead. Example:
fruits = {
"apple": "a sweet red fruit",
"banana": "a long yellow fruit"
}
# Using get without a default value
grape_description = fruits.get("grape") # Returns: None
Key Points:
No Error: You won't encounter a KeyError, which is what happens if you try to access a missing key directly using square brackets (e.g., fruits["grape"]).
Return Value: The return value will simply be None, indicating that the key does not exist in the dictionary.
This behavior allows for safer code when dealing with dictionaries, as it prevents crashes due to missing keys.

Tuples in Python: A Simple Explanation


In Python, a tuple is like a list, but with one important difference: tuples cannot be changed once they are created. Think of a tuple as a sealed box containing items. Once you put things inside,
you can't take them out or change them. This makes tuples more efficient for storing data because Python knows they won't change, allowing it to use memory more effectively.

For example, if you have a tuple of colors like this: ('red', 'green', 'blue'), you can access each color using its position, just like with a list. However, if you try to change 'green' to 'yellow', Python
will give you an error because tuples are immutable. This immutability is what makes tuples special and useful in certain situations, especially when you want to ensure that the data remains
constant.
What is the difference between a Python tuple and Python list? Lists are mutable and tuples are not mutable

Which of the following methods work both in Python lists and Python tuples? index()

What will end up in the variable y after this code is executed? 4

In the following Python code, what will end up in the variable y? A list of tuples
x = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
y = x.items()

Which of the following tuples is greater than x in the following Python sequence? (6, 0, 0)
x = (5, 1, 3)
if ??? > x :
...

What does the following Python code accomplish, assuming the c is a non-empty dictionary? It creates a list of tuples where each tuple is a value, key pair
tmp = list()
for k, v in c.items() :
tmp.append( (v, k) )

If the variable data is a Python list, how do we sort it in reverse order? data.sort(reverse=True)

Using the following tuple, how would you print 'Wed'? print(days{2})
days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')

In the following Python loop, why are there two iteration variables (k and v)? Because the items() method in dictionaries returns a list of tuples
c = {'a':10, 'b':1, 'c':22}
for k, v in c.items() :
...

Given that Python lists and Python tuples are quite similar - when might you prefer to use a tuple over a list? For a temporary variable that you will use and discard without modifying

You might also like