0% found this document useful (0 votes)
4 views5 pages

Python Spreadsheet

The document is a cheat sheet for beginners learning Python, covering essential topics such as lists, dictionaries, tuples, and functions. It includes examples of list comprehensions, conditional statements, and user input handling. Additionally, it discusses file operations, classes, and basic statistics on lists, providing a comprehensive overview of Python programming concepts.

Uploaded by

odbrlp9282
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)
4 views5 pages

Python Spreadsheet

The document is a cheat sheet for beginners learning Python, covering essential topics such as lists, dictionaries, tuples, and functions. It includes examples of list comprehensions, conditional statements, and user input handling. Additionally, it discusses file operations, classes, and basic statistics on lists, providing a comprehensive overview of Python programming concepts.

Uploaded by

odbrlp9282
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

Lists (cont) Dictionaries

Beginners Python List comprehensions Dictionaries store connectionsbetween


Een em m Ciconay
a
pieces of
Key-value pair.
1s a

squares [x**2 forx in range(1, 11)]


A simple dictionary
Cheat Sheet Slicing a list allen ( color": green, Points: 5)

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

bikes [trek", redline, 'giant']


less 1
Oequal to
x
x
42
42 Your programs can prompt the user for input Al input is
Get the first item in a list Conditional test with lists
storedas asting
Prompting for a value
first_bike bikes[0] trek innotbikes
in bikes
name
input ("What s your name?
Get the last tem in a list Surly Prant ello, name )

bikes[-1] Assigning boolean values Prompting for numerical input


last bike -

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!")

bikes l If-elif-else statements


[Link] tre
ppenene
[Link]("giant
4:
ticket price -
Python Crash Course
Making numerical lists elifticket
age <price
18: 1e
Covers Python 3 and Python 2
squares 0 else:
for x in range(1,
11): [Link]/pythoncrashcourse
[Link] (x*2) ticketprice - 15
Working Witn i e s
Classes
While loops
A Whie loop repeats a bioCK Of C0de as long9 as a certain A class detines the behavior of an object and the kindo nread redrom ies and write to tiles. Fles
( ) by deraui, Dut can also be
are
opened in mode
ntormation an object can store hetmar
noronn
Delong to a class
Opened in write mode (wj and append mode ( a )
es andunctions the attributes and
A Simple while loop r e called
methods. A child cla5s inhenits Reading a file and storing its lines
Tiefhods from its parent class.
current_value 1 ilename
filename siddhartha. txt'
wh1le
current value 5: Creating a dog class 1name) as
file_object
print(current_value) 1ines file_object.readlines()
current_value class DoE) epresent a dog.
"**

Letting the user cho00se when to quit for 1ine in lines:

def init_(self, name): print(1ine)


msg Initialize dog object.
Writing to a file
while ns8nut(What"s your mes sage?)
[Link] name

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!")

print("Your tickets are printing. ")

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.

sum add numbers(3,


print(sum)
5) If you haven't done so already, take a few minutes
More cheat sheets available at
and describe three projects you'd like to create.
[Link]/pcc/
Adding elements Sorung a s t

Beginner's Python You can add


elements
themwherever you like in as
fo
the end of a list, or you can insert eThe Soo menod chges
sorted) function returns
original list unchanged. You can sor ne
tne order
ofa list permanentiy.
a copy of the fist, leaving the

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

Find the length of a list


Covers Python 3 and Python 2
Changing an element
num_users len(users)
users[ print ("We have str(num_users) users. ")
wsersi-2] valerie
ron [Link]/pythoncrashcourse
The ranged function Copying a ist
functior Sel o
To copy alist make a slice that starts at the first item and tuple is like a list, except you cant change the vakes in a
upleonce ts
Cent
hunction starts at 0 by ends at the last item you y to copy a i s Wou uSing
will atect
hrouahout the ife of
to n e coped ist desianated by parentheses instead
default, and stops one number below the number psseoo s approc, Wnalever you do
t. You can use the list) function to efficienty generate a
O St as well of square brackets. ((You can overwrite an entire tupie. Dut
you c a n t c h a n g e u e indivicdual e i e m e n s i n a tuple.
Making a copy of a list
Printing the numbers O to 1000 finishers[ kai, abeada, gus', zoe'] Defininga tuple
finishers[ ]
for
number in range(1001):
print(number)
copy_offinishers aimensions (8e, b60)

List comprehensions Looping through a tuple


Printing the numbers 1 to 1000
in
for number in range(1, 1001):
You can use a loop to generate a ist based on arange of
for
dimension dimensions:
print number numbers or on another list. This is a common operalion, s0 print(dimens1on)
Python offers a more ecent wao
1 to a milion t;it so, use the Overwriting a tuple
Making a list of numbers from a c h until you're ready to start ue dimensions (866, 600)
numbers list(range(1, 100e001)) omprehensions. peznoenszons)
To write a comprehension, define an expression
alues you want to store in tne fist. h e n wile a
for the
lor loop to
Simple statistics dimensions (1280, 9O0)
v a u e s needed to make the list.
There are Saistics you can run on a ist
onta Using a loop to generate a list of square numbers Visualizing your code
the minimum value in list
Finding a
squares 11):
When you're first leaming about data structures 5UCha5
ages(93, 99, 66, 17, 85, 1, 35, 82, 2, 77] O xn range(1, STS, Re ntor eoms areat too a

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

trstthree finishers [ :3] Styling your code el dogs[®]


[Link]( "peso)
Getting the middle three items Readability counts print (dogs)
Use four spaces perindentation
level.
middle_three finishers [1:4] Keep your lines to 79 characters or fewer.
Getting the last three items lines to group parts of your
Use singleblank
program visually.
More cheat sheets available at
last three finishers[-3:] [Link]/pcc/
.00ping tnrougn à dictionary
Adding new key-value pairs

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

oop thirough al the key-value pairs, all


the keys, or all the

Cheat Sheet Oe cicny and


Selt equal newto the
he
new key in square brackets,
value.
and
Adictionany only tracks the connectons betweon keys
a n f vou want to process the information in order
This also alows you to start with an empty aictionary and
you can sort the keys in your loop.
Dictionaries add key-value pairs as they

Adding a key-value pair


Deconmereievant
Looping through all key-value pairs

alien_e'color": 'green. 'points': 5} Store people'sfavorite languages.


What are dictionaries? fav languages
alien_ 2525 jen': 'python,
Python's dictionaries allow you to connect pieces of alien_e['y'i sarah'
relatedintormaion Eacn piece ofinOrnaonn alien_et speed 1.5 edward': 'ruby
Oicuonaly ho vale aesociated Adding to an empty dictionary phil Python
provide a Vean looo through all the key-value
witn ua Vevs. Or all the aliene r #Show each person's favorite language.
paits, d me keys, or values.
the values.
aenecolor green for name, language in fav_languages. items ):
alien_B[ points] S
print (name anguage)
Defining a dictionary
Modifying values Looping through all the keys
Use braces
curly to define detionay. Use colons to
a
connect keys and values, and use commas to separate
individual key-value pairs.
You can modily the value associated withdictionary
dictonary
any key ina
To do so gve the n a m e of the and
#Show everyone who's taken the survey
for name in fav_1anguages. keys():
in square brackets, then provide the new
Making a dictionary enclose the key
Value tor that key. print(name)
Looping through all the values
alien_ ('color": 'green', points': 5) Modifying values in a dictionary
all that chosen.
alien_e ('color': 'green', 'points: 5) Show the languages have been
Accessing values CS, values(:
To access the value associated with an indVduRl Key give
print(alien_ 0) print (language)
the name of dictionary
the

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)

alien_e ('color": "green"

alien_color alien_ [Link]("color)


del alien_er 'points ]
print (alien_0) Python Crash Course
Covers Python 3 and Python2
alien_points alien_B.get("points, e)

print (alien_color) Visualizing


Ty running
dictionariesexamples
of these [Link]/pythoncrashcourse
print (alien_points) some on
[Link]

You might also like