Python Spreadsheet
Python Spreadsheet
finishers bob
['sam, ada", "bea'] Accessing a value
Variables and Strings first twOfinishers [ :2] print("The alien's color is + alien[ ' color ])
Variables g s a5ernes
of Copying a list
Adding a new key-value pair
copy_of bikes bikes[:]
Hello world alien['xposition']
print("Hello world1 ") Looping through all key-value pairs
Tuples
Hello world with a variable similar to lists, Dut the items in a tuple cant be favnumbers('eric': 17, 'ever: 4)
pes are
modined. for name, number in fav_numbers. items()
msg"Hello world Making a tupie
print(name loves str(number ))
print (msg8)
Looping through all keys
Concatenation (combining strings) dimensions (1928, 1e88)
fav_numbers(eric": 17, ever' 4)
first name 'albert If statements for name 1n fav_numbers.keys(
1astname einstein print(name+1oves a number
name + last name statements are used to test for particular conditions and
neto
print (fulname) Looping through all the values
respond aDpropriately.
Conditional tests fav_numbers f'eric': 17, ever: 4)
Lists for
number in fav numbers.' ivalues()
equals 42 print(str(number) s
+
a favorite')
A list stores a series of items in a particular order. You not equa x I 4
access items using an index, or within a lop.
greater than X > 42
Make a list or equal to x > 42 User input
Looping through a list game active True age input ("How old are you? )
can_edit False age int (age)
for bike in bikes:
print (bike) A simple if test
pi input ("what's the value of pi? *)
Adding items to a list i f age 18: pi float (pi)
print(You can vote!")
print (msp)
your message Filename [Link]
def sit(selt)
Drinteas itting.
with
open(filename, w) as file object:
tile_object.write("I love programming.)
Functions is sitting.")
one
print (self. name Appending to a file
Funcro named passedcode,
unions aremation designed do
blockS of to
to a function my_doß Dog("Peso")
iss cais called a filename [Link]
argument, and information received by a function with open(filename, 'a') as
file object:
paramere print([Link] + is a great dog file_object.write("\nI love making games . ")
og-5to
A simple function
Inheritance
der greet_user(): Exceptions
tha
you respond appropriately to
help errors
D1splay a simple greeting.*** class SARDOg(Dog) EXceptions
print(Hello!") Represent a search dog.**
Code that should run in response to
greet_user0 def init_(self, name): an error goes in the exoept block. Code that should run only
if the try block sucoesstul goes in
Passing an argument
**"Initialize the sardog.
Super).-1n1t-(name)
was
the else bloCK.
Catching an exception
def greet user(username):
"Display a personalized greeting. def search (self): prompt How many tickets do you need?
print(Hello, "username ) **"Simulate searching.
is searching-")
numtickets 1nput(prompt)
print([Link]
greet_user (°jesse") y_dogSARDOg( "Willie')
try int (num_tickets)
Default values for parameters xcep
numtickets
def make pizza(topping0o print(my_dog.name+ is a search dog.") exeint( Please try again.
my [Link]() else:
my_dog.search()
print("Have a topping+ " pizza!")
make_pizza()
ake_pizza( pepperoni" 7
intinite Skills Zen of Python
yo had initinite programming skills, what would you Simple is better than complex
Returning a value
DUiG If you havea choice between a simple and a complex
sef add_numbers (x, y): As you're learning to program, it's heiptul to think
Add two numbers and return the sum."*** about the real-world projects you'd like to create. If's solution, and both work, use the simple solution. Your
code will be easier to maintain, and it will be easier
return x y
keep an that
a
good habit to ideas" notebook
can refer to whenever you want to start a new project.
you for you and others to build on that code later on.
Cheat Sheet - Lists Adding an element to the end of the list alphabetical ore the ist. Keep in mind that
[Link]( amy)
lowercase and uppercase letters may affect the sort order
What are lists?
Starting with an empty list Sorting a list permanentiy
users
[Link]()
A list stores a series of items in a particular order [Link]("val')
list in alphabetical
Lists allow you to store sets of intormation in one
Sorting a permanently reverse
use end 'mia' )
[Link](
order
place, whether you have just a few items or mions
of items. Lists are one of Python's most powerru Inserting elements at a particular position
and [Link] (reverse-True)
features
tie
readily accessible to new programimers, ana
important concepisS n [Link](8, joe Soring a list temporarily
they together many [Link](3, "bea')
programming. print(sorted(users) )
print (sorted (users , reverse-True) )
Removing elements
Defining a list Reversing the order of a list
by their position ina ist, or by
brackets fo define a lst and use commas to Ou can reove eements
ou remove an item by its value,
Sqar
separate individual items in the list. Use plural names for [Link]()
Python removes only the first item that has that value
lists, to make your code easier to read.
Deleting an element by its position Looping through a list
Making a list
del users[-1] Lists can contain millions of items, so Python provides an
users [val', "bob, mia', "ron', 'ned'] efficient way to loop through a nees S
Removing an item by its value you ser upa 1o00, i
Accessing elements
[Link]("mia prouide a name for. This name should be the singular
individual olements in a kst are accessed according to their version of the list
name
position, caled the index The index of the irst elemernt is Popping elements The indented block of
0, the index or mes code makes up the body of the
o f the list To get you want to work with an element that you re removing Oop, where you can work Wilh each naiviaua ttem. Any
nes natare nor indented run ater the lo0p is completed.
a narticular element. write the name of the list and then ne from the ist. you can pop the eiement, you ink of the
index of the element in square brackets. list as a stack of items, pop) takes an tem of the top of fhe
nng an tems in a list
Getting the first element
Stack. By default pop() returns the last element in the list.
but you can also pop elements from any position in the list. for user in users
first user users[e) Pop the last item from a list print(user
Printing a message for each item, and a separate
Getting the second element )
most recent_user [Link] message aterwards
second_user- users[1] print(mostrecenEuse for user in users:
Getting the last element
Pop the first item in a list
print("Welcome, u s e r "I")
firstuser - [Link](®)
newest user -
users[-1] print("Welcome, we're glad to see you alli)
print(first_user)
Modifying individual items
Once you've defined a list, you can change individua
List length
elements in the list. You do this by referring to the index of
the item you want to modify.
Thelen)functionreturns the number ofitemsin alist. Python Crash Course cA ON
youngest min(ages) [Link] (square) for neina how Python keeps track of the information in a
list. Try running the following code on [Link]
Finding the maximum value a comprehension to generate a list of square
17, 85, 1, 35, 82, 2, 77]
Using nen ruin yur ow co
ages
oldest
[93, 99, 66,
max(ages)
numbers
Build a list and print the items in the list
squares [x**2 for x in range(1, 11)]
Finding the sum of all values dogs
Using a loop to convert a list of names to upper case dogS.appendwill1e)
ages [93, 99, 66, 17, 85, 1, 35, 82, 2, 77 [Link]( hootz)
vears
total_years sum(ages) names [°kai', "abe", ada", 'gus, zoe"]
[Link] pe
[Link]( goblin")
Slicing a list upper names
for name in
names for dog in dogs
You can wok with any set of elements trom a list A portion upper_names .append(name. upper())
of list is
a caled a shice
1o sic Using a comprehension to convert a list ot names to
print("Hello dog+I")
print("I love these dogs!)
e off the fist index to start at Upper case
the beginning of the list, and leave off the last index to sice printnthese were my first two dogs:
names [ k a i ' , 'abe"', 'ada", 'gus, z0e"]
throughthe end of the lst old_dogs
for old
dogs[:2]
dog in old dogs:
upper names [name. upper() for name in names]
Getting the first three items print(old_dog)
finishers [ kaiabeada', us 0
Beginner's Python You can store as many key-value pairs as you want in a
dictionary, unt your
eyve po compulerruns o eo
an exSng Cicionary give he anme
You can lo0p througha dictionany in three ways: you can
then
and
tne
place
n aSero
Key
# Change the alien's color and point value. Looping through all the keys in order
square brackets. if the key you're asking for is not in the alien e color yellow
16 #Show each person 's favorite language,
alien er points
print (alien_8) #in order by the person's name
instead of an error if the key doesn7ex Yo for
name in sorted(fav_languages.keys()):
default value to use if the print (name": "+ language)
specify a key is not in the
dictonary. Removing key-value pairs
Getting the value associated with a key You can remove any keyvaluepair you wan rom a
dictionary
1o do so Use me
ce
Dictionary length
name. folowed by the key in square brackets. This will
You
can find the number of key-value pairs in a dichornary.
alien_ (color": 'green", "points': 5}
delete the koy and its associated value Finding a dictionary's length
print(alien_er color Deleting a key-value pair num_responses len(fav_languages)
print (alien_e[ points
Getting the value with get) alien (color:
print(alien_8)
green, points": 5)