






Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!







Variables are used to store values. A string is a series of
characters, surrounded by single or double quotes.
print("Hello world!")
msg = "Hello world!"
print(msg)
first_name = 'albert'
last_name = 'einstein'
full_name = first_name + ' ' + last_name
print(full_name)
A list stores a series of items in a particular order. You
access items using an index, or within a loop.
bikes = ['trek', 'redline', 'giant']
first_bike = bikes[0]
last_bike = bikes[-1]
for bike in bikes:
print(bike)
bikes = []
bikes.append('trek')
bikes.append('redline')
bikes.append('giant')
squares = []
for x in range(1, 11):
squares.append(x**2)
squares = [x**2 for x in range(1, 11)]
finishers = ['sam', 'bob', 'ada', 'bea']
first_two = finishers[:2]
copy_of_bikes = bikes[:]
Tuples are similar to lists, but the items in a tuple can't be
modified.
dimensions = (1920, 1080)
If statements are used to test for particular conditions and
respond appropriately.
equals x == 42
not equal x != 42
greater than x > 42
or equal to x >= 42
less than x < 42
or equal to x <= 42
'trek' in bikes
'surly' not in bikes
game_active = True
can_edit = False
if age >= 18:
print("You can vote!")
if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
else:
ticket_price = 15
Dictionaries store connections between pieces of
information. Each item in a dictionary is a key-value pair.
alien = {'color': 'green', 'points': 5}
print("The alien's color is ' + alien['color'])
alien['x_position'] = 0
fav_numbers = {'eric': 17, 'ever': 4}
for name, number in fav_numbers.items():
print(name + ' loves ' + str(number))
fav_numbers = {'eric': 17, 'ever': 4}
for name in fav_numbers.keys():
print(name + ' loves a number')
fav_numbers = {'eric': 17, 'ever': 4}
for number in fav_numbers.values():
print(str(number) + ' is a favorite')
Your programs can prompt the user for input. All input is
stored as a string.
name = input("What's your name? ")
print("Hello, " + name + "!")
age = input("How old are you? ")
age = int(age)
pi = input("What's the value of pi? ")
pi = float(pi)
A while loop repeats a block of code as long as a certain
condition is true.
current_value = 1
while current_value <= 5:
print(current_value)
current_value += 1
msg = ''
while msg != 'quit':
msg = input("What's your message? ")
print(msg)
A class defines the behavior of an object and the kind of
information an object can store. The information in a class
is stored in attributes, and functions that belong to a class
are called methods. A child class inherits the attributes and
methods from its parent class.
class Dog():
"""Represent a dog."""
def init(self, name):
"""Initialize dog object."""
self.name = name
def sit(self):
"""Simulate sitting."""
print(self.name + " is sitting.")
my_dog = Dog('Peso')
print(my_dog.name + " is a great dog!")
my_dog.sit()
class SARDog(Dog):
"""Represent a search dog."""
def init(self, name):
"""Initialize the sardog."""
super().init(name)
def search(self):
"Simulate searching."""
print(self.name + " is searching.")
my_dog = SARDog('Willie')
print(my_dog.name + " is a search dog.")
my_dog.sit()
my_dog.search()
Your programs can read from files and write to files. Files
are opened in read mode ('r') by default, but can also be
opened in write mode ('w') and append mode ('a').
filename = 'siddhartha.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line)
filename = 'journal.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
filename = 'journal.txt'
with open(filename, 'a') as file_object:
file_object.write("\nI love making games.")
Exceptions help you respond appropriately to errors that
are likely to occur. You place code that might cause an
error in the try block. Code that should run in response to
an error goes in the except block. Code that should run only
if the try block was successful goes in the else block.
prompt = "How many tickets do you need? "
num_tickets = input(prompt)
try:
num_tickets = int(num_tickets)
except ValueError:
print("Please try again.")
else:
print("Your tickets are printing.")
Functions are named blocks of code, designed to do one
specific job. Information passed to a function is called an
argument, and information received by a function is called a
parameter.
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()
def greet_user(username):
"""Display a personalized greeting."""
print("Hello, " + username + "!")
greet_user('jesse')
def make_pizza(topping='bacon'):
"""Make a single-topping pizza."""
print("Have a " + topping + " pizza!")
make_pizza()
make_pizza('pepperoni')
def add_numbers(x, y):
"""Add two numbers and return the sum."""
return x + y
sum = add_numbers(3, 5)
print(sum)
If you had infinite programming skills, what would you
build?
Simple is better than complex
You can use the range() function to work with a set of
numbers efficiently. The range() function starts at 0 by
default, and stops one number below the number passed to
it. You can use the list() function to efficiently generate a
large list of numbers.
for number in range(1001):
print(number)
for number in range(1, 1001):
print(number)
numbers = list(range(1, 1000001))
To copy a list make a slice that starts at the first item and
ends at the last item. If you try to copy a list without using
this approach, whatever you do to the copied list will affect
the original list as well.
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe']
copy_of_finishers = finishers[:]
Readability counts
There are a number of simple statistics you can run on a list
containing numerical data.
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77]
youngest = min(ages)
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77]
oldest = max(ages)
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77]
total_years = sum(ages)
You can use a loop to generate a list based on a range of
numbers or on another list. This is a common operation, so
Python offers a more efficient way to do it. List
comprehensions may look complicated at first; if so, use the
for loop approach until you're ready to start using
comprehensions.
To write a comprehension, define an expression for the
values you want to store in the list. Then write a for loop to
generate input values needed to make the list.
squares = []
for x in range(1, 11):
square = x**
squares.append(square)
squares = [x**2 for x in range(1, 11)]
names = ['kai', 'abe', 'ada', 'gus', 'zoe']
upper_names = []
for name in names:
upper_names.append(name.upper())
names = ['kai', 'abe', 'ada', 'gus', 'zoe']
upper_names = [name.upper() for name in names]
You can work with any set of elements from a list. A portion
of a list is called a slice. To slice a list start with the index of
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
the beginning of the list, and leave off the last index to slice
through the end of the list.
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe']
first_three = finishers[:3]
middle_three = finishers[1:4]
last_three = finishers[-3:]
A tuple is like a list, except you can't change the values in a
tuple once it's defined. Tuples are good for storing
information that shouldn't be changed throughout the life of
a program. Tuples are designated by parentheses instead
of square brackets. (You can overwrite an entire tuple, but
you can't change the individual elements in a tuple.)
dimensions = (800, 600)
for dimension in dimensions:
print(dimension)
dimensions = (800, 600)
print(dimensions)
dimensions = (1200, 900)
When you're first learning about data structures such as
lists, it helps to visualize how Python is working with the
information in your program. pythontutor.com is a great tool
for seeing how Python keeps track of the information in a
list. Try running the following code on pythontutor.com, and
then run your own code.
dogs = []
dogs.append('willie')
dogs.append('hootz')
dogs.append('peso')
dogs.append('goblin')
for dog in dogs:
print("Hello " + dog + "!")
print("I love these dogs!")
print("\nThese were my first two dogs:")
old_dogs = dogs[:2]
for old_dog in old_dogs:
print(old_dog)
del dogs[0]
dogs.remove('peso')
print(dogs)
Use curly braces to define a dictionary. Use colons to
connect keys and values, and use commas to separate
individual key-value pairs.
alien_0 = {'color': 'green', 'points': 5}
You can loop through a dictionary in three ways: you can
loop through all the key-value pairs, all the keys, or all the
values.
A dictionary only tracks the connections between keys
and values; it doesn't track the order of items in the
dictionary. If you want to process the information in order,
you can sort the keys in your loop.
fav_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
for name, language in fav_languages.items():
print(name + ": " + language)
for name in fav_languages.keys():
print(name)
for language in fav_languages.values():
print(language)
for name in sorted(fav_languages.keys()):
print(name + ": " + 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
square brackets. If the key you're asking for is not in the
dictionary, an error will occur.
You can also use the get() method, which returns None
instead of an error if the key doesn't exist. You can also
specify a default value to use if the key is not in the
dictionary.
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
alien_0 = {'color': 'green'}
alien_color = alien_0.get('color')
alien_points = alien_0.get('points', 0)
print(alien_color)
print(alien_points)
You can modify the value associated with any key in a
dictionary. To do so give the name of the dictionary and
enclose the key in square brackets, then provide the new
value for that key.
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['color'] = 'yellow'
alien_0['points'] = 10
print(alien_0)
You can remove any key-value pair you want from a
dictionary. To do so use the del keyword and the dictionary
name, followed by the key in square brackets. This will
delete the key and its associated value.
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
You can store as many key-value pairs as you want in a
dictionary, until your computer runs out of memory. To add
a new key-value pair to an existing dictionary give the name
of the dictionary and the new key in square brackets, and
set it equal to the new value.
This also allows you to start with an empty dictionary and
add key-value pairs as they become relevant.
alien_0 = {'color': 'green', 'points': 5}
alien_0['x'] = 0
alien_0['y'] = 25
alien_0['speed'] = 1.
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
Try running some of these examples on pythontutor.com.
You can find the number of key-value pairs in a dictionary.
num_responses = len(fav_languages)
A conditional test is an expression that can be evaluated as
True or False. Python uses the values True and False to
decide whether the code in an if statement should be
executed.
A single equal sign assigns a value to a variable. A double equal
sign (==) checks whether two values are equal.
>>> car = 'bmw'
>>> car == 'bmw'
True
>>> car = 'audi'
>>> car == 'bmw'
False
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
>>> topping = 'mushrooms'
>>> topping != 'anchovies'
True
Testing numerical values is similar to testing string values.
>>> age = 18
>>> age == 18
True
>>> age != 18
False
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
Several kinds of if statements exist. Your choice of which to
use depends on the number of conditions you need to test.
You can have as many elif blocks as you need, and the
else block is always optional.
age = 19
if age >= 18:
print("You're old enough to vote!")
age = 17
if age >= 18:
print("You're old enough to vote!")
else:
print("You can't vote yet.")
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your cost is $" + str(price) + ".")
You can check multiple conditions at the same time. The
and operator returns True if all the conditions listed are
True. The or operator returns True if any condition is True.
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 23
>>> age_0 >= 21 and age_1 >= 21
True
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 or age_1 >= 21
False
A boolean value is either True or False. Variables with
boolean values are often used to keep track of certain
conditions within a program.
game_active = True
can_edit = False
You can easily test whether a certain value is in a list. You
can also test whether a list is empty before trying to loop
through the list.
>>> players = ['al', 'bea', 'cyn', 'dale']
>>> 'al' in players
True
>>> 'eric' in players
False
banned_users = ['ann', 'chad', 'dee']
user = 'erin'
if user not in banned_users:
print("You can play!")
players = []
if players:
for player in players:
print("Player: " + player.title())
else:
print("We have no players yet!")
prompt = "\nTell me something, and I'll "
prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
prompt = "\nTell me something, and I'll "
prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
prompt = "\nWhat cities have you visited?"
prompt += "\nEnter 'quit' when you're done. "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I've been to " + city + "!")
banned_users = ['eve', 'fred', 'gary', 'helen']
prompt = "\nAdd a player to your team."
prompt += "\nEnter 'quit' when you're done. "
players = []
while True:
player = input(prompt)
if player == 'quit':
break
elif player in banned_users:
print(player + " is banned!")
continue
else:
players.append(player)
print("\nYour team:")
for player in players:
print(player)
You can allow your users to enter input using the input()
statement. In Python 3, all input is stored as a string.
name = input("What's your name? ")
print("Hello, " + name + ".")
age = input("How old are you? ")
age = int(age)
if age >= 18:
print("\nYou can vote!")
else:
print("\nYou can't vote yet.")
Use raw_input() in Python 2.7. This function interprets all input as a
string, just as input() does in Python 3.
name = raw_input("What's your name? ")
print("Hello, " + name + ".")
A while loop repeats a block of code as long as a condition
is True.
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
Sublime Text doesn't run programs that prompt the user for
input. You can use Sublime Text to write programs that
prompt for input, but you'll need to run these programs from
a terminal.
Every while loop needs a way to stop running so it won't
continue to run forever. If there's no way for the condition to
become False, the loop will never stop running.
while True:
name = input("\nWho are you? ")
print("Nice to meet you, " + name + "!")
The remove() method removes a specific value from a list,
but it only removes the first instance of the value you
provide. You can use a while loop to remove all instances
of a particular value.
pets = ['dog', 'cat', 'dog', 'fish', 'cat',
'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets) You can use the break statement and the continue
statement with any of Python's loops. For example you can
use break to quit a for loop that's working through a list or a
dictionary. You can use continue to skip over certain items
when looping through a list or dictionary as well.
You can pass a list as an argument to a function, and the
function can work with the values in the list. Any changes
the function makes to the list will affect the original list. You
can prevent a function from modifying a list by passing a
copy of the list as an argument.
def greet_users(names):
"""Print a simple greeting to everyone."""
for name in names:
msg = "Hello, " + name + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
The following example sends a list of models to a function for
printing. The original list is emptied, and the second list is filled.
def print_models(unprinted, printed):
"""3d print a set of models."""
while unprinted:
current_model = unprinted.pop()
print("Printing " + current_model)
printed.append(current_model)
unprinted = ['phone case', 'pendant', 'ring']
printed = []
print_models(unprinted, printed)
print("\nUnprinted:", unprinted)
print("Printed:", printed)
The following example is the same as the previous one, except the
original list is unchanged after calling print_models().
def print_models(unprinted, printed):
"""3d print a set of models."""
while unprinted:
current_model = unprinted.pop()
print("Printing " + current_model)
printed.append(current_model)
original = ['phone case', 'pendant', 'ring']
printed = []
print_models(original[:], printed)
print("\nOriginal:", original)
print("Printed:", printed)
Sometimes you won't know how many arguments a
function will need to accept. Python allows you to collect an
arbitrary number of arguments into one parameter using the
* operator. A parameter that accepts an arbitrary number of
arguments must come last in the function definition.
The ** operator allows a parameter to collect an arbitrary
number of keyword arguments.
def make_pizza(size, *toppings):
"""Make a pizza."""
print("\nMaking a " + size + " pizza.")
print("Toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('small', 'pepperoni')
make_pizza('large', 'bacon bits', 'pineapple')
make_pizza('medium', 'mushrooms', 'peppers',
'onions', 'extra cheese')
def build_profile(first, last, **user_info):
"""Build a user's profile dictionary."""
profile = {'first': first, 'last': last}
for key, value in user_info.items():
profile[key] = value
return profile
user_0 = build_profile('albert', 'einstein',
location='princeton')
user_1 = build_profile('marie', 'curie',
location='paris', field='chemistry')
print(user_0)
print(user_1)
You can store your functions in a separate file called a
module, and then import the functions you need into the file
containing your main program. This allows for cleaner
program files. (Make sure your module is stored in the
same directory as your main program.)
File: pizza.py
def make_pizza(size, *toppings):
"""Make a pizza."""
print("\nMaking a " + size + " pizza.")
print("Toppings:")
for topping in toppings:
print("- " + topping)
File: making_pizzas.py
Every function in the module is available in the program file.
import pizza
pizza.make_pizza('medium', 'pepperoni')
pizza.make_pizza('small', 'bacon', 'pineapple')
Only the imported functions are available in the program file.
from pizza import make_pizza
make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')
import pizza as p
p.make_pizza('medium', 'pepperoni')
p.make_pizza('small', 'bacon', 'pineapple')
from pizza import make_pizza as mp
mp('medium', 'pepperoni')
mp('small', 'bacon', 'pineapple')
Don't do this, but recognize it when you see it in others' code. It
can result in naming conflicts, which can cause errors.
from pizza import *
make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')
As you can see there are many ways to write and call a
function. When you're starting out, aim for something that
simply works. As you gain experience you'll develop an
understanding of the more subtle advantages of different
structures such as positional and keyword arguments, and
the various approaches to importing functions. For now if
your functions do what you need them to, you're doing well.
my_car = Car('audi', 'a4', 2016)
print(my_car.make)
print(my_car.model)
print(my_car.year)
my_car.fill_tank()
my_car.drive()
my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)
Consider how we might model a car. What information
would we associate with a car, and what behavior would it
have? The information is stored in variables called
attributes, and the behavior is represented by functions.
Functions that are part of a class are called methods.
class Car():
"""A simple attempt to model a car."""
def init(self, make, model, year):
"""Initialize car attributes."""
self.make = make
self.model = model
self.year = year
self.fuel_capacity = 15
self.fuel_level = 0
def fill_tank(self):
"""Fill gas tank to capacity."""
self.fuel_level = self.fuel_capacity
print("Fuel tank is full.")
def drive(self):
"""Simulate driving."""
print("The car is moving.")
You can modify an attribute's value directly, or you can
write methods that manage updating values more carefully.
my_new_car = Car('audi', 'a4', 2016)
my_new_car.fuel_level = 5
def update_fuel_level(self, new_level):
"""Update the fuel level."""
if new_level <= self.fuel_capacity:
self.fuel_level = new_level
else:
print("The tank can't hold that much!")
def add_fuel(self, amount):
"""Add fuel to the tank."""
if (self.fuel_level + amount
<= self.fuel_capacity):
self.fuel_level += amount
print("Added fuel.")
else:
print("The tank won't hold that much.")
If the class you're writing is a specialized version of another
class, you can use inheritance. When one class inherits
from another, it automatically takes on all the attributes and
methods of the parent class. The child class is free to
introduce new attributes and methods, and override
attributes and methods of the parent class.
To inherit from another class include the name of the
parent class in parentheses when defining the new class.
class ElectricCar(Car):
"""A simple model of an electric car."""
def init(self, make, model, year):
"""Initialize an electric car."""
super().init(make, model, year)
self.battery_size = 70
self.charge_level = 0
class ElectricCar(Car):
--snip--
def charge(self):
"""Fully charge the vehicle."""
self.charge_level = 100
print("The vehicle is fully charged.")
my_ecar = ElectricCar('tesla', 'model s', 2016)
my_ecar.charge()
my_ecar.drive()
In Python class names are written in CamelCase and object
names are written in lowercase with underscores. Modules
that contain classes should still be named in lowercase with
underscores.
There are many ways to model real world objects and
situations in code, and sometimes that variety can feel
overwhelming. Pick an approach and try it – if your first
attempt doesn't work, try a different approach.