Sunteți pe pagina 1din 14

Dictionaries store connections between pieces of

List comprehensions information. Each item in a dictionary is a key-value pair.


squares = [x**2 for x in range(1, 11)] A simple dictionary
Slicing a list alien = {'color': 'green', 'points': 5}
finishers = ['sam', 'bob', 'ada', 'bea']
Accessing a value
first_two = finishers[:2]
print("The alien's color is ' + alien['color'])
Variables are used to store values. A string is a series of Copying a list
characters, surrounded by single or double quotes. Adding a new key-value pair
copy_of_bikes = bikes[:]
Hello world alien['x_position'] = 0
print("Hello world!") Looping through all key-value pairs
Hello world with a variable Tuples are similar to lists, but the items in a tuple can't be fav_numbers = {'eric': 17, 'ever': 4}
modified. for name, number in fav_numbers.items():
msg = "Hello world!"
print(name + ' loves ' + str(number))
print(msg) Making a tuple
Concatenation (combining strings) dimensions = (1920, 1080)
Looping through all keys
fav_numbers = {'eric': 17, 'ever': 4}
first_name = 'albert'
for name in fav_numbers.keys():
last_name = 'einstein'
print(name + ' loves a number')
full_name = first_name + ' ' + last_name If statements are used to test for particular conditions and
print(full_name) respond appropriately. Looping through all the values
Conditional tests fav_numbers = {'eric': 17, 'ever': 4}
for number in fav_numbers.values():
equals x == 42 print(str(number) + ' is a favorite')
A list stores a series of items in a particular order. You
not equal x != 42
access items using an index, or within a loop.
greater than x > 42
Make a list or equal to x >= 42
less than x < 42 Your programs can prompt the user for input. All input is
bikes = ['trek', 'redline', 'giant'] or equal to x <= 42 stored as a string.
Get the first item in a list Conditional test with lists Prompting for a value
first_bike = bikes[0] 'trek' in bikes name = input("What's your name? ")
Get the last item in a list 'surly' not in bikes print("Hello, " + name + "!")
last_bike = bikes[-1] Boolean values Prompting for numerical 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 if age >= 18: pi = float(pi)
print("You can vote!")
bikes = []
bikes.append('trek') If-elif-else statements
bikes.append('redline') if age < 4:
bikes.append('giant') ticket_price = 0
Making numerical lists elif age < 18: Covers Python 3 and Python 2
ticket_price = 10
squares = [] else:
for x in range(1, 11): ticket_price = 15
squares.append(x**2)
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. Files
condition is true. information an object can store. The information in a class are opened in read mode ('r') by default, but can also be
is stored in attributes, and functions that belong to a class opened in write mode ('w') and append mode ('a').
A simple while loop are called methods. A child class inherits the attributes and
methods from its parent class. Reading a file and storing its lines
current_value = 1
while current_value <= 5: filename = 'siddhartha.txt'
Creating a dog class
print(current_value) with open(filename) as file_object:
current_value += 1 class Dog(): lines = file_object.readlines()
"""Represent a dog."""
Letting the user choose when to quit for line in lines:
msg = '' def __init__(self, name): print(line)
while msg != 'quit': """Initialize dog object."""
self.name = name Writing to a file
msg = input("What's your message? ")
print(msg) filename = 'journal.txt'
def sit(self): with open(filename, 'w') as file_object:
"""Simulate sitting.""" file_object.write("I love programming.")
print(self.name + " is sitting.")
Functions are named blocks of code, designed to do one Appending to a file
specific job. Information passed to a function is called an my_dog = Dog('Peso')
argument, and information received by a function is called a filename = 'journal.txt'
parameter. with open(filename, 'a') as file_object:
print(my_dog.name + " is a great dog!") file_object.write("\nI love making games.")
A simple function my_dog.sit()

def greet_user(): Inheritance


"""Display a simple greeting.""" class SARDog(Dog): Exceptions help you respond appropriately to errors that
print("Hello!") """Represent a search dog.""" are likely to occur. You place code that might cause an
error in the try block. Code that should run in response to
greet_user() def __init__(self, name): an error goes in the except block. Code that should run only
Passing an argument """Initialize the sardog.""" if the try block was successful goes in the else block.
super().__init__(name)
def greet_user(username): Catching an exception
"""Display a personalized greeting.""" def search(self): prompt = "How many tickets do you need? "
print("Hello, " + username + "!") "Simulate searching.""" num_tickets = input(prompt)
print(self.name + " is searching.")
greet_user('jesse') try:
my_dog = SARDog('Willie') num_tickets = int(num_tickets)
Default values for parameters
except ValueError:
def make_pizza(topping='bacon'): print(my_dog.name + " is a search dog.") print("Please try again.")
"""Make a single-topping pizza.""" my_dog.sit() else:
print("Have a " + topping + " pizza!") my_dog.search() print("Your tickets are printing.")

make_pizza()
make_pizza('pepperoni')
If you had infinite programming skills, what would you Simple is better than complex
Returning a value build?
If you have a choice between a simple and a complex
def add_numbers(x, y): As you're learning to program, it's helpful to think solution, and both work, use the simple solution. Your
"""Add two numbers and return the sum.""" about the real-world projects you'd like to create. It's
return x + y code will be easier to maintain, and it will be easier
a good habit to keep an "ideas" notebook that you for you and others to build on that code later on.
can refer to whenever you want to start a new project.
sum = add_numbers(3, 5)
print(sum)
If you haven't done so already, take a few minutes
and describe three projects you'd like to create. More cheat sheets available at
You can add elements to the end of a list, or you can insert The sort() method changes the order of a list permanently.
them wherever you like in a list. The sorted() function returns a copy of the list, leaving the
original list unchanged. You can sort the items in a list in
Adding an element to the end of the list alphabetical order, or reverse alphabetical order. You can
users.append('amy') also reverse the original order of the list. Keep in mind that
lowercase and uppercase letters may affect the sort order.
Starting with an empty list
Sorting a list permanently
users = []
A list stores a series of items in a particular order. users.append('val') users.sort()
Lists allow you to store sets of information in one users.append('bob') Sorting a list permanently in reverse alphabetical
place, whether you have just a few items or millions users.append('mia')
order
of items. Lists are one of Python's most powerful Inserting elements at a particular position
features readily accessible to new programmers, and users.sort(reverse=True)
they tie together many important concepts in users.insert(0, 'joe')
Sorting a list temporarily
programming. users.insert(3, 'bea')
print(sorted(users))
print(sorted(users, reverse=True))

You can remove elements by their position in a list, or by Reversing the order of a list
Use square brackets to define a list, and use commas to
separate individual items in the list. Use plural names for the value of the item. If you remove an item by its value, users.reverse()
lists, to make your code easier to read. Python removes only the first item that has that value.

Making a list Deleting an element by its position

users = ['val', 'bob', 'mia', 'ron', 'ned'] del users[-1] Lists can contain millions of items, so Python provides an
efficient way to loop through all the items in a list. When
Removing an item by its value you set up a loop, Python pulls each item from the list one
users.remove('mia') at a time and stores it in a temporary variable, which you
Individual elements in a list are accessed according to their provide a name for. This name should be the singular
position, called the index. The index of the first element is version of the list name.
0, the index of the second element is 1, and so forth. The indented block of code makes up the body of the
Negative indices refer to items at the end of the list. To get If you want to work with an element that you're removing loop, where you can work with each individual item. Any
a particular element, write the name of the list and then the from the list, you can "pop" the element. If you think of the lines that are not indented run after the loop is completed.
index of the element in square brackets. list as a stack of items, pop() takes an item off the top of the
stack. By default pop() returns the last element in the list,
Printing all items in a list
Getting the first element but you can also pop elements from any position in the list. for user in users:
first_user = users[0] print(user)
Pop the last item from a list
Getting the second element most_recent_user = users.pop() Printing a message for each item, and a separate
print(most_recent_user) message afterwards
second_user = users[1]
for user in users:
Getting the last element Pop the first item in a list
print("Welcome, " + user + "!")
newest_user = users[-1] first_user = users.pop(0)
print(first_user) print("Welcome, we're glad to see you all!")

Once you've defined a list, you can change individual


elements in the list. You do this by referring to the index of The len() function returns the number of items in a list.
the item you want to modify.
Find the length of a list
Covers Python 3 and Python 2
Changing an element num_users = len(users)
users[0] = 'valerie' print("We have " + str(num_users) + " users.")
users[-2] = 'ronald'
You can use the range() function to work with a set of To copy a list make a slice that starts at the first item and A tuple is like a list, except you can't change the values in a
numbers efficiently. The range() function starts at 0 by ends at the last item. If you try to copy a list without using tuple once it's defined. Tuples are good for storing
default, and stops one number below the number passed to this approach, whatever you do to the copied list will affect information that shouldn't be changed throughout the life of
it. You can use the list() function to efficiently generate a the original list as well. a program. Tuples are designated by parentheses instead
large list of numbers. of square brackets. (You can overwrite an entire tuple, but
Making a copy of a list you can't change the individual elements in a tuple.)
Printing the numbers 0 to 1000
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe'] Defining a tuple
for number in range(1001): copy_of_finishers = finishers[:]
print(number) dimensions = (800, 600)

Printing the numbers 1 to 1000 Looping through a tuple


for number in range(1, 1001): You can use a loop to generate a list based on a range of for dimension in dimensions:
print(number) numbers or on another list. This is a common operation, so print(dimension)
Python offers a more efficient way to do it. List
Making a list of numbers from 1 to a million comprehensions may look complicated at first; if so, use the Overwriting a tuple
for loop approach until you're ready to start using dimensions = (800, 600)
numbers = list(range(1, 1000001)) comprehensions. print(dimensions)
To write a comprehension, define an expression for the
values you want to store in the list. Then write a for loop to
dimensions = (1200, 900)
generate input values needed to make the list.
There are a number of simple statistics you can run on a list
containing numerical data. Using a loop to generate a list of square numbers
Finding the minimum value in a list squares = [] When you're first learning about data structures such as
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] for x in range(1, 11): lists, it helps to visualize how Python is working with the
youngest = min(ages) square = x**2 information in your program. pythontutor.com is a great tool
squares.append(square) for seeing how Python keeps track of the information in a
Finding the maximum value list. Try running the following code on pythontutor.com, and
Using a comprehension to generate a list of square
then run your own code.
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] numbers
oldest = max(ages) 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.append('willie')
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77]
names = ['kai', 'abe', 'ada', 'gus', 'zoe'] dogs.append('hootz')
total_years = sum(ages)
dogs.append('peso')
upper_names = [] dogs.append('goblin')
for name in names:
You can work with any set of elements from a list. A portion upper_names.append(name.upper()) for dog in dogs:
of a list is called a slice. To slice a list start with the index of print("Hello " + dog + "!")
Using a comprehension to convert a list of names to print("I love these dogs!")
the first item you want, then add a colon and the index after
the last item you want. Leave off the first index to start at upper case
the beginning of the list, and leave off the last index to slice print("\nThese were my first two dogs:")
names = ['kai', 'abe', 'ada', 'gus', 'zoe']
through the end of the list. old_dogs = dogs[:2]
for old_dog in old_dogs:
Getting the first three items upper_names = [name.upper() for name in names]
print(old_dog)
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe']
first_three = finishers[:3] del dogs[0]
Readability counts dogs.remove('peso')
Getting the middle three items print(dogs)
Use four spaces per indentation level.
middle_three = finishers[1:4]
Keep your lines to 79 characters or fewer.
Getting the last three items Use single blank lines to group parts of your More cheat sheets available at
last_three = finishers[-3:] program visually.
You can store as many key-value pairs as you want in a You can loop through a dictionary in three ways: you can
dictionary, until your computer runs out of memory. To add loop through all the key-value pairs, all the keys, or all the
a new key-value pair to an existing dictionary give the name values.
of the dictionary and the new key in square brackets, and A dictionary only tracks the connections between keys
set it equal to the new value. and values; it doesn't track the order of items in the
This also allows you to start with an empty dictionary and dictionary. If you want to process the information in order,
add key-value pairs as they become relevant. you can sort the keys in your loop.

