100% satisfaction guarantee Immediately available after payment Both online and in PDF No strings attached 4.2 TrustPilot
logo-home
Exam (elaborations)

Introduction to Programming in Python WGU D335 Beginner's Python Cheat Sheet - PCC for Basics.

Rating
-
Sold
-
Pages
28
Grade
A+
Uploaded on
30-06-2025
Written in
2024/2025

Introduction to Programming in Python WGU D335 Beginner's Python Cheat Sheet - PCC for Basics.











Whoops! We can’t load your doc right now. Try again or contact support.

Document information

Uploaded on
June 30, 2025
Number of pages
28
Written in
2024/2025
Type
Exam (elaborations)
Contains
Questions & answers

Subjects

Content preview

Lists (cont.) Dictionaries
Beginner's Python List comprehensions Dictionaries store connections between pieces of
information. Each item in a dictionary is a key-value

Cheat Sheet
squares = [x**2 for x in range(1, 11)] pair.
Slicing a list A simple dictionary
finishers = ['sam', 'bob', 'ada', 'bea'] alien = {'color': 'green', 'points': 5}
first_two = finishers[:2]
Variables and Strings Accessing a value
Variables are used to assign labels to values. A string is a Copying a list print(f"The alien's color is
series of characters, surrounded by single or double quotes. copy_of_bikes = bikes[:] {alien['color']}.")
Python's f-strings allow you to use variables inside strings to
Adding a new key-value pair
build dynamic messages.
Tuples alien['x_position'] = 0
Hello world Tuples are similar to lists, but the items in a tuple can't be
print("Hello world!") modified. Looping through all key-value pairs
Making a tuple fav_numbers = {'eric': 7, 'ever': 4, 'erin':
Hello world with a variable 47}
msg = "Hello world!" dimensions = (1920, 1080)
print(msg) resolutions = ('720p', '1080p', '4K') for name, number in fav_numbers.items():
print(f"{name} loves {number}.")
f-strings (using variables in strings) If statements Looping through all keys
first_name = 'albert' If statements are used to test for particular conditions and fav_numbers = {'eric': 7, 'ever': 4, 'erin':
last_name = 'einstein' respond appropriately. 47}
full_name = f"{first_name} {last_name}"
print(full_name) Conditional tests
for name in fav_numbers.keys():
equal x == 42 print(f"{name} loves a number.")
Lists not equal x != 42
Looping through all the values
greater than x > 42
A list stores a series of items in a particular order. You
or equal to x >= fav_numbers = {'eric': 7, 'ever': 4, 'erin':
access items using an index, or within a loop.
42 47}
Make a list less than x < 42
or equal to x <= for number in fav_numbers.values():
bikes = ['trek', 'redline', 'giant']
42 print(f"{number} is a favorite.")
Get the first item in a list Conditional tests with lists
User input
first_bike = bikes[0] 'trek' in bikes
Your programs can prompt the user for input. All input is
'surly' not in
Get the last item in a list bikes
stored as a string.
last_bike = bikes[-1] Assigning boolean values Prompting for a value
Looping through a list game_active = True name = input("What's your name? ")
can_edit = False print(f"Hello, {name}!")
for bike in bikes:
print(bike) A simple if test Prompting for numerical input
Adding items to a list if age >= 18: age = input("How old are you?
print("You can vote!") ") age = int(age)
bikes = []
bikes.append('trek') If-elif-else statements pi = input("What's the value of pi?
bikes.append('redline')
if age < 4:
bikes.append('giant')
ticket_price = Python Crash Course
Making numerical lists 0 elif age < 18: A Hands-on, Project-Based
ticket_price = Introduction to Programming
squares = []
10 elif age < 65:
for x in range(1, 11): ehmatthes.github.io/pcc_3e
ticket_price =
squares.append(x**2)
40 else:

,While loops Classes Working with files
A while loop repeats a block of code as long as a certain A class defines the behavior of an object and the kind of Your programs can read from files and write to files.
condition is true. While loops are especially useful when you information an object can store. The information in a class The pathlib library makes it easier to work with files and
can't know ahead of time how many times a loop should run. is stored in attributes, and functions that belong to a class directories. Once you have a path defined, you can
are called methods. A child class inherits the attributes and work with the read_text() and write_text()
A simple while loop
methods from its parent class. methods.
current_value = 1 Reading the contents of a file
while current_value <= 5: Creating a dog class
The read_text() method reads in the entire contents of a file.
print(current_value) class Dog: You can then split the text into a list of individual lines, and then
current_value += 1 """Represent a dog.""" process each line as you need to.
Letting the user choose when to quit def init (self, name): from pathlib import Path
msg = '' """Initialize dog object."""
self.name = name path =
while msg != 'quit':
Path('siddhartha.txt')
msg = input("What's your message? ")
def sit(self): contents = path.read_text()
"""Simulate sitting.""" lines =
if msg != 'quit':
print(f"{self.name} is sitting.") contents.splitlines()
print(msg)

my_dog = Dog('Peso') for line in lines:
Functions print(line)
Functions are named blocks of code, designed to do one print(f"{my_dog.name} is a great dog!") Writing to a file
specific job. Information passed to a function is called an my_dog.sit()
argument, and information received by a function is called a path = Path('journal.txt')
parameter. Inheritance
msg = "I love
A simple function class SARDog(Dog): programming.")
"""Represent a search dog.""" path.write_text(msg)
def greet_user():
"""Display a simple greeting."""
print("Hello!")
def init (self, name): Exceptions
"""Initialize the sardog.""" Exceptions help you respond appropriately to errors that are
super(). init (name) likely to occur. You place code that might cause an error in
greet_user()
the try block. Code that should run in response to an error
Passing an argument def search(self): goes in the except block. Code that should run only if the try
"""Simulate searching.""" block was successful goes in the else block.
def greet_user(username): print(f"{self.name} is searching.")
"""Display a personalized greeting.""" Catching an exception
print(f"Hello, {username}!") my_dog = SARDog('Willie')
prompt = "How many tickets do you need? "
greet_user('jesse') num_tickets = input(prompt)
print(f"{my_dog.name} is a search dog.")
my_dog.sit()
Default values for parameters try:
my_dog.search()
num_tickets =
def
int(num_tickets) except
make_pizza(topping='pineapple'):
"""Make a single-topping
Infinite Skills ValueError:
If you had infinite programming skills, what would you build? print("Please try again.")
pizza.""" print(f"Have a
else:
{topping} pizza!") As you're learning to program, it's helpful to print("Your tickets are printing.")
think about the real-world projects you'd like to
make_pizza()
make_pizza('mushroom')
create. It's a good habit to keep an "ideas" Zen of Python
notebook that you can refer to whenever you Simple is better than complex
Returning a value
want to start a new project. If you have a choice between a simple and a
def add_numbers(x, y): If you haven't done so already, take a few
"""Add two numbers and return the complex solution, and both work, use the
minutes and describe three projects you'd like
sum.""" return x + y
to create. As you're learning you can write Weekly posts about all things Python
sum = add_numbers(3, 5) small programs that relate to these ideas, so mostlypython.substack.com

, Beginner's Python Sorting


Cheat Sheet - Lists
What are lists?
A list stores a series of items in a particular Adding
order. Lists allow you to store sets of a list
information in one place, whether you have just The sort() method changes the order of a list
a few items or millions of items. Lists are one of permanently. The sorted() function returns a copy of the
Python's most powerful features readily list, leaving the original list unchanged.
accessible to new programmers, and they tie You can sort the items in a list in alphabetical order, or
reverse alphabetical order. You can also reverse the original
together many important concepts in
order of the list. Keep in mind that lowercase and uppercase
programming. letters may affect the sort order.
Defining a list elements Sorting a list permanently
Use square brackets to define a list, and use commas to You can add elements to the end of a list, or you can insert
them wherever you like in a list. This allows you to modify users.sort()
separate individual items in the list. Use plural names for
lists, to make it clear that the variable represents more than existing lists, or start with an empty list and then add items Sorting a list permanently in reverse
to it as the program develops.
one item. alphabetical order
Making a list Adding an element to the end of the list users.sort(reverse=True)
users = ['val', 'bob', 'mia', 'ron', 'ned'] users.append('amy') Sorting a list temporarily
Starting with an empty list print(sorted(users))
Accessing elements users = [] print(sorted(users,
Individual elements in a list are accessed according to their users.append('amy') reverse=True))
position, called the index. The index of the first element is 0, users.append('val') Reversing the order of a list
the index of the second element is 1, and so forth. Negative users.append('bob') users.reverse()
indices refer to items at the end of the list. To get a particular users.append('mia')
element, write the name of the list and then the index of the
element in square brackets. Inserting elements at a particular position Looping through a list
users.insert(0, Lists can contain millions of items, so Python provides an
Getting the first element efficient way to loop through all the items in a list. When
'joe')
first_user = users[0] users.insert(3, you set up a loop, Python pulls each item from the list
Getting the second element
'bea') Python
one at a time and assigns it to a temporary variable,
which you provide a name for. This name should be the
second_user = users[1] Removing elements singular version of the list name.
You can remove elements by their position in a list, or by The indented block of code makes up the body of the
Getting the last element the value of the item. If you remove an item by its value, loop, where you can work with each individual item. Any
newest_user = users[-1] Python removes only the first item that has that value. lines that are not indented run after the loop is completed.
Deleting an element by its position Printing all items in a list
Modifying individual items
del users[-1] for user in users:
Once you've defined a list, you can change the value of
individual elements in the list. You do this by referring to the List length
Removing an item by its value
index of the item you want to modify. The len() function returns the number of items
users.remove('mia')
Crash Course
in a list. A Hands-on, Project-Based
Changing an element Find the length of a list
Popping elements Introduction to Programming
users[0] = num_users = len(users)
'valerie' users[1] print(f"We havewith
If you want to work {num_users}
an element thatusers.")
you're removing ehmatthes.github.io/pcc_3e
= 'robert' users[-

from the list, you can "pop" the item. If you think of the list as

Get to know the seller

Seller avatar
Reputation scores are based on the amount of documents a seller has sold for a fee and the reviews they have received for those documents. There are three levels: Bronze, Silver and Gold. The better the reputation, the more your can rely on the quality of the sellers work.
Boffin Harvard University
View profile
Follow You need to be logged in order to follow users or courses
Sold
1764
Member since
4 year
Number of followers
1469
Documents
7146
Last sold
1 day ago
Pilot Study

Prevent resits and get higher grades.

3.8

433 reviews

5
209
4
74
3
70
2
16
1
64

Recently viewed by you

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Frequently asked questions