Reading notes of Python Programming: from introduction to practice

Chapter 2 variables and simple data types

1. variables

  1. Naming and use:
    1. Variable name: letters, numbers, underscores. Begin with letters or underscores.
    2. Cannot contain spaces.
    3. Cannot be a keyword
    4. Try to use lowercase for variable names
message = "Hello Python!"

2. string

  1. A string is enclosed in quotation marks, either single or double.
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
  1. Case method
    1. title(): initial capitalization
    2. upper(): all uppercase
    3. lower(): all lowercase
name = "ada lovelace"
  1. Merge string: +
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
  1. Add blank
    1. Tabs: \t
    2. Line breaks: \n
    3. Also includes: \n\t
  1. Delete blank
    1. rstrip(): remove trailing blanks
    2. lstrip(): delete the blank of the header
    3. strip(): remove the blank space on both sides

3. figures

  1. Integer: +, -, */
    1. Python2 and Python3 have different division methods
  2. Floating point number: +*
  3. str(): represents a non string as a string

4. notes

  1. Writing:#

Chapter 3 list

1. list definition

  1. Square brackets [] denote a list
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
  1. Access list elements
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
  1. Index starting from 0 is not 1
  2. Access the last list element: a negative number- 1 returns the last but one.

2. modify, add and delete elements

  1. Modify element
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
  1. Add element
    1. Add to end: append('element ')
    2. Intermediate insert: insert (position, 'element')
  2. Delete element
    1. del: delete an element at a location
    2. pop(): delete the last element
    3. Pop (location): delete an element at a location
    4. remove('value '): delete an element based on the value
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
popped_motorcycle = motorcycles.pop()
first_owned = motorcycles.pop(0)

3. organization list

  1. sort(): sort the list (permanent)
  2. sorted(): sort the list (temporary)
  3. reverse(): print the list upside down
  4. len(): learn the length of the list
cars = ['bmw', 'audi', 'toyota', 'subaru']

4. operation list

  1. ergodic
    1. for loop (indent)
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
  1. Create a list of values
    1. range(): generate a series of numbers (left closed and right open)
      1. You can set the step range (left, right, step)
    2. list(): generate a list
for value in range(1,5):

numbers = list(range(1,6))

squares = []
for value in range(1,11):
	square = value**2		# square
  1. List statistics

    1. min()
    2. max()
    3. sum()
  2. List parsing: merge the for loop and the code for creating new elements into one line, and automatically attach new elements

squares = [value**2 for value in range(1,11)]

Output results
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

5. use part of the list

  1. section
    1. Specify left and right indexes (left closed and right open)
    2. First index not specified (starting from list header)
    3. No second index specified (starting at the end of the list)
    4. Negative: all elements output to the end
players = ['charles', 'martina', 'michael', 'florence', 'eli']

Output results
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
  1. Slice traversal
  2. Copy list: create a slice containing the entire list, omitting two indexes.
    • Cannot assign directly. Consider java and C++ references.
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]

6. Yuanzu

  1. Definition:
    1. Lists are suitable for storing data sets that may change. The list type can be modified. The immutable list is called Yuanzu.
    2. Use parentheses to identify, and use indexes to access elements.
dimensions = (200, 50)
  1. Traversal: for loop (same as list)
  2. Modify ancestor variable: assign a value to the variable storing the ancestor.

Chapter 5 if statement

1. condition test

  1. Equal:==
  2. Unequal:=
  3. Compare numbers: >, =, <, > =<=
  4. Multiple conditions: and, or, in, not in
age_0 >= 21 and age_1 >= 21
age_0 >= 21 or age_1 >= 21
'mushrooms' in requested_toppings
'mushrooms' not in requested_toppings

2. if statement

  1. if
  2. if-else
  3. if-elif-else

3. if processing list

  1. Check an element
  2. Confirm that the list is not empty
requested_toppings = []
if requested_toppings:
	for requested_topping in requested_toppings:
		print("Adding " + requested_topping + ".")
	print("\nFinished making your pizza!")
	print("Are you sure you want a plain pizza?")
  1. Use multiple lists

Chapter 6 dictionary

1. definitions

  1. Dictionary: key value pairs
alien_0 = {'color': 'green', 'points': 5}   # Create a new dictionary
print(alien_0['color'])	# Accessing dictionary values
alien_0['x_position'] = 0   # Add a key value pair
alien_0 = {} # Create an empty dictionary
alien_0['color'] = 'yellow' #Modify a key value pair
del alien_0['points'] # Delete key value pair

