Python basics learning

Python data type

Here are just some differences between Python and Java and JavaScript. If you have any language foundation, I believe you can easily write Python programs after reading this article.

character string

Py strings can be represented by single quotation marks'... ', double quotation marks * *'... '* *, three quotation marks'...', and single quotation marks can be placed in double quotation marks. As follows:

>>> print("I'm OK") 
I'm OK

>>> print('I\'m OK') #Use escape characters
I'm OK

If many characters in the string need to be escaped, you need to add a lot of \. In order to simplify, Python also allows r '...' to represent the string inside '...' without escape by default

>>> print('\\\\')

>>> print(r'\\\\')

If there are many line breaks in the string, it is not easy to read \ nwriting in one line. For simplicity, Python allows multiple lines to be represented in the format of '...' '

>>> print('''Hello
... World!
... I'm Leo!''')

I'm Leo!

Note that * * '* * here can be printed without escape characters, but for safety reasons, it can be written as follows:

>>> print(r'''Hello
... World!
... I'm Leo!''')

I'm Leo!

Indicates that line breaks can be recognized and not escaped by default. This is very useful. It can handle some multi line text. If there is a need to preserve the content style, it can also be well met.

String formatting

In Python, the formatting method adopted is consistent with that of C language, which is implemented with%

>>> 'Hello, %s' % 'world'
'Hello, world'

>>> 'Hello, %s, %d time' % ('world', 3)
'Hello, world, 3 time'

Inside the string,% s means to replace with a string,% d means to replace with an integer. How many%? Placeholder, followed by several variables or values, in good order. If there is only one%?, Parentheses can be omitted.

Common placeholders are: %d -- integer %f -- floating point number %s -- string %x -- hexadecimal integer

Formatting integers and floating-point numbers can also specify whether to complement 0 and the number of integers and decimals

>>> '%2d - %02d' % (2,1)
' 2 - 01'

>>> '%2.f' % 3.14
' 3'

>>> '%.2f' % 3.1415

If you're not sure what to use,% s will always work, and it will convert any data type to a string:

>>> 'Age: %s. Gender: %s' % (25, True)
'Age: 25. Gender: True'

What if% in the string is an ordinary character? At this time, you need to escape. Use%% to represent a%

>>> 'growth rate: %d %%' % 7
'growth rate: 7 %'

Boolean value

The difference between Boolean values and JavaScript and Java is that True and False start with uppercase. In addition, logical operations are performed with and, or and not. I only know this difference for the time being.

>>> age=1
>>> if age >= 18:
...     print('adult')
... else:
...     print('teenager')

Null value

The null value in Py is represented by None. During logical operation, None is equivalent to False

>>> None==None
>>> if(not None):
...     print('Leo')
>>> not None


Variable names in Python must be uppercase, lowercase, English, numeric, and_ And cannot start with a number. Py is extremely simple to define a variable. You only need to write the variable name = XX. Since py is a dynamic language, the data types of variables can be switched at will.


In Java, the final keyword is generally used to define constants. The final constant is usually declared with an initial value, or it can be given an initial value in the constructor. In order to save memory space, we often declare variables as static

static final double PI=3.1415926;

In JavaScript, the ES6 standard also adds support for constants, using the const keyword

const MY_FAV = 7;

There are no real constants in Python, but if you see all values in uppercase letters, you'd better be cautious.

PI = 3.14159265359


Py has two kinds of division, one is floating-point division and the other is integer division. Floating point division / the result is a floating point number whether or not it is divisible.

>>> 10/3

Another division method is / /, which is called floor division. The division of two integers is always an integer, just like Java.

>>> 10//3

Data type conversion

>>> int('123')
>>> int(12.34)
>>> float('12.34')
>>> str(1.23)
>>> str(100)
>>> bool(1)
>>> bool('')


list is an ordered collection in which elements can be added and deleted at any time.

>>> students=[1,'xiao',True]
>>> len(students)
>>> students[0]
>>> students[2]

>>> students[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

When the index exceeds the range, Python will report an IndexError error If you want to get the last element, in addition to calculating the index position (len()-1), you can also use - 1 as the index to get the last element directly

>>> students[-1]

Common operations are: append(), insert(index, value), pop(), pop(index),

>>> students.append('Leo') #Append an element
>>> students
[1, 'xiao', True, 'Leo']

>>> students.insert(2, False) #Insert an element
>>> students
[1, 'xiao', False, True, 'Leo']

>>> students.pop() #Delete end element
>>> students
[1, 'xiao', False, True]


The Chinese name is tuple. Tuple is also an ordered list. Tuple cannot be modified after initialization, so it is safer to use.

>>> names=('Jack', 'Lucy', 'Leo') #When tuple is defined, the element must be determined
>>> names 
('Jack', 'Lucy', 'Leo')

>>> names=(True,) #If there is only one element, distinguish it from parentheses
>>> names
(True,)          #Python also adds a comma when displaying a tuple with only one element

>>> t=() #Define an empty tuple
>>> t

It is worth noting that the so-called invariance of tuple means that the direction of each element is unchanged. If the object pointed to is changed, the tuple is also changeable. For example:

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])

Conditional judgment

Write a sample to understand everything

age = 16
if age >= 18:
elif age >= 6:

elif is the abbreviation of else if

if x:

As long as x is a non-zero value, non empty string, non empty list, etc., it is judged to be True, otherwise it is False


Use input to get the user's input

>>> age=input()
>>> age

However, you can see that the value obtained by input is a string, so you can use int(age) for data type conversion