Adding a key-value pair Looping through all key-value pairs


alien_0 = {'color': 'green', 'points': 5} # Store people's favorite languages.
fav_languages = {
alien_0['x'] = 0 'jen': 'python',
Python's dictionaries allow you to connect pieces of
alien_0['y'] = 25 'sarah': 'c',
related information. Each piece of information in a 'edward': 'ruby',
alien_0['speed'] = 1.5
dictionary is stored as a key-value pair. When you 'phil': 'python',
provide a key, Python returns the value associated Adding to an empty dictionary }
with that key. You can loop through all the key-value alien_0 = {}
pairs, all the keys, or all the values. alien_0['color'] = 'green' # Show each person's favorite language.
alien_0['points'] = 5 for name, language in fav_languages.items():
print(name + ": " + language)

Use curly braces to define a dictionary. Use colons to Looping through all the keys
connect keys and values, and use commas to separate You can modify the value associated with any key in a # Show everyone who's taken the survey.
individual key-value pairs. dictionary. To do so give the name of the dictionary and for name in fav_languages.keys():
enclose the key in square brackets, then provide the new print(name)
Making a dictionary
value for that key.
alien_0 = {'color': 'green', 'points': 5} Looping through all the values
Modifying values in a dictionary
# Show all the languages that have been chosen.
alien_0 = {'color': 'green', 'points': 5} for language in fav_languages.values():
print(alien_0) print(language)
To access the value associated with an individual key give
the name of the dictionary and then place the key in a set of # 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_0['color'] = 'yellow'
dictionary, an error will occur. # Show each person's favorite language,
alien_0['points'] = 10 # in order by the person's name.
You can also use the get() method, which returns None print(alien_0)
instead of an error if the key doesn't exist. You can also for name in sorted(fav_languages.keys()):
specify a default value to use if the key is not in the print(name + ": " + language)
dictionary.
Getting the value associated with a key You can remove any key-value pair you want from a
dictionary. To do so use the del keyword and the dictionary
You can find the number of key-value pairs in a dictionary.
alien_0 = {'color': 'green', 'points': 5} name, followed by the key in square brackets. This will
delete the key and its associated value. Finding a dictionary's length
print(alien_0['color'])
print(alien_0['points']) Deleting a key-value pair num_responses = len(fav_languages)
alien_0 = {'color': 'green', 'points': 5}
Getting the value with get()
print(alien_0)
alien_0 = {'color': 'green'}
del alien_0['points']
alien_color = alien_0.get('color') print(alien_0)
alien_points = alien_0.get('points', 0) Covers Python 3 and Python 2