2. dictionary traversal

  1. Traverse all key value pairs: items()
user_0 = {
	'username': 'efermi',
	'first': 'enrico',
	'last': 'fermi',
for key, value in user_0.items():
	print("\nKey: " + key)
	print("Value: " + value)
  1. Traverse all keys: keys()
for name in favorite_languages.keys():
  1. Traverse all values: values()
    1. If there are duplicate elements, use set() to remove duplicates
for language in favorite_languages.values():
for language in set(favorite_languages.values()):

3. nesting

  1. Nesting dictionaries in lists
aliens = []
for alien_number in range (0,30):
	new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
  1. Store list in dictionary
pizza = {
	'crust': 'thick',
	'toppings': ['mushrooms', 'extra cheese'],
  1. Store dictionary in dictionary
users = {
	'aeinstein': {
		'first': 'albert',
		'last': 'einstein',
		'location': 'princeton',
	'mcurie': {
		'first': 'marie',
		'last': 'curie',
		'location': 'paris',

Chapter 7 user input and while loop

1. user input

  1. input(): pause the program and wait for user input. Parameters are input prompts.
message = input("Tell me something, and I will repeat it back to you: ")
  1. Use int() to get numeric input
age = input("How old are you? ")
How old are you? 21
age = int(age)
  1. Touch operator:%

2. while loop

  1. Common use
current_number = 1
while current_number <= 5:
	current_number += 1
  1. User selects when to exit
message = ""
while message != 'quit':
	message = input(prompt)
	if message != 'quit':
  1. Use flag
active = True
while active:
	message = input(prompt)
	if message == 'quit':
		active = False
  1. Use break to exit the loop
while True:
	city = input(prompt)
	if city == 'quit':
		print("I'd love to go to " + city.title() + "!")
  1. Use continue to exit this cycle
current_number = 0
while current_number < 10:
	current_number += 1
	if current_number % 2 == 0:

3. use the while loop to process lists and dictionaries

  1. Move elements between lists
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
	current_user = unconfirmed_users.pop()
	print("Verifying user: " + current_user.title())
  1. Delete all list elements that contain a specific value
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
  1. Populate dictionary with user input
responses = {}
polling_active = True
while polling_active:
	name = input("\nWhat is 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

Chapter 8 functions

1. function definition

  1. Use def to define a function: function name, function body, and document string (to describe the function)
    1. Passing information to a function: add parameters in parentheses.
def greet_user(username):
"""Show simple greetings"""
	print("Hello, " + username.title() + "!")


2. pass arguments

  1. Associate formal parameters by position
  2. Associate formal parameters by keyword
  3. Default value: when using the default value, the formal parameters without the default value must be listed first in the formal parameter list, and then the arguments with the default value must be listed.
  4. Mixed call
def describe_pet(animal_type, pet_name):
	"""Display pet information"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')

def describe_pet(animal_type, pet_name):
	"""Display pet information"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='harry', animal_type='hamster')

def describe_pet(pet_name, animal_type='dog'):
"""Display pet information"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='harry', animal_type='hamster')
  1. Make the argument optional: give the optional argument a default value, an empty string, and move it to the end of the parameter list.
def get_formatted_name(first_name, last_name, middle_name=''):
"""Return neat names"""
	if middle_name:
		full_name = first_name + ' ' + middle_name + ' ' + last_name
		full_name = first_name + ' ' + last_name
	return full_name.title()
  1. Transmittal list
    1. After the list is passed to the function, the modification of the list by the function is permanent
    2. Prevent functions from modifying lists: passing copies of lists
def greet_users(names):
	"""Send a simple greeting to each user in the list"""
	for name in names:
		msg = "Hello, " + name.title() + "!"

usernames = ['hannah', 'ty', 'margot']

function_name(list_name[:]) # Slice notation [:] creates a copy of the list.
  1. Pass any number of arguments
    1. Use position arguments with any number of arguments
    2. Use any number of keyword arguments
def make_pizza(*toppings):
	"""Print all ingredients ordered by the customer"""
make_pizza('mushrooms', 'green peppers', 'extra cheese')

def make_pizza(size, *toppings):
	"""Overview of pizza to be made"""
	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')

def build_profile(first, last, **user_info):
	"""Create a dictionary that contains everything we know about users"""
	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')

3. return value

  1. return
  2. Return to dictionary

4. store functions in modules

  1. Import the entire module:
    1. Module: extension is py file
    2. Using functions in modules
  2. Import specific functions
  3. Using as to assign aliases to functions
  4. Using as to assign an alias to a module
  5. Import all functions in the module: Using*
import pizza
pizza.make_pizza(16, 'pepperoni')

from module_name import function_name

from pizza import make_pizza as mp

import pizza as p

from pizza import *

Chapter 9 class

1. create and use classes

  1. Create class:
    1. Method__ init__ (): called automatically whenever a new instance is created.
      1. Formal parameter self: a reference to the instance itself, allowing the instance to access methods and properties in the class. Self is passed automatically. Just pass the other parameters.
    2. Other methods.
class Dog():
	"""A simple attempt to simulate a puppy"""
	def __init__(self, name, age):
		"""Initialize properties name and age""" = name
		self.age = age
	def sit(self):
		"""Simulate a dog crouching when commanded"""
		print( + " is now sitting.")
  1. Create instances from classes
    1. Access properties: using period access
    2. Call method: call with period
    3. Create multiple instances
my_dog = Dog('willie', 6)
print("My dog's name is " + + ".")

2. use classes and instances

  1. Assign default values to attributes: in__ init()__ Method.
class Car():
	def __init__(self, make, model, year):
		"""Initialize attributes describing the car"""
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0

	def read_odometer(self):
		"""Print a message indicating car mileage"""
		print("This car has " + str(self.odometer_reading) + " miles on it.")
  1. Modify the value of an attribute
    1. Directly modify the value of the attribute
    2. Modifying the value of an attribute through a method
my_new_car.odometer_reading = 23

class Car():
	def update_odometer(self, mileage):
		"""Set the odometer reading to the specified value"""
		self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2016)

3. succession

  1. Inherit all properties and methods of the parent class
class ElectricCar(Car):
	"""The uniqueness of electric vehicles"""
	def __init__(self, make, model, year):
		"""Initialize properties of parent class"""
		super().__init__(make, model, year)
  1. Define properties and methods for subclasses
class ElectricCar(Car):
	"""Represent aspects of a car, specific to electric vehicles."""
	def __init__(self, make, model, year):
		The uniqueness of electric vehicles
		Initialize the attributes of the parent class, and then initialize the attributes specific to electric vehicles
		super().__init__(make, model, year)
		self.battery_size = 70
  1. Override method of parent class
  2. Use instance as attribute: create a new class and use the instance of the new class as an attribute of a previous class.
class Car():

class Battery():
	"""A simple attempt to simulate electric vehicle battery"""
	def __init__(self, battery_size=70):
		"""Initialize battery properties"""
		self.battery_size = battery_size
	def describe_battery(self):
		"""Print a message describing the battery capacity"""
		print("This car has a " + str(self.battery_size) + "-kWh battery.")

class ElectricCar(Car):
	"""The uniqueness of electric vehicles"""
	def __init__(self, make, model, year):
		Initialize the attributes of the parent class, and then initialize the electric vehicle specific attributes
		super().__init__(make, model, year)
		self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)

4. import class

  1. Import a single class
    1. Only a single class per module
    2. Each module stores multiple classes
from car import Car
from car import ElectricCar
  1. Import multiple classes
    1. Importing multiple classes from a module
    2. Import the entire module, and then use the period notation to access the required classes.
    3. Import all classes in the module
from car import Car, ElectricCar
import car
from module_name import *
  1. Importing one module into another

5. class coding style

  1. Class name: hump nomenclature
  2. Instance name / module name: lowercase, underlined between words

Chapter 10 documents and exceptions

1. read data from file

  1. Read entire file:
    1. with: close the file after you no longer need to access it
    2. open(): open the file
    3. read(): read the contents of the file. An empty string is returned when the end of the file is reached. Displayed as a blank line.
      • Use rstrip() in the print statement to delete empty rows.
with open('pi_digits.txt') as file_object:
	contents =
  1. File path
    1. Relative path:
      1. Linux: /
      2. Windows: \
    2. Absolute path
with open('text_files/filename.txt') as file_object:
with open('text_files\filename.txt') as file_object:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
  1. Read line by line: for loop
    • A blank line appears. Because there is an invisible line break at the end of each line in the file, a line break will be added to the print statement. There are two line breaks at the end of each line.
    • Eliminate blank lines: use rstrip() in print statements.
filename = 'pi_digits.txt'
with open(filename) as file_object:
	for line in file_object:
  1. Read file and store in list
    1. readlines(): read each line from the file and store it in the list.
filename = 'pi_digits.txt'
with open(filename) as file_object:
	lines = file_object.readlines()
for line in lines:

2. write file

  1. Write empty file:
    1. open():
      1. Parameter 1: name of the open file. If the file does not exist, it will be created automatically. If it already exists, the file will be emptied.
      2. Parameter 2: mode of opening the file.
        1. 'w': write mode
        2. 'r': read mode
        3. 'a': additional mode
        4. 'r+': mode of reading and writing files
        5. Omitting: read only mode
filename = 'programming.txt'
with open(filename, 'w') as file_object:
	file_object.write("I love programming.")
  1. Write multiple lines: add newline at the end

3. abnormal

  • Use 'try except' to handle exceptions
  1. ZeroDivisionError
except ZeroDivisionError:
	print("You can't divide by zero!")
print("Enter 'q' to quit.")
while True:
	first_number = input("\nFirst number: ")
	if first_number == 'q':
	second_number = input("Second number: ")
		answer = int(first_number) / int(second_number)
	except ZeroDivisionError:
		print("You can't divide by 0!")
  1. FileNotFoundError
filename = 'alice.txt'
	with open(filename) as f_obj:
		contents =
except FileNotFoundError:
	msg = "Sorry, the file " + filename + " does not exist."
  1. Parsing text: split() method
filename = 'alice.txt'
	with open(filename) as f_obj:
		contents =
except FileNotFoundError:
	msg = "Sorry, the file " + filename + " does not exist."
	# Calculate the approximate number of words in the file
	words = contents.split()
	num_words = len(words)
	print("The file " + filename + " has about " + str(num_words) + " words.")
  1. Skip on failure: pass
def count_words(filename):
	"""Calculate the approximate number of words in a file"""
	except FileNotFoundError:

4. store data

  1. Json Dump(): stores an array. Arguments: stored data and file objects that store data
  2. json Load(): read json
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
	json.dump(numbers, f_obj)
	numbers = json.load(f_obj)

Chapter 11 test code

1. test function

  1. Unit tests and test cases
    1. Unit test: verify that there is no problem with one aspect of the function
    2. Test case: a set of unit tests to test various situations.
  2. Test process:
    1. Import module unittest and test function
    2. Create a unittest Testcase class. This class must inherit unittest Testcase
    3. Assertion method: assertEquals(): parameters are two comparisons.
    4. Unittest Main(): run the test.
      1. Period: Pass
      2. E: An error occurred in one of the unit tests.
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
		"""Be able to process images correctly Janis Joplin Such a name?"""
		formatted_name = get_formatted_name('janis', 'joplin')
		self.assertEqual(formatted_name, 'Janis Joplin')

2. testing

  1. assert methods
    1. assertEqual(a, b): a == b
    2. assertNotEqual(a, b): a != b
    3. assertTrue(x):a is True
    4. assertFalse(x):x is False
    5. assertIn(item, list):item in the list
    6. assertNotIn(item, list):item is not in the list
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
	"""test """
	def test_first_last_name(self):
		"""Be able to process images correctly Janis Joplin Such a name?"""
		formatted_name = get_formatted_name('janis', 'joplin')
		self.assertEqual(formatted_name, 'Janis Joplin')
	def test_first_last_middle_name(self):
		"""Be able to process images correctly Wolfgang Amadeus Mozart Such a name?"""
		formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
		self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
  1. Tested classes
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
	"""aim at AnonymousSurvey Class testing"""
	def test_store_single_response(self):
		"""Test individual answers are stored appropriately"""
	def test_store_three_responses(self):
		"""The three answers to the test will be stored properly"""
		question = "What language did you first learn to speak?"
		my_survey = AnonymousSurvey(question)
		responses = ['English', 'Spanish', 'Mandarin']
		for response in responses:
		for response in responses:
			self.assertIn(response, my_survey.responses)
  1. Method setUp(): create test objects only once and use them in each test method. If the TestCase class contains the method setUp(): Python runs it first, and then runs each to test_ The method of leading. In this way, each test method can use the object created by setUp().
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
	"""aim at AnonymousSurvey Class testing"""
	def setUp(self):
		Create a survey object and a set of answers for the test method used
		question = "What language did you first learn to speak?"
		self.my_survey = AnonymousSurvey(question)
		self.responses = ['English', 'Spanish', 'Mandarin']
	def test_store_single_response(self):
		"""Test individual answers are stored appropriately"""
		self.assertIn(self.responses[0], self.my_survey.responses)
	def test_store_three_responses(self):
		"""The three answers to the test will be stored properly"""
		for response in self.responses:
		for response in self.responses:
			self.assertIn(response, self.my_survey.responses)

Tags: Python Machine Learning

Posted by ferdi on Mon, 30 May 2022 10:05:35 +0530