Notes on Python Programming: from introduction to practice

Learning notes from "Python Programming: from introduction to practice" (by Eric Matthes of the United States). Mainly for Python 3.

Python uses indentation to determine the relationship between a line of code and the previous line of code. In the previous example, the lines of code that display messages to magicians are part of the for loop because they are indented.

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, everyone. That was a great magic show!") ❶

 

In Python, strings are surrounded by quotation marks. The quotation marks can be single quotation marks or double quotation marks, and the strings can contain quotation marks.

 

For example, to change a string to all uppercase or all lowercase, do the following:

name = "Ada Lovelace"

print(name.upper())

print(name.lower())

 

Use the plus sign (+) to merge strings

first_name = "ada"

last_name = "lovelace"

full_name = first_name + " " + last_name

message = "Hello, " + full_name.title() + "!" ❶

print(message) ❷

 

You can also remove whitespace at the beginning of a string, or at both ends of a string. To do this, use the methods lstrip() and strip(), respectively.

 

In Python, you can add (+) subtract (-) multiply (*) divide (/) an integer.

If you need to explicitly indicate that you want Python to use this integer as a string. To do this, call the function str(), which lets Python express non string values as strings, such as star(age), and change the age value into a string.

Execute the command import this in a Python terminal session and take a cursory look at other guidelines.

 

list

The easiest way to add a new element to a list is to append the element to the end of the list. When you attach elements to a list, the append() method adds them to the end of the list.

Use the method insert() to add new elements anywhere in the list. To do this, you need to specify the index and value of the new element. motorcycles = ['honda', 'yamaha', 'suzuki'] motorcycles.insert(0, 'ducati') ❶ print(motorcycles)

 

The pop() method removes the element at the end of the list and allows you to use it later.

Method remove() only deletes the first specified value.

The sort() method (see ❶) permanently changes the order of the list elements. The sorted() function allows you to display list elements in a specific order, without affecting their original order in the list.

 

To output the list in reverse order, the method reverse() permanently changes the order of the list elements, but it can be restored to the original order at any time, so just call reverse() again for the list.

Use the function len() to quickly learn the length of the list.

 

To print numbers 1 to 5, you need to use range(1,6):

for value in range(1,6):

print(value)

 

The following example uses list resolution to create the list of squares you saw earlier: squares.py

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

print(squares)

 

You can generate any subset of the list. For example, if you want to extract the second to fourth elements of the list, you can specify the starting index as 1 and the ending index as 4:

players = ['charles', 'martina', 'michael', 'florence', 'eli']

print(players[1:4])

This time, the slice starts at 'martina' and ends at 'florence':

['martina', 'michael', 'florence']

 

Copy list

my_foods = ['pizza', 'falafel', 'carrot cake']

friend_foods = my_foods[:] ❶

Tuples look like lists, but are identified with parentheses instead of square brackets. The value of an element cannot be modified, but it can be fully reassigned. definition

dimensions = (200, 50) ❶

 

Each text editor provides a setting that converts the entered tabs to a specified number of spaces. You should use tab keys when writing code, but be sure to set the editor to insert spaces instead of tabs in the document.

 

if judgment

cars = ['audi', 'bmw', 'subaru', 'toyota']



for car in cars:

if car == 'bmw': ❶

print(car.upper())

else:

print(car.title())

 

compare

If case does not matter and you only want to check the value of the variable, you can convert the value of the variable to lowercase, otherwise it will be case sensitive, and then compare:

>>> car = 'Audi'

>>> car.lower() == 'audi'

True

Conditional statements can contain various mathematical comparisons, such as less than, less than or equal to, greater than, greater than or equal to, and can also use and, or to make a combined judgment

>>> age = 19

>>> age < 21

True

>>> age <= 21

True

>>> age > 21

False

>>> age >= 21

False

There are also times when it's important to make sure that a specific value is not included in the list; in this case, use the keyword not in.

 

If you want to execute only one code block, use the if elif else structure; if you want to run multiple code blocks, use a series of independent if statements.

When a list name is used in a conditional expression in an if statement, Python returns True when the list contains at least one element and False when the list is empty.

 

Dictionaries

alien_0 = {'color': 'green', 'points': 5}

print(alien_0)



alien_0['x_position'] = 0 ❶

alien_0['y_position'] = 25 ❷

print(alien_0)

Delete a key value pair in the dictionary

del alien_0['points'] ❶

 

Press enter to enter the subsequent lines of the print statement, and use Tab to align and indent them one level. This shows how a statement can be broken down

print("Sarah's favorite language is " + ❶

favorite_languages['sarah'].title() + ❷

".") ❸

 

Dictionary in real life, we call it glossary.

Ergodic dictionary

for key, value in user_0.items(): ❶

print("\nKey: " + key) ❷

print("Value: " + value) ❸

K and v suggest replacing the actual meaning of the dictionary content with a name, such as

for name, language in favorite_languages.items():

 

When traversing the dictionary, all keys will be traversed by default, so if the for name in favorite_languages.keys(): replace with for name in favorite_languages:, output will not change.

Determine whether a key is in the dictionary:

if 'erin' not in favorite_languages.keys(): ❶