for in loop

The for... In loop iterates out each element in the list or tuple in turn, substitutes it into a variable, and then executes the statement indenting the block.

>>> for x in range(3):
...     print(x)

range() can produce a sequence of integers, which can be converted to list through the list() function. For example, the sequence generated by range(5) is an integer starting from 0 and less than 5, Range (2,4) the production sequence starts from 2 and is an integer less than 4.

>>> range(3)
range(0, 3)

>>> list(range(3))
[0, 1, 2]

>>> list(range(2,4))
[2, 3]

while Loop

The while loop is almost no different from Java and JS, but the format is a little different

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2

dict and set


dict in Python is a dictionary, which is equivalent to an object or map in JavaScript and Java. In general, Python dict is used similar to JavaScript objects. Let's first look at how to define a Python dictionary

>>> ages={'Leo':20,'Jack':25,'Lucy':34}
>>> ages
{'Leo': 20, 'Lucy': 34, 'Jack': 25}
>>> ages['Leo']

Dict has the advantage of fast search speed. Imagine if you look up a word through a dictionary, first find the page number of the word through pinyin or side, and then turn to this page directly. Therefore, no matter which word to find, this search speed is very fast and will not slow down with the increase of dictionary size. This is the advantage of dict.

Python will report an error if the key does not exist

>>> ages['Pig']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Pig'

You can determine whether a key exists through in

>>> 'Leo' in ages

Get the value corresponding to the key through get. If the key does not exist, return None. You can also specify the return value when the key does not exist.

>>> ages.get('Lucy')
>>> ages.get('Lu')
>>> ages.get('Lu', 30)

Compared with list, dict has the following characteristics:

  1. The search and insertion speed is extremely fast and will not slow down with the increase of key s;
  2. It takes up a lot of memory and wastes a lot of memory.

On the contrary:

  1. The time of searching and inserting increases with the increase of elements;
  2. It takes up little space and wastes little memory.

Therefore, dict is a way to exchange space for time.


set is a collection without duplicate elements, which is the same as Java and JavaScript. The usage is also very similar

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}

>>> s.add(4)
>>> s
{1, 2, 3, 4}

>>> s.remove(4)
>>> s
{1, 2, 3}

set in Python can do intersection and union, which is more powerful

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}


Built in function

Python provides many built-in functions, and there are detailed documents for reference. Address: A blog explaining the built-in functions will be written later. Please look forward to it

Define function

Python uses def to define a function

def  my_abs(x):
    if x >= 0:
        return x
        return -x
  1. If the function does not have a return statement, it returns None by default
  2. return None = return
  3. Import functions through from... (file name) import... (function name)
  4. You can also use pass in the function to do nothing
  5. Functions can return multiple values
>>> def cal(x, y):
...     add = x + y
...     sub = x - y
...     return add,sub
>>> a1, a2 = (5, 3)
>>> a1
>>> a1, a2
(5, 3)


The parameters of Python functions are much more powerful than those of Java and JavaScript. In addition to the required parameters normally defined, default parameters, variable parameters and keyword parameters can also be used, so that the interface defined by the function can not only deal with complex parameters, but also simplify the caller's code.

Default parameters

def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
power(5) #25

power(5, 2) #25

power(5, n=3) # 125

One thing to keep in mind when defining default parameters: default parameters must point to invariant objects! Why? Let's take an example:

def test(lang=[]):
  return lang

When called honestly, the result is what you want

print(test(['js','go']))  #['js', 'go', 'python']
print(test(['c','java']))  #['c', 'java', 'python']

However, if the default parameter is called multiple times

print(test())  #['python']
print(test())  #['python', 'python']

analysis: When the function is defined, the value of the default parameter lang has been declared, i.e. empty [], that is, the default parameter points to the object []. When the default parameter is called many times, the data pointed to the object by the default parameter is changed. The data pointed to the object by the default parameter changes. The default parameter has changed the next time you call, instead of empty []

For ease of understanding, it is equivalent to the following paragraph:

temp = []
def test(lang=temp):
  return lang

Modify code again:

def test(lang=None):
  if lang is None:
    lang = []
  return lang

Summary: When defining function default parameters, the function default parameters must point to immutable objects. It is recommended to use None and str to handle immutable objects

Variable parameters

Variable parameters means that the number of parameters passed in is variable, which can be 1, 2 to any, or 0.

If you want to define a summation function and the number of incoming parameters is unknown, you can define it in a general way

def sum(numbers):
    sum = 0
    for n in numbers:
        sum = sum +n
    return sum

However, when calling, you need to assemble a list or tuple:

sum([1,2,3]) #6
sum((1,2,3)) #6

Use variable parameter definitions:

def sum(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n
    return sum

You can pass in any parameter when calling

sum(1,2,3) #6

Keyword parameters

Variable parameters allow you to pass in 0 or any parameters. These variable parameters are automatically assembled into a tuple when the function is called. Keyword parameters allow you to pass in 0 or any parameter with parameter name. These keyword parameters are automatically assembled into a dict within the function.

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)

In addition to the required parameters name and age, the function person also accepts the keyword parameter kw. When calling this function, you can only pass in the required parameters or any number of keyword parameters.

person('Leo', 18)  #name: Leo age: 18 other: {}
person('Bob', 35, city='Beijing')  #name: Bob age: 35 other: {'city': 'Beijing'}
person('Adam', 45, gender='M', job='Engineer')   #name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

Posted on Fri, 26 Nov 2021 07:32:03 -0500 by PHPFreaksMaster