print(alien_color)
print(alien_points) Try running some of these examples on pythontutor.com.
It's sometimes useful to store a set of dictionaries in a list; Storing a list inside a dictionary alows you to associate Standard Python dictionaries don't keep track of the order
this is called nesting. more than one value with each key. in which keys and values are added; they only preserve the
association between each key and its value. If you want to
Storing dictionaries in a list Storing lists in a dictionary preserve the order in which keys and values are added, use
# Start with an empty list. # Store multiple languages for each person. an OrderedDict.
users = [] fav_languages = { Preserving the order of keys and values
'jen': ['python', 'ruby'],
# Make a new user, and add them to the list. 'sarah': ['c'], from collections import OrderedDict
new_user = { 'edward': ['ruby', 'go'],
'last': 'fermi', 'phil': ['python', 'haskell'], # Store each person's languages, keeping
'first': 'enrico', } # track of who respoded first.
'username': 'efermi', fav_languages = OrderedDict()
} # Show all responses for each person.
users.append(new_user) for name, langs in fav_languages.items(): fav_languages['jen'] = ['python', 'ruby']
print(name + ": ") fav_languages['sarah'] = ['c']
# Make another new user, and add them as well. for lang in langs: fav_languages['edward'] = ['ruby', 'go']
new_user = { print("- " + lang) fav_languages['phil'] = ['python', 'haskell']
'last': 'curie',
'first': 'marie', # Display the results, in the same order they
'username': 'mcurie', # were entered.
} You can store a dictionary inside another dictionary. In this for name, langs in fav_languages.items():
users.append(new_user) case each value associated with a key is itself a dictionary. print(name + ":")
for lang in langs:
Storing dictionaries in a dictionary print("- " + lang)
# Show all information about each user.
for user_dict in users: users = {
for k, v in user_dict.items(): 'aeinstein': {
print(k + ": " + v) 'first': 'albert',
'last': 'einstein', You can use a loop to generate a large number of
print("\n")
'location': 'princeton', dictionaries efficiently, if all the dictionaries start out with
You can also define a list of dictionaries directly, }, similar data.
without using append(): 'mcurie': { A million aliens
# Define a list of users, where each user 'first': 'marie',
'last': 'curie', aliens = []
# is represented by a dictionary.
users = [ 'location': 'paris',
}, # Make a million green aliens, worth 5 points
{ # each. Have them all start in one row.
'last': 'fermi', }
for alien_num in range(1000000):
'first': 'enrico', new_alien = {}
'username': 'efermi', for username, user_dict in users.items():
print("\nUsername: " + username) new_alien['color'] = 'green'
}, new_alien['points'] = 5
{ full_name = user_dict['first'] + " "
full_name += user_dict['last'] new_alien['x'] = 20 * alien_num
'last': 'curie', new_alien['y'] = 0
'first': 'marie', location = user_dict['location']
aliens.append(new_alien)
'username': 'mcurie',
}, print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title()) # Prove the list contains a million aliens.
] num_aliens = len(aliens)
# Show all information about each user. print("Number of aliens created:")
for user_dict in users: Nesting is extremely useful in certain situations. However, print(num_aliens)
for k, v in user_dict.items(): be aware of making your code overly complex. If you're
print(k + ": " + v) nesting items much deeper than what you see here there
print("\n") are probably simpler ways of managing your data, such as More cheat sheets available at
using classes.
Testing numerical values is similar to testing string values. Several kinds of if statements exist. Your choice of which to
use depends on the number of conditions you need to test.
Testing equality and inequality You can have as many elif blocks as you need, and the
>>> age = 18 else block is always optional.
>>> age == 18 Simple if statement
True
>>> age != 18 age = 19
False
if age >= 18:
Comparison operators print("You're old enough to vote!")
>>> age = 19 If-else statements
>>> age < 21
True age = 17
>>> age <= 21
True if age >= 18:
If statements allow you to examine the current state >>> age > 21 print("You're old enough to vote!")
of a program and respond appropriately to that state. False else:
>>> age >= 21 print("You can't vote yet.")
You can write a simple if statement that checks one
False
condition, or you can create a complex series of if The if-elif-else chain
statements that idenitfy the exact conditions you're
age = 12
looking for.
You can check multiple conditions at the same time. The if age < 4:
While loops run as long as certain conditions remain and operator returns True if all the conditions listed are price = 0
true. You can use while loops to let your programs True. The or operator returns True if any condition is True. elif age < 18:
run as long as your users want them to. Using and to check multiple conditions price = 5
else:
>>> age_0 = 22 price = 10
>>> age_1 = 18
A conditional test is an expression that can be evaluated as >>> age_0 >= 21 and age_1 >= 21 print("Your cost is $" + str(price) + ".")
True or False. Python uses the values True and False to False
decide whether the code in an if statement should be >>> age_1 = 23
executed. >>> age_0 >= 21 and age_1 >= 21
True You can easily test whether a certain value is in a list. You
Checking for equality
A single equal sign assigns a value to a variable. A double equal can also test whether a list is empty before trying to loop
Using or to check multiple conditions through the list.
sign (==) checks whether two values are equal.
>>> age_0 = 22 Testing if a value is in a list
>>> car = 'bmw'
>>> age_1 = 18
>>> car == 'bmw' >>> players = ['al', 'bea', 'cyn', 'dale']
>>> age_0 >= 21 or age_1 >= 21
True >>> 'al' in players
True
>>> car = 'audi' True
>>> age_0 = 18
>>> car == 'bmw' >>> 'eric' in players
>>> age_0 >= 21 or age_1 >= 21
False False
False
Ignoring case when making a comparison
>>> car = 'Audi'
>>> car.lower() == 'audi' A boolean value is either True or False. Variables with
True boolean values are often used to keep track of certain
conditions within a program.
Checking for inequality Covers Python 3 and Python 2
Simple boolean values
>>> topping = 'mushrooms'
>>> topping != 'anchovies' game_active = True
True can_edit = False
Testing if a value is not in a list Letting the user choose when to quit Using continue in a loop
banned_users = ['ann', 'chad', 'dee'] prompt = "\nTell me something, and I'll " banned_users = ['eve', 'fred', 'gary', 'helen']
user = 'erin' prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program. " prompt = "\nAdd a player to your team."
if user not in banned_users: prompt += "\nEnter 'quit' when you're done. "
print("You can play!") message = ""
while message != 'quit': players = []
Checking if a list is empty message = input(prompt) while True:
players = [] player = input(prompt)
if message != 'quit': if player == 'quit':
if players: print(message) break
for player in players: elif player in banned_users:
Using a flag print(player + " is banned!")
print("Player: " + player.title())
else: prompt = "\nTell me something, and I'll " continue
print("We have no players yet!") prompt += "repeat it back to you." else:
prompt += "\nEnter 'quit' to end the program. " players.append(player)

active = True print("\nYour team:")


You can allow your users to enter input using the input() while active: for player in players:
statement. In Python 3, all input is stored as a string. message = input(prompt) print(player)

Simple input
if message == 'quit':
name = input("What's your name? ") active = False Every while loop needs a way to stop running so it won't
print("Hello, " + name + ".") else: continue to run forever. If there's no way for the condition to
print(message) become False, the loop will never stop running.
Accepting numerical input
Using break to exit a loop An infinite loop
age = input("How old are you? ")
age = int(age) prompt = "\nWhat cities have you visited?" while True:
prompt += "\nEnter 'quit' when you're done. " name = input("\nWho are you? ")
if age >= 18: print("Nice to meet you, " + name + "!")
print("\nYou can vote!") while True:
else: city = input(prompt)
print("\nYou can't vote yet.")
if city == 'quit': The remove() method removes a specific value from a list,
Accepting input in Python 2.7 break
Use raw_input() in Python 2.7. This function interprets all input as a
but it only removes the first instance of the value you
string, just as input() does in Python 3.
else: provide. You can use a while loop to remove all instances
print("I've been to " + city + "!") of a particular value.
name = raw_input("What's your name? ")
print("Hello, " + name + ".") Removing all cats from a list of pets
pets = ['dog', 'cat', 'dog', 'fish', 'cat',
Sublime Text doesn't run programs that prompt the user for
'rabbit', 'cat']
input. You can use Sublime Text to write programs that
prompt for input, but you'll need to run these programs from print(pets)
A while loop repeats a block of code as long as a condition
is True. a terminal.
while 'cat' in pets:
Counting to 5 pets.remove('cat')

