Python learning notes -- Summary of basic knowledge

Posted by bradkenyon on Fri, 21 Jan 2022 04:58:00 +0100

List operation

You can use the function range() to generate a specified sequence of numbers.
range(1,5) means 1,2,3,4
You can create a list of numbers by using range() as an argument to the function list():
For example, create a list of 1-5

numbers = list(range(1,6))

Create a list of numbers entered by the user:

numbers = list(map(int,input().split()))

You can use * * to represent square in python
The min() function can find the minimum value of a list of numbers, max() the maximum value, and sum() the sum

Dictionaries

In Python, a dictionary is a series of key value pairs.

Each key is associated with a value, and you can use the key to access the value associated with it. The values associated with keys can be numbers, strings, lists, and even dictionaries. In fact, any Python object can be used as a value in the dictionary.

Each key value key = > value pair of the dictionary is separated by colon, and each key value pair is separated by comma. The whole dictionary is included in curly brackets {}. The format is as follows:

d = {key1 : value1, key2 : value2 }

Example 1:

>>> tinydict = {'a': 1, 'b': 2, 'b': '3'}
>>> tinydict['b']
'3'
>>> tinydict
{'a': 1, 'b': '3'}

Example 2:

tinydict = {'Name': 'Runoob', 'Age': 7, 'Name': 'Manni'} 
 
print "tinydict['Name']: ", tinydict['Name']

Create dictionary and new key value pairs

alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)

Output:

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

When deleting, you can use the del() function to delete.

Functions and modules

Basic format of function:

def functionname( parameters ):
   "function_Document string"
   function_suite
   return [expression]
Function code block def Keyword, followed by function identifier name and parentheses(). 
Any passed in parameters and arguments must be placed between parentheses. Parentheses can be used to define parameters.
The first line of the function can optionally use a document string - used to hold the function description.
The function content starts with a colon and is indented.
return [expression] End the function and optionally return a value to the caller. Without expression return Equivalent to return None. 

Function example:

def max(a, b):
    if a > b:
        return a
    else:
        return b

Mutable and immutable objects

In python, strings, tuples, and numbers are immutable objects, while list,dict, and so on are modifiable objects.

modular:
A module is a file that contains all the functions and variables you define. Its suffix is py. The module can be introduced by other programs to use the functions in the module. This is also the way to use the python standard library.
import statement
To use a Python source file, simply execute the import statement in another source file. The syntax is as follows:

import module1[, module2[,... moduleN]

Python's from statement allows you to import a specified part from the module into the current namespace. The syntax is as follows:

from modname import name1[, name2[, ... nameN]]

It is also feasible to import all the contents of a module into the current namespace. Just use the following Declaration:

from modname import *

dir() function

The built-in function dir() can find all the names defined in the module. Return as a list of strings:
give an example:

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)  
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
 '__package__', '__stderr__', '__stdin__', '__stdout__',
 '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
 '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
 'call_tracing', 'callstats', 'copyright', 'displayhook',
 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
 'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
 'thread_info', 'version', 'version_info', 'warnoptions']

output

Character output:
str(): the function returns a user-friendly expression.
repr(): produces an interpreter readable expression.

>>> s = 'Hello, Runoob'
>>> str(s)
'Hello, Runoob'

>>> repr(s)
"'Hello, Runoob'"

>>> str(1/7)
'0.14285714285714285'

>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x The value of is: ' + repr(x) + ',  y The value of is:' + repr(y) + '...'
>>> print(s)
x The value of is: 32.5,  y The value of is 40000...

>>> #  The repr() function can escape special characters in a string

... hello = 'hello, runoob\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, runoob\n'
>>> # The argument to repr() can be any Python object
... repr((x, y, ('Google', 'Runoob')))
"(32.5, 40000, ('Google', 'Runoob'))"

Format output:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note the use of the previous line 'end' to change the default carriage return at the end of the output to a space
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

The rjust() method of the string object can keep the string to the right and fill in spaces on the left.
Similarly, ljust() is a string left

The basic use of str.format() is as follows:
The parentheses and the characters inside them (called formatting fields) will be replaced by the parameters in format().

The number in parentheses is used to point to the position of the incoming object in format(), as shown below:

>>> print('{} and {}'.format('Google', 'Runoob'))
Google and Runoob
>>> print('{0} and {1}'.format('Google', 'Runoob'))
Google and Runoob
>>> print('{1} and {0}'.format('Google', 'Runoob'))
Runoob and Google

Used in {}! A (using ASCII ())! S (using str()) and! r (using repr()) can be used to convert a value before formatting it

%Operators can also implement string formatting. It takes the parameters on the left as a format string similar to sprintf(), substitutes the parameters on the right, and then returns the formatted string

>>> import math
>>> print('constant PI The approximate value of is:%5.3f. ' % math.pi)
constant PI The approximate value of is: 3.142. 

object

Related concepts:

Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.
Method class.
Class variables: class variables are common to the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are usually not used as instance variables.
Data members: class variables or instance variables are used to process data related to classes and their instance objects.
Method Rewriting: if the method inherited from the parent class cannot meet the needs of the child class, it can be rewritten. This process is called method override, also known as method rewriting.
Local variable: the variable defined in the method, which only acts on the class of the current instance.
Instance variable: in the declaration of a class, attributes are represented by variables, which are called instance variables. Instance variables are variables decorated with self.
Inheritance: that is, a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is such a design: an object of Dog type is derived from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).
Instantiation: create an instance of a class and a concrete object of the class.
Object: an instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.

Class definition format:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

Class objects support two operations: attribute reference and instantiation.

example:

class MyClass:
    """A simple class instance"""
    i = 12345
    def f(self):
        return 'hello world'
 
# Instantiation class
x = MyClass()
 
# Access the properties and methods of the class
print("MyClass Properties of class i Is:", x.i)
print("MyClass Class method f Output is:", x.f())

Output is:

MyClass Properties of class i Is: 12345
MyClass Class method f Output is: hello world

Inside the class, use the def keyword to define a method. Different from the general function definition, the class method must contain the parameter self, which is the first parameter. Self represents the instance of the class.
self represents an instance of a class, not a class

Topics: Python