Chapter 1 Setup
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren’t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one– and preferably only one –obvious way to do it. Although that way may not be obvious at first unless you’re Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea – let’s do more of those!
Chapter 2 Data Types
001 variables
msg = "hello"
print(msg)
hello
002 string operations
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
Ada Lovelace ADA LOVELACE ada lovelace
new_msg = msg + " " + name
print ('\t' + new_msg + '\n')
hello ada lovelace
msg_1 = ' hiuf yeb w hviu ywe r '
print(msg_1.rstrip())
hiuf yeb w hviu ywe r
msg_1 = msg_1.rstrip()
print(msg_1.lstrip())
hiuf yeb w hviu ywe r
msg_1 = '\t' + msg_1 + '\n'
print(msg_1)
msg_1 = msg_1.rstrip()
print(msg_1)
msg_1 = msg_1.lstrip()
print(msg_1)
hiuf yeb w hviu ywe r
hiuf yeb w hviu ywe r
hiuf yeb w hviu ywe r
003 number operations
10**6
1000000
3/2
1.5
3//2
1
0.1*3
0.30000000000000004
floats’ problems still exists in python3, but it’s common in any language due to how computers save these floats
004 number&string
num_test_1 = 666
print(num_test_1)
# print('huvife' + num_test_1 + 'gbtehgbe')
# error version
print('huvife' + str(num_test_1) + 'gbtehgbe')
# or
num_test_1 = '666'
print('huvife' + num_test_1 + 'gbtehgbe')
666
huvife666gbtehgbe
huvife666gbtehgbe
Chapter 3 List
There is no array in Python!!!
001 Introduction to Lists
arr = ['vfervewr','gftewgwter','gtewgewwe','gtwgw']
print(arr)
print(arr[0].title())
print(arr[-1]) #see? minus is not only available, but useful!
print(arr[-3])
message = "vfsvegeerwsgetrw " + arr[0] + " vbgfdbgfrdsbg"
print(message)
# message = "vfsvegeerwsgetrw " + arr + " vbgfdbgfrdsbg"
# print(message)
# error version
['vfervewr', 'gftewgwter', 'gtewgewwe', 'gtwgw']
Vfervewr
gtwgw
gftewgwter
vfsvegeerwsgetrw vfervewr vbgfdbgfrdsbg
Again, thers is no array in Python! So don’t follow my mistake! (I used ‘arr’ to name a list, because I thought they were the same!)
002 Modifying Lists
arr[0] = 'cool'
print(arr)
['cool', 'gftewgwter', 'gtewgewwe', 'gtwgw', 'new one', 666]
003 Add Elements
arr.append('new one')
print(arr)
['cool', 'gftewgwter', 'gtewgewwe', 'gtwgw', 'new one', 666, 'new one']
You can even create an empty list and add elements to it later!
motor = []
motor.append('honda')
motor.append('yamaha')
motor.append('suzuki')
print(motor)
['honda', 'yamaha', 'suzuki']
004 Insert Elements
motor.insert(0,'ducati')
print(motor)
['ducati', 'honda', 'yamaha', 'suzuki']
005 Delete Elements
print(motor)
del motor[1]
print(motor)
['ducati', 'honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
006 Pop Elements
print(motor)
poped_motor = motor.pop()
print(motor)
print(poped_motor)
['ducati', 'yamaha', 'suzuki']
['ducati', 'yamaha']
suzuki
This way, you can still use the element you want to delete for the last time.
This is useful! Watch this example!
motor = ['ducati', 'honda', 'yamaha', 'suzuki']
last_owned = motor.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")
print(motor)
The last motorcycle I owned was a Suzuki.
['ducati', 'honda', 'yamaha']
And pop can be used to pop any element!
motor = ['ducati', 'honda', 'yamaha', 'suzuki']
first_owned = motor.pop(0)
print("The first motorcycle I owned was a " + first_owned.title() + ".")
print(motor)
The first motorcycle I owned was a Ducati.
['honda', 'yamaha', 'suzuki']
007 Remove Elements According to Its Value
motor = ['ducati', 'honda', 'yamaha', 'suzuki']
motor.remove('ducati')
print(motor)
['honda', 'yamaha', 'suzuki']
motor = ['ducati', 'honda', 'yamaha', 'suzuki']
too_expensive = 'ducati'
motor.remove(too_expensive)
print(motor)
print("\nA " + too_expensive.title() + " is too expensive for me.")
['honda', 'yamaha', 'suzuki']
A Ducati is too expensive for me.
008 Arrange Lists
To Sort Permanently
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse = True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']
To Sort Temporarily
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
print(sorted(cars))
print(cars)
['bmw', 'audi', 'toyota', 'subaru']
['audi', 'bmw', 'subaru', 'toyota']
['bmw', 'audi', 'toyota', 'subaru']
To Reverse
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse() #don't forget the "()"!
print(cars)
cars.reverse()
print(cars)
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
['bmw', 'audi', 'toyota', 'subaru']
To Confirm the Length
cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
4
Chapter 4 Operate the List
001 For: Loop
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you, all!")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
Thank you, all!
As you can see, indent is very important in Python. It can decide whether your program will be running properly.
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
File "<ipython-input-32-f0b382b2b777>", line 3
print(magician.title() + ", that was a great trick!")
^
IndentationError: expected an indented block
See? An error occured when you don’t indent the code!
msg = "hello"
print(msg)
Errors also occur when there’s an unnecessary indent!
002 Use A Number As the Loop Control Variable
for value in range(1,6):
print(value)
range()
stops when value
reaches 6, which means after 5 is printed and value
has been 6, the program will stop.
And range()
has other ways to use.
numbers = list(range(1,6))
print(numbers)
odd_numbers = list(range(1,11,2))
print(odd_numbers)
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
digits = list(range(0,10))
min(digits)
max(digits)
sum(digits)
squares = [value**2 for value in range(1,11)]
print(squares)
players = ['charles', 'martina', 'micheal', 'florence', 'eli']
print(players[0:3])
players = ['charles', 'martina', 'micheal', 'florence', 'eli']
print(players[1:4])
players = ['charles', 'martina', 'micheal', 'florence', 'eli']
print(players[:4])
players = ['charles', 'martina', 'micheal', 'florence', 'eli']
print(players[2:])
players = ['charles', 'martina', 'micheal', 'florence', 'eli']
print(players[-3:])
players = ['charles', 'martina', 'micheal', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
print("My favorite foods are:")
print(my_foods)
print("\nMyfriend's favorite foods are:")
print(friend_foods)
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMyfriend's favorite foods are:")
print(friend_foods)
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMyfriend's favorite foods are:")
print(friend_foods)
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
# Not Workable
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMyfriend's favorite foods are:")
print(friend_foods)
Mind the tiny difference between the two codes. Though they look similar, the results are totally different!
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
Edting the elements in a tuple is illegal!
dimensions = (200, 50)
dimensions[0] = 250
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
200
50
However, assigning the whole tuple is allowed!
dimensions = (200, 50)
print("origin:")
print(dimensions)
dimensions = (400, 100)
print("modified:")
print(dimensions)
origin:
(200, 50)
modified:
(400, 100)
005 PEP 8
Check Here for more details. https://www.python.org/dev/peps/pep-0008/
Chapter 5 If Statement
001 Simple Example
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
Audi
BMW
Subaru
Toyota
002 Condition Testing
car = 'bmw'
car == 'bmw'
True
car = 'bmw'
car == 'audi'
False
car = 'Audi'
car == 'audi'
False
car = 'Audi'
car.lower() == 'audi'
True
car = 'Audi'
car.lower() == 'audi'
car
'Audi'
car = 'Audi'
car.lower() == 'auDi'.lower()
True
!=
is availiable, too!
str1 = 'hello'
str2 = 'hel'
str1 != str2
True
Numbers are workable, too!
age = 18
age == 18
True
age >= 18
True
age > 17
True
age > 16 and age < 19
True
(age > 16) and (age < 19)
True
(age < 16) or (age != 17)
True
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
True
'apple' in requested_toppings
False
bool1 = True
bool2 = False
bool1 and bool2
False
003 If Statement
age = 12
if age < 4:
print(1)
elif age < 18:
print(2)
elif age > 65:
print(3)
else:
print(4)
2
age = 1
if age < 4:
print(1)
elif age < 18:
print(2)
elif age > 65:
print(3)
1
004 Combination
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we ran out of " + requested_topping + ".")
else:
print("Adding " + requested_topping + ".")
print("Finished!")
Adding mushrooms.
Sorry, we ran out of green peppers.
Adding extra cheese.
Finished!
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we ran out of " + requested_topping + ".")
else:
print("Adding " + requested_topping + ".")
else:
print("You want a plain pizza?")
You want a plain pizza?
available_toppings = ['mushrooms', 'extra cheese']
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
if requested_toppings:
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we ran out of " + requested_topping + ".")
else:
print("You want a plain pizza?")
print("\nFinished!")
Adding mushrooms.
Sorry, we ran out of green peppers.
Adding extra cheese.
Finished!
Chapter 6 Dictionary
001 A Simple Example
alien_0 = {'color' : 'green', 'points' : 5}
print(alien_0['color'])
print(alien_0['points'])
green
5
A dictionary is a series of “key = value”. In this case, ‘color’ and ‘points’ are two keys, and ‘green’ and 5 are two values.
alien_0 = {'color' : 'green', 'points' : 5}
color_0 = alien_0['color']
print('The color is ' + color_0 + '.')
The color is green.
alien_0 = {'color' : 'green', 'points' : 5}
print('The color is ' + alien_0['color'] + '.')
The color is green.
alien_0 = {'color' : 'green', 'points' : 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
You can create an empty dictionary for convenience, just like you have done for lists.
alien_0 = {}
print(alien_0)
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
{}
{'color': 'green', 'points': 5}
002 Modification and Deletion
alien_0 = {'color' : 'green', 'points' : 5}
print(alien_0)
alien_0['color'] = 'yellow'
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 5}
alien_0 = {'color' : 'green', 'points' : 5}
print(alien_0)
del alien_0['points']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}
Code Standards For Long Statements
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
'.')
Sarah's favorite language is C.
003 Traverse A Dictionary
user_0 = {
'username' : 'efermi',
'first' : 'enrico',
'last' : 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favortie language is " +
language.title() + ".")
Jen's favortie language is Python.
Sarah's favortie language is C.
Edward's favortie language is Ruby.
Phil's favortie language is Python.
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
for name in favorite_languages.keys():
print(name.title())
Jen
Sarah
Edward
Phil
In fact, .keys()
can be omitted.
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
for name in favorite_languages: #mind here!
print(name.title())
Jen
Sarah
Edward
Phil
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi! " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
Jen
Sarah
Hi! Sarah, I see your favorite language is C!
Edward
Phil
Hi! Phil, I see your favorite language is Python!
This is how .keys()
actually works.
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
favorite_languages.keys()
dict_keys(['jen', 'sarah', 'edward', 'phil'])
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
Erin, please take our poll!
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title())
Edward
Jen
Phil
Sarah
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
favorite_languages.values()
dict_values(['python', 'C', 'ruby', 'python'])
favorite_languages = {
'jen' : 'python',
'sarah' : 'C',
'edward' : 'ruby',
'phil' : 'python',
}
set(favorite_languages.values())
{'C', 'python', 'ruby'}
This will remove the repeated values!
004 Nest
Dictionaries in A List
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'res'
alien['speed'] = 'fast'
alien['points'] = 15
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30
Lists in A Dictionary
favorite_languages = {
'jen' : ['python', 'ruby'],
'sarah' : ['C'],
'edward' : ['ruby', 'go'],
'phil' : ['python', 'haskell'],
}
for name, language in favorite_languages.items():
if len(language) == 1:
print("\n" + name.title() + "'s favorite language is " + language[0].title())
else:
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
Jen's favorite languages are:
Python
Haskell
Sarah's favorite language is C
Edward's favorite languages are:
Python
Haskell
Phil's favorite languages are:
Python
Haskell
users = {
'aeinsein' : {
'first' : 'albert',
'last' : 'einstein',
'location' : 'princeton',
},
'mcurie':{
'first' : 'marie',
'last' : 'curie',
'location' : 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name:" + full_name.title())
print("\tLocation: " + location.title())
Username: aeinsein
Full name:Albert Einstein
Location: Princeton
Username: mcurie
Full name:Marie Curie
Location: Paris
Chapter 7 Input and While Loop
001 input()
? Try int()
msg = input("Tell me sth:")
print(msg)
Tell me sth:test
test
msg0 = "hello "
msg0 += "\ninput sth: "
msg1 = input(msg0)
print(msg1)
hello
input sth: test1
test1
But, how to input a number?
age = input("your age")
age
your age18
'18'
age = input("your age")
age >= 18
your age18
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-74683d3f63a8> in <module>
1 age = input("your age")
----> 2 age >= 18
TypeError: '>=' not supported between instances of 'str' and 'int'
age1 = input(age1)
age1
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-b4864473f466> in <module>
----> 1 age1 = input(age1)
2 age1
NameError: name 'age1' is not defined
Above is just a silly test out of my curiosity.
age = input("your age")
age = int(age)
age >= 18
your age18
True
Mod %
4 % 3
1
num = input()
num = int(num)
if num % 2 == 0:
print("\nThe number " + num + " is even.")
else:
print("\nThe number " + num + " is odd.")
100
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-2b870bf3f31d> in <module>
3
4 if num % 2 == 0:
----> 5 print("\nThe number " + num + " is even.")
6 else:
7 print("\nThe number " + num + " is odd.")
TypeError: must be str, not int
num = input()
num = int(num)
if num % 2 == 0:
print("\nThe number " + str(num) + " is even.")
else:
print("\nThe number " + str(num) + " is odd.")
100
The number 100 is even.
Bear in mind that str()
is necessary when inserting a number into a string.
002 While
cnt = 1
while cnt <= 5:
print(cnt)
cnt += 1
1
2
3
4
5
cnt++
is illegal in Python!
msg = ""
while msg != "quit":
msg = input(msg)
if msg != "quit":
print(msg + "\n")
666
666
666quit
active = True
while active:
msg = input()
if msg == "quit":
active = False
else:
print(msg)
666
666
quit
while True:
msg = input()
if msg == "quit":
break
else:
print(msg)
666
666
quit
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)
1
3
5
7
9
i = 1
while i < 10:
print(i)
Above is a endless loop!
003 While & List & Dictionary
unconfirmed_users = ['alice', 'brain', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
Verifying user: Candace
Verifying user: Brain
Verifying user: Alice
The following users have been confirmed:
Candace
Brain
Alice
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat's your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/no)")
if repeat == 'no':
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + '.')
What's your name? 1
Which mountain would you like to climb someday? 1
Would you like to let another person respond? (yes/no)No
What's your name? 2
Which mountain would you like to climb someday? 2
Would you like to let another person respond? (yes/no)no
--- Poll Results ---
1 would like to climb 1.
2 would like to climb 2.
Chapter 8 Function
001 Define a function
def greet_user():
print("Hello!")
greet_user()
Hello!
def greet_user(username):
print("Hello, " + username.title() + "!")
greet_user("charlie")
Hello, Charlie!
Mind the formal parameter and the actual parameter
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is" + pet_name.title() + ".")
describe_pet("hamster", 'harry')
I have a hamster.
My hamster's name isHarry.
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is" + pet_name.title() + ".")
describe_pet("hamster", 'harry')
describe_pet("dog", 'willie')
I have a hamster.
My hamster's name isHarry.
I have a dog.
My dog's name isWillie.
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is" + pet_name.title() + ".")
describe_pet("hamster", 'harry')
describe_pet('harry', "hamster")
describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet(pet_name = 'harry', animal_type = 'hamster')
I have a hamster.
My hamster's name isHarry.
I have a harry.
My harry's name isHamster.
I have a hamster.
My hamster's name isHarry.
I have a hamster.
My hamster's name isHarry.
Mind the last two calling of the function describe_pet
!
002 Functions with default values
def describe_pet(pet_name, animal_type = 'dog'):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is" + pet_name.title() + ".")
describe_pet('harry', "hamster")
describe_pet('willie')
I have a hamster.
My hamster's name isHarry.
I have a dog.
My dog's name isWillie.
def describe_pet(animal_type = 'dog', pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is" + pet_name.title() + ".")
describe_pet("hamster", 'harry')
describe_pet('willie')
File "<ipython-input-22-783719293d54>", line 1
def describe_pet(animal_type = 'dog', pet_name):
^
SyntaxError: non-default argument follows default argument
This time, an error occured!
def describe_pet(animal_type = 'dog', pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is" + pet_name.title() + ".")
describe_pet("hamster", 'harry')
describe_pet(pet_name = 'willie')
File "<ipython-input-23-697809b5a3b4>", line 1
def describe_pet(animal_type = 'dog', pet_name):
^
SyntaxError: non-default argument follows default argument
Another error!
In Python, you have to put the non-default arguments before the default ones!!!
003 Return Value
def get_full_name(first_name, second_name):
full_name = first_name + ' ' + second_name
return full_name.title()
musician = get_full_name('jimi', 'hendrix')
print(musician)
Jimi Hendrix
def get_formatted_name(first_name, last_name, middle_name=''): # Pay Attention!
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
Jimi Hendrix
John Lee Hooker
def build_person(first_name, last_name, age=''):
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix')
print(musician)
musician = build_person('jimi', 'hendrix', 27)
print(musician)
{'first': 'jimi', 'last': 'hendrix'}
{'first': 'jimi', 'last': 'hendrix', 'age': 27}
def get_full_name(first_name, second_name):
full_name = first_name + ' ' + second_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(Enter 'q' to quit!)")
f_name = input("First name:")
if f_name == 'q':
break;
l_name = input("Last name:")
if l_name == 'q':
break;
formatted_name = get_full_name(f_name, l_name)
print("\nHello, " + formatted_name + '!')
Please tell me your name:
(Enter 'q' to quit!)
First name:charlie
Last name:jiang
Hello, Charlie Jiang!
Please tell me your name:
(Enter 'q' to quit!)
First name:charlie
Last name:jiang
Hello, Charlie Jiang!
Please tell me your name:
(Enter 'q' to quit!)
First name:c
Last name:q
004 Relay Lists
def greet_users(names):
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
Hello, Hannah!
Hello, Ty!
Hello, Margot!
def print_models(unprinted_designs, completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
Printing: dodecahedron
Printing: robot pendant
Printing: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
[]
def print_models(unprinted_designs, completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs[:], completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
Printing: dodecahedron
Printing: robot pendant
Printing: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
['iphone case', 'robot pendant', 'dodecahedron']
The second version of this programme conveys a copy of a list!
005 Relay as many actual parameters as you like!
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
*
let Python create a tuple that contains the actual parameters you relayed, no matter how many actual parameters you relayed to the function.
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
def build_profile(first, last, **user_info):
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location = 'princeton',
field = 'physics')
print(user_profile)
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
**
let Python create a dictionary that contains the keys and values you relayed, no matter how many pairs you have relayed to the function.
006 Import
Due to the difficulty of using import
in notebook. I’ll practice this part in sublime text 3.
007 PEP8, again!
def function_name(parameter_0, parameter_1='default_value')
function_name(value_0, parameter_1='value_1')
def function_name(
parameter_0, parameter_1, parameter_2,
parameter_3, parameter_4, parameter_5):
function body...
Chapter 9 Class
001 Introduction to Class
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
def roll_over(self):
print(self.name.title() + " rolled over!")
my_dog = Dog('willie', 6)
print("name: " + my_dog.name.title())
print("age: " + str(my_dog.age))
name: Willie
age: 6
my_dog = Dog('willie', 6)
print("name: " + my_dog.name.title())
print("age: " + str(my_dog.age))
name: Willie
age: 6
Mind that __init__
has two _
s at each side!
my_dog.sit()
Willie is now sitting.
my_dog.roll_over()
Willie rolled over!
your_dog = Dog('Lucy', 3)
your_dog.name
'Lucy'
your_dog.age
3
your_dog.sit()
Lucy is now sitting.
002 Use Class and Instances
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.
Here are some ways to change properties.
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
This car has 23 miles on it.
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.update_odometer(23)
my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.
This car has 23 miles on it.
my_new_car.update_odometer(46)
my_new_car.read_odometer()
my_new_car.update_odometer(23)
my_new_car.read_odometer()
This car has 46 miles on it.
You can't roll back an odometer!
This car has 46 miles on it.
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
if miles > 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer!")
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.update_odometer(23)
my_new_car.read_odometer()
my_new_car.increment_odometer(100)
my_new_car.read_odometer()
my_new_car.increment_odometer(-100)
my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.
This car has 23 miles on it.
This car has 123 miles on it.
You can't roll back an odometer!
This car has 123 miles on it.
003 Inheritance
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
if miles > 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer!")
def fill_gas_tank(self):
print("Filled!")
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
2016 Tesla Model S
This car has a 70-kWh battery.
This car doesn't need a gas tank!
Don’t forget self
!!!
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
if miles > 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer!")
def fill_gas_tank(self):
print("Filled!")
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
2016 Tesla Model S
This car has a 70-kWh battery.
This car can go approximately 240 miles on a full charge.
004 Import Class
Similar to import functions.
005 Python Standard Library
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.