print("Erin, please take our poll!")

Output key in sequence:

for name in sorted(favorite_languages.keys()):

 

Dictionaries can store lists or dictionaries.

 

function

def describe_pet(animal_type, pet_name):

Keyword arguments

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(animal_type='hamster', pet_name='harry')

 

Optional parameter. You can put the actual parameter to the end and specify an empty default value to make it an optional parameter.

def get_formatted_ips(corp_ip,corp_ip2=''): 

 

 

The asterisk in parameter name * toppings causes Python to create an empty tuple named toppings, and encapsulates all the received values into the tuple

def make_pizza(*toppings):

"""Print all ingredients ordered by customers"""

print(toppings)



make_pizza('pepperoni')

make_pizza('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')

print(user_profile)

Function build_ The definition of profile () requires a first and last name, and allows the user to provide any number of name value pairs as needed. Parameter * * user_ Two asterisks in info let Python create a user_ The empty dictionary of info and encapsulates all the name value pairs received in this dictionary. In this function, you can access user as you would any other dictionary_ Name value pair in info.

 

By separating function names with commas, you can import any number of functions from the module as needed:

from module_name import function_0, function_1, function_2

 

Alias import function

from pizza import make_pizza as mp



mp(16, 'pepperoni')

mp(12, 'mushrooms', 'green peppers', 'extra cheese')

 

You can also assign aliases to modules. By giving a module a short alias, such as P for pizza, you can make it easier to call functions in the module. Compared to pizza.make_pizza(),p.make_pizza() is simpler:

import pizza as p



p.make_pizza(16, 'pepperoni')

p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

 

class

Object-oriented programming is one of the most effective software writing methods. In object-oriented programming, you write classes that represent things and situations in the real world and create objects based on those classes. When you write a class, you define the general behavior of a large class of objects. When you create objects based on classes, each object automatically has this general behavior, and then you can give each object a unique personality as needed.

 

Method to modify the value of a property

class Car():

--snip--



def update_odometer(self, mileage):

"""

Set the odometer reading to the specified value

Do not call back the odometer reading

"""

if mileage >= self.odometer_reading: ❶

self.odometer_reading = mileage

else:

print("You can't roll back an odometer!") ❷

Now, update_odometer() checks that the specified reading is reasonable before modifying properties. If the newly specified mileage is greater than or equal to the original mileage( self.odometer_reading) will change the odometer reading to the newly specified mileage (see ❶); otherwise, a warning will be given that the odometer cannot be dialed back (see ❷).

 

Store the Car class in a file named car.py The module will overwrite the previously used file car.py . From now on, programs using this module must use more specific file names, such as my_car.py .

my_car.py

from car import Car ❶



my_new_car = Car('audi', 'a4', 2016)

print(my_new_car.get_descriptive_name())



my_new_car.odometer_reading = 23

my_new_car.read_odometer()

 

 

Import the whole module

 

You can also import the entire module and use the period notation to access the required classes. The import method is simple and the code is easy to read. Because the code that creates the class instance contains the module name, it does not conflict with any of the names used by the current file.

The following code imports the whole car module and creates a normal car and an electric car:

my_cars.py

import car ❶



my_beetle = car.Car('volkswagen', 'beetle', 2016) ❷

print(my_beetle.get_descriptive_name())



my_tesla = car.ElectricCar('tesla', 'roadster', 2016) ❸

print(my_tesla.get_descriptive_name())

 

At ❶, we imported the whole car module. Next, we use the syntax module_name.class_name accesses the required class. As before, we created a Volkswagen Beetle at ❸ and a Tesla Roadster at ❸.

 

Operation file

The following program opens and reads the file and displays its contents on the screen:

file_reader.py

with open('pi_digits.txt') as file_object:

contents = file_object.read()

print(contents)

 

The keyword with closes the file after it no longer needs to be accessed.

 

The absolute path opens the file as follows:

file_path = '/home/ehmatthes/other_files/text_files/filename.txt'

with open(file_path) as file_object:

 

To check a file one line at a time, use the for loop on the file object:

file_reader.py

filename = 'pi_digits.txt' ❶



with open(filename) as file_object: ❷

for line in file_object: ❸

print(line)

 

PI file_ digits.txt The lines of are stored in a list and printed outside the with code block:

filename = 'pi_digits.txt'



with open(filename) as file_object:

lines = file_object.readlines() ❶



for line in lines: ❷

print(line.rstrip())

 

Write empty file

with open(filename, 'w') as file_object: ❶

file_object.write("I love programming.") ❷

The first argument is also the name of the file to open; the second argument ('w ') tells Python that we want to open the file in write mode. When opening a file, you can specify the read mode ('r '), write mode ('w'), append mode ('a ') or the mode ('r +') that allows you to read and write to the file. If you omit the schema argument, Python will open the file in the default read-only mode.

If the file you want to write does not exist, the function open() will automatically create it. However, be careful when opening a file in write ('w ') mode, because if the specified file already exists, Python will empty it before returning the file object.

Keywords: Python Programming less Session

Added by cli_man on Sun, 14 Jun 2020 06:59:49 +0300