current_number = 1 print(pets)
You can use the break statement and the continue
statement with any of Python's loops. For example you can
while current_number <= 5: use break to quit a for loop that's working through a list or a
print(current_number) dictionary. You can use continue to skip over certain items More cheat sheets available at
current_number += 1 when looping through a list or dictionary as well.
The two main kinds of arguments are positional and A function can return a value or a set of values. When a
keyword arguments. When you use positional arguments function returns a value, the calling line must provide a
Python matches the first argument in the function call with variable in which to store the return value. A function stops
the first parameter in the function definition, and so forth. running when it reaches a return statement.
With keyword arguments, you specify which parameter
each argument should be assigned to in the function call. Returning a single value
When you use keyword arguments, the order of the def get_full_name(first, last):
arguments doesn't matter. """Return a neatly formatted full name."""
Using positional arguments full_name = first + ' ' + last
return full_name.title()
def describe_pet(animal, name):
Functions are named blocks of code designed to do """Display information about a pet.""" musician = get_full_name('jimi', 'hendrix')
print("\nI have a " + animal + ".") print(musician)
one specific job. Functions allow you to write code
print("Its name is " + name + ".")
once that can then be run whenever you need to Returning a dictionary
accomplish the same task. Functions can take in the describe_pet('hamster', 'harry') def build_person(first, last):
information they need, and return the information they describe_pet('dog', 'willie') """Return a dictionary of information
generate. Using functions effectively makes your about a person.
programs easier to write, read, test, and fix. Using keyword arguments
"""
def describe_pet(animal, name): person = {'first': first, 'last': last}
"""Display information about a pet.""" return person
The first line of a function is its definition, marked by the print("\nI have a " + animal + ".")
keyword def. The name of the function is followed by a set print("Its name is " + name + ".") musician = build_person('jimi', 'hendrix')
of parentheses and a colon. A docstring, in triple quotes, print(musician)
describes what the function does. The body of a function is describe_pet(animal='hamster', name='harry')
describe_pet(name='willie', animal='dog') Returning a dictionary with optional values
indented one level.
To call a function, give the name of the function followed def build_person(first, last, age=None):
by a set of parentheses. """Return a dictionary of information
about a person.
Making a function You can provide a default value for a parameter. When
"""
function calls omit this argument the default value will be
def greet_user(): used. Parameters with default values must be listed after person = {'first': first, 'last': last}
"""Display a simple greeting.""" parameters without default values in the function's definition if age:
print("Hello!") so positional arguments can still work correctly. person['age'] = age
return person
greet_user() Using a default value
musician = build_person('jimi', 'hendrix', 27)
def describe_pet(name, animal='dog'):
print(musician)
"""Display information about a pet."""
Information that's passed to a function is called an print("\nI have a " + animal + ".")
musician = build_person('janis', 'joplin')
argument; information that's received by a function is called print("Its name is " + name + ".")
print(musician)
a parameter. Arguments are included in parentheses after
the function's name, and parameters are listed in describe_pet('harry', 'hamster')
parentheses in the function's definition. describe_pet('willie')
Try running some of these examples on pythontutor.com.
Passing a single argument Using None to make an argument optional
def greet_user(username): def describe_pet(animal, name=None):
"""Display a simple greeting.""" """Display information about a pet."""
print("Hello, " + username + "!") print("\nI have a " + animal + ".")
if name:
print("Its name is " + name + ".")
Covers Python 3 and Python 2
greet_user('jesse')
greet_user('diana')
greet_user('brandon') describe_pet('hamster', 'harry')
describe_pet('snake')
You can pass a list as an argument to a function, and the Sometimes you won't know how many arguments a You can store your functions in a separate file called a
function can work with the values in the list. Any changes function will need to accept. Python allows you to collect an module, and then import the functions you need into the file
the function makes to the list will affect the original list. You arbitrary number of arguments into one parameter using the containing your main program. This allows for cleaner
can prevent a function from modifying a list by passing a * operator. A parameter that accepts an arbitrary number of program files. (Make sure your module is stored in the
copy of the list as an argument. arguments must come last in the function definition. same directory as your main program.)
The ** operator allows a parameter to collect an arbitrary
Passing a list as an argument number of keyword arguments. Storing a function in a module
File: pizza.py
def greet_users(names): Collecting an arbitrary number of arguments
"""Print a simple greeting to everyone.""" def make_pizza(size, *toppings):
for name in names: def make_pizza(size, *toppings): """Make a pizza."""
msg = "Hello, " + name + "!" """Make a pizza.""" print("\nMaking a " + size + " pizza.")
print(msg) print("\nMaking a " + size + " pizza.") print("Toppings:")
print("Toppings:") for topping in toppings:
usernames = ['hannah', 'ty', 'margot'] for topping in toppings: print("- " + topping)
greet_users(usernames) print("- " + topping)
Importing an entire module
Allowing a function to modify a list File: making_pizzas.py
# Make three pizzas with different toppings. Every function in the module is available in the program file.
The following example sends a list of models to a function for
make_pizza('small', 'pepperoni')
printing. The original list is emptied, and the second list is filled. import pizza
make_pizza('large', 'bacon bits', 'pineapple')
def print_models(unprinted, printed): make_pizza('medium', 'mushrooms', 'peppers',
"""3d print a set of models.""" 'onions', 'extra cheese') pizza.make_pizza('medium', 'pepperoni')
while unprinted: pizza.make_pizza('small', 'bacon', 'pineapple')
current_model = unprinted.pop() Collecting an arbitrary number of keyword arguments
Importing a specific function
print("Printing " + current_model) def build_profile(first, last, **user_info): Only the imported functions are available in the program file.
printed.append(current_model) """Build a user's profile dictionary."""
# Build a dict with the required keys. from pizza import make_pizza
# Store some unprinted designs, profile = {'first': first, 'last': last}
# and print each of them. make_pizza('medium', 'pepperoni')
unprinted = ['phone case', 'pendant', 'ring'] # Add any other keys and values. make_pizza('small', 'bacon', 'pineapple')
printed = [] for key, value in user_info.items():
print_models(unprinted, printed) Giving a module an alias
profile[key] = value
import pizza as p
print("\nUnprinted:", unprinted) return profile
print("Printed:", printed) p.make_pizza('medium', 'pepperoni')
# Create two users with different kinds p.make_pizza('small', 'bacon', 'pineapple')
Preventing a function from modifying a list
The following example is the same as the previous one, except the # of information.
user_0 = build_profile('albert', 'einstein',
Giving a function an alias
original list is unchanged after calling print_models().
location='princeton') from pizza import make_pizza as mp
def print_models(unprinted, printed): user_1 = build_profile('marie', 'curie',
"""3d print a set of models.""" location='paris', field='chemistry') mp('medium', 'pepperoni')
while unprinted: mp('small', 'bacon', 'pineapple')
current_model = unprinted.pop() print(user_0)
print("Printing " + current_model) print(user_1) Importing all functions from a module
printed.append(current_model) Don't do this, but recognize it when you see it in others' code. It
can result in naming conflicts, which can cause errors.
# Store some unprinted designs, from pizza import *
# and print each of them. As you can see there are many ways to write and call a
original = ['phone case', 'pendant', 'ring'] function. When you're starting out, aim for something that make_pizza('medium', 'pepperoni')
printed = [] simply works. As you gain experience you'll develop an make_pizza('small', 'bacon', 'pineapple')
understanding of the more subtle advantages of different
print_models(original[:], printed) structures such as positional and keyword arguments, and
print("\nOriginal:", original) the various approaches to importing functions. For now if More cheat sheets available at
print("Printed:", printed) your functions do what you need them to, you're doing well.
If the class you're writing is a specialized version of another
Creating an object from a class class, you can use inheritance. When one class inherits
my_car = Car('audi', 'a4', 2016) from another, it automatically takes on all the attributes and
methods of the parent class. The child class is free to
Accessing attribute values introduce new attributes and methods, and override
attributes and methods of the parent class.
print(my_car.make)
To inherit from another class include the name of the
print(my_car.model)
parent class in parentheses when defining the new class.
print(my_car.year)
Classes are the foundation of object-oriented The __init__() method for a child class
Calling methods
programming. Classes represent real-world things
class ElectricCar(Car):
you want to model in your programs: for example my_car.fill_tank()
"""A simple model of an electric car."""
dogs, cars, and robots. You use a class to make my_car.drive()
objects, which are specific instances of dogs, cars, Creating multiple objects def __init__(self, make, model, year):
and robots. A class defines the general behavior that """Initialize an electric car."""
a whole category of objects can have, and the my_car = Car('audi', 'a4', 2016) super().__init__(make, model, year)
information that can be associated with those objects. my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)
Classes can inherit from each other you can # Attributes specific to electric cars.
write a class that extends the functionality of an # Battery capacity in kWh.
existing class. This allows you to code efficiently for a self.battery_size = 70
# Charge level in %.
wide variety of situations. You can modify an attribute's value directly, or you can
self.charge_level = 0
write methods that manage updating values more carefully.
Modifying an attribute directly Adding new methods to the child class
Consider how we might model a car. What information class ElectricCar(Car):
my_new_car = Car('audi', 'a4', 2016)
would we associate with a car, and what behavior would it --snip--
my_new_car.fuel_level = 5
have? The information is stored in variables called def charge(self):
attributes, and the behavior is represented by functions. Writing a method to update an attribute's value """Fully charge the vehicle."""
Functions that are part of a class are called methods. self.charge_level = 100
def update_fuel_level(self, new_level): print("The vehicle is fully charged.")
The Car class """Update the fuel level."""
class Car():
if new_level <= self.fuel_capacity: Using child methods and parent methods
self.fuel_level = new_level
"""A simple attempt to model a car.""" my_ecar = ElectricCar('tesla', 'model s', 2016)
else:
print("The tank can't hold that much!")
def __init__(self, make, model, year): my_ecar.charge()
"""Initialize car attributes.""" Writing a method to increment an attribute's value my_ecar.drive()
self.make = make
self.model = model def add_fuel(self, amount):
self.year = year """Add fuel to the tank."""
if (self.fuel_level + amount
# Fuel capacity and level in gallons. <= self.fuel_capacity): There are many ways to model real world objects and
self.fuel_capacity = 15 self.fuel_level += amount situations in code, and sometimes that variety can feel
self.fuel_level = 0 print("Added fuel.") overwhelming. Pick an approach and try it if your first
else: attempt doesn't work, try a different approach.
def fill_tank(self): print("The tank won't hold that much.")
"""Fill gas tank to capacity."""
self.fuel_level = self.fuel_capacity
print("Fuel tank is full.")
In Python class names are written in CamelCase and object Covers Python 3 and Python 2
def drive(self): names are written in lowercase with underscores. Modules
"""Simulate driving.""" that contain classes should still be named in lowercase with
print("The car is moving.") underscores.
Class files can get long as you add detailed information and
Overriding parent methods functionality. To help keep your program files uncluttered, Classes should inherit from object
class ElectricCar(Car): you can store your classes in modules and import the class ClassName(object):
--snip-- classes you need into your main program.
def fill_tank(self): The Car class in Python 2.7
Storing classes in a file
"""Display an error message.""" car.py class Car(object):
print("This car has no fuel tank!")
"""Represent gas and electric cars.""" Child class __init__() method is different
class ChildClassName(ParentClass):
class Car():
def __init__(self):
A class can have objects as attributes. This allows classes """A simple attempt to model a car."""
super(ClassName, self).__init__()
to work together to model complex situations. --snip
The ElectricCar class in Python 2.7
A Battery class class Battery():
"""A battery for an electric car.""" class ElectricCar(Car):
class Battery(): def __init__(self, make, model, year):
"""A battery for an electric car.""" --snip--
super(ElectricCar, self).__init__(
class ElectricCar(Car): make, model, year)
def __init__(self, size=70):
"""Initialize battery attributes.""" """A simple model of an electric car."""
# Capacity in kWh, charge level in %. --snip--
self.size = size Importing individual classes from a module A list can hold as many items as you want, so you can
self.charge_level = 0 my_cars.py make a large number of objects from a class and store
them in a list.
def get_range(self): from car import Car, ElectricCar Here's an example showing how to make a fleet of rental
"""Return the battery's range.""" cars, and make sure all the cars are ready to drive.
if self.size == 70: my_beetle = Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank() A fleet of rental cars
return 240
elif self.size == 85: my_beetle.drive() from car import Car, ElectricCar
return 270
my_tesla = ElectricCar('tesla', 'model s', # Make lists to hold a fleet of cars.
Using an instance as an attribute 2016) gas_fleet = []
my_tesla.charge() electric_fleet = []
class ElectricCar(Car):
my_tesla.drive()
--snip--
Importing an entire module # Make 500 gas cars and 250 electric cars.
def __init__(self, make, model, year): for _ in range(500):
"""Initialize an electric car.""" import car car = Car('ford', 'focus', 2016)
super().__init__(make, model, year) gas_fleet.append(car)
my_beetle = car.Car( for _ in range(250):
# Attribute specific to electric cars. 'volkswagen', 'beetle', 2016) ecar = ElectricCar('nissan', 'leaf', 2016)
self.battery = Battery() my_beetle.fill_tank() electric_fleet.append(ecar)
my_beetle.drive()
def charge(self): # Fill the gas cars, and charge electric cars.
"""Fully charge the vehicle.""" my_tesla = car.ElectricCar( for car in gas_fleet:
self.battery.charge_level = 100 'tesla', 'model s', 2016) car.fill_tank()
print("The vehicle is fully charged.") my_tesla.charge() for ecar in electric_fleet:
my_tesla.drive() ecar.charge()
Using the instance
Importing all classes from a module
my_ecar = ElectricCar('tesla', 'model x', 2016) (Dont do this, but recognize it when you see it.) print("Gas cars:", len(gas_fleet))
print("Electric cars:", len(electric_fleet))
from car import *
my_ecar.charge()
print(my_ecar.battery.get_range())
my_beetle = Car('volkswagen', 'beetle', 2016)
More cheat sheets available at
my_ecar.drive()
Storing the lines in a list Opening a file using an absolute path
filename = 'siddhartha.txt' f_path = "/home/ehmatthes/books/alice.txt"

with open(filename) as f_obj: with open(f_path) as f_obj:


lines = f_obj.readlines() lines = f_obj.readlines()

for line in lines: Opening a file on Windows


Windows will sometimes interpret forward slashes incorrectly. If
print(line.rstrip())
you run into this, use backslashes in your file paths.
f_path = "C:\Users\ehmatthes\books\alice.txt"
Your programs can read information in from files, and Passing the 'w' argument to open() tells Python you want to
they can write data to files. Reading from files allows with open(f_path) as f_obj:
write to the file. Be careful; this will erase the contents of lines = f_obj.readlines()
you to work with a wide variety of information; writing the file if it already exists. Passing the 'a' argument tells
to files allows users to pick up where they left off the Python you want to append to the end of an existing file.
next time they run your program. You can write text to
files, and you can store Python structures such as Writing to an empty file When you think an error may occur, you can write a try-
lists in data files. filename = 'programming.txt' except block to handle the exception that might be raised.
The try block tells Python to try running some code, and the
with open(filename, 'w') as f: except block tells Python what to do if the code results in a
Exceptions are special objects that help your
f.write("I love programming!") particular kind of error.
programs respond to errors in appropriate ways. For
example if your program tries to open a file that Writing multiple lines to an empty file Handling the ZeroDivisionError exception
doesnt exist, you can use exceptions to display an try:
informative error message instead of having the filename = 'programming.txt'
print(5/0)
program crash. except ZeroDivisionError:
with open(filename, 'w') as f:
f.write("I love programming!\n") print("You can't divide by zero!")
f.write("I love creating new games.\n") Handling the FileNotFoundError exception
To read from a file your program needs to open the file and
Appending to a file f_name = 'siddhartha.txt'
then read the contents of the file. You can read the entire
contents of the file at once, or read the file line by line. The filename = 'programming.txt'
with statement makes sure the file is closed properly when try:
the program has finished accessing the file. with open(filename, 'a') as f: with open(f_name) as f_obj:
f.write("I also love working with data.\n") lines = f_obj.readlines()
Reading an entire file at once f.write("I love making apps as well.\n") except FileNotFoundError:
filename = 'siddhartha.txt' msg = "Can't find file {0}.".format(f_name)
print(msg)
with open(filename) as f_obj:
contents = f_obj.read() When Python runs the open() function, it looks for the file in
the same directory where the program that's being excuted
is stored. You can open a file from a subfolder using a It can be hard to know what kind of exception to handle
print(contents) when writing code. Try writing your code without a try block,
relative path. You can also use an absolute path to open
Reading line by line any file on your system. and make it generate an error. The traceback will tell you
Each line that's read from the file has a newline character at the what kind of exception your program needs to handle.
end of the line, and the print function adds its own newline Opening a file from a subfolder
character. The rstrip() method gets rid of the the extra blank lines
this would result in when printing to the terminal.
f_path = "text_files/alice.txt"

filename = 'siddhartha.txt' with open(f_path) as f_obj:


lines = f_obj.readlines()
Covers Python 3 and Python 2
with open(filename) as f_obj:
for line in f_obj: for line in lines:
print(line.rstrip()) print(line.rstrip())
The try block should only contain code that may cause an Sometimes you want your program to just continue running The json module allows you to dump simple Python data
error. Any code that depends on the try block running when it encounters an error, without reporting the error to structures into a file, and load the data from that file the
successfully should be placed in the else block. the user. Using the pass statement in an else block allows next time the program runs. The JSON data format is not
you to do this. specific to Python, so you can share this kind of data with
Using an else block people who work in other languages as well.
Using the pass statement in an else block
print("Enter two numbers. I'll divide them.")
f_names = ['alice.txt', 'siddhartha.txt', Knowing how to manage exceptions is important when
x = input("First number: ") 'moby_dick.txt', 'little_women.txt'] working with stored data. You'll usually want to make sure
y = input("Second number: ") the data you're trying to load exists before working with it.
for f_name in f_names: Using json.dump() to store data
try: # Report the length of each file found.
result = int(x) / int(y) try: """Store some numbers."""
except ZeroDivisionError: with open(f_name) as f_obj:
print("You can't divide by zero!") lines = f_obj.readlines() import json
else: except FileNotFoundError:
print(result) # Just move on to the next file. numbers = [2, 3, 5, 7, 11, 13]
pass
Preventing crashes from user input else: filename = 'numbers.json'
Without the except block in the following example, the program with open(filename, 'w') as f_obj:
num_lines = len(lines)
would crash if the user tries to divide by zero. As written, it will
handle the error gracefully and keep running. msg = "{0} has {1} lines.".format( json.dump(numbers, f_obj)
f_name, num_lines)
"""A simple calculator for division only.""" print(msg)
Using json.load() to read data
"""Load some previously stored numbers."""
print("Enter two numbers. I'll divide them.")
print("Enter 'q' to quit.") import json
Exception-handling code should catch specific exceptions
while True: that you expect to happen during your program's execution. filename = 'numbers.json'
x = input("\nFirst number: ") A bare except block will catch all exceptions, including with open(filename) as f_obj:
if x == 'q': keyboard interrupts and system exits you might need when numbers = json.load(f_obj)
break forcing a program to close.
y = input("Second number: ") print(numbers)
if y == 'q': If you want to use a try block and you're not sure which
break exception to catch, use Exception. It will catch most Making sure the stored data exists
exceptions, but still allow you to interrupt programs
intentionally. import json
try:
result = int(x) / int(y) Dont use bare except blocks f_name = 'numbers.json'
except ZeroDivisionError:
print("You can't divide by zero!") try:
try:
else: # Do something
with open(f_name) as f_obj:
print(result) except:
numbers = json.load(f_obj)
pass
except FileNotFoundError:
Use Exception instead msg = "Cant find {0}.".format(f_name)
Well-written, properly tested code is not very prone to print(msg)
try: else:
internal errors such as syntax or logical errors. But every # Do something
time your program depends on something external such as print(numbers)
except Exception:
user input or the existence of a file, there's a possibility of pass
an exception being raised. Practice with exceptions
Printing the exception Take a program you've already written that prompts for user
It's up to you how to communicate errors to your users. input, and add some error-handling code to the program.
Sometimes users need to know if a file is missing; try:
sometimes it's better to handle the error silently. A little # Do something
except Exception as e: More cheat sheets available at
experience will help you know how much to report.
print(e, type(e))

S-ar putea să vă placă și