python minimalist tutorial 01: basic variables

Test Qitan, the BUG is missing.

In fact, a long time ago, my colleagues or netizens asked me to share some tutorials on python programming language. Like most self-taught programming language people, they encountered the following problems:

  • There are too many data on the network, and the good and bad are incomplete, so I don't know how to distinguish them;
  • "Redundant" knowledge is too much, beginners do not know how to start;
  • I want to master a programming language without spending too much time.

As a non professional tester who became a monk on the way, I also encountered these problems and went through many detours on the way to knowledge, but fortunately I defeated it!

Therefore, I love to say that there are always more ways than problems.

When you see here, I don't want to give you more chicken soup. In short, learning python is really useful!

This useful does not mean that if you learn python, you can do automated testing, get a higher salary, get a better job, etc., but you should understand the change of Python to your working mode and realize that the programming language is just a tool.

For example, I can use text comparison software to replace manual word for word comparison - the former greatly improves your work efficiency.

python is the same. It can significantly improve your work efficiency and improve your way of thinking.

This hidden, thinking skill upgrade is the biggest help to you, even if you don't continue to engage in testing in the future.

I hope this "nonsense" is useful to you.

Next, let's get to the point. I'll share with you a set of minimalist tutorials for quickly mastering python on the content of the training for the group test in the past two months.

Let's talk about the purpose of the tutorial first: you can draw a ladle according to the gourd, which can be used at first.

Let's talk about the content of the tutorial: most of them are scenes I use more in coding at ordinary times, so as to solve the trouble that you don't know what to learn and avoid taking in too much "redundant" knowledge at the beginning of learning.

This one focuses on the variable types of python.

Objective: to be familiar with the basic variable types in python and the knowledge points we should focus on.

Note: variable assignment in Python does not require type declaration.

Common python variable types are:

counter = 100 # integer
miles = 1000.0 # float 
name = "John" # character string
py_list = [123, 'john'] # list
py_tuple = (123, 'john') # tuple
py_dict = {'name': 'runoob','code':6734, 'dept': 'sales'} # Dictionaries

Integer and floating point are integers and decimals. Those who have studied mathematics know it clearly. There is nothing to say. I'll start with the string.

character string

[common scenario 1] format conversion, eg: conversion between string, json and dictionary types

# Built in function - string to json
str1 = "{'key':1,'value':2}"
eval(str1)
# This method is generally used for conversion, but it has a problem. If there is a null value in json, it cannot be used. In this case, the json library needs to be used

import json
json1= '{"key":null,"value":2}'
dicts = json.loads(json1)  # null of json can be replaced with None recognized by python
print(dicts)

[common scenario 2] using single and double quotation marks

# Double quotes in double quotes need to be escaped
string1 = "hello,my,\"god\" "
# Double quotation marks in single quotation marks do not need to be escaped
string2 = 'hello, my "god" '

[common scenario 3] using multiple quotation marks

# For example, we need to write an sql statement in the py file
sql_a = 'select * from asset where asset_create_at >= "2018-08-01" '
# Note that a space is required to the left of each closing quotation mark, which is particularly troublesome to write code
sql_b = ('select * '
    'from asset '
    'where asset_id = "123456";'
    )
sql_c = '''
select * from asset where asset_create_at >= "2018-08-01"
'''
# You can also write freely within three quotation marks, which is more convenient. However, it should be noted that the actual string contains three lines, that is, the line feed before sql and the line feed after sql (actually harmless)

list

The index key of the list must be mastered!!!

lst = ['a', 'b', 'c','d','e','f']
lst.append('g') # Add a value at the end of the list
lst.pop(0) # Delete value at index position
lst[0] # Take the value of index=0
lst[1:3] # Take the value of index from 0 (excluding) to index=3

List traversal iteration key points must be mastered!!!

li = ['a', 'b', 'c', 'd', 'e']
# General traversal
for i in li:
    print(i)

# Indexed traversal
for i, e in enumerate(li):
    print("index:",i,"element:",e)

[expansion scenario 1]: multi list iteration

# loop nesting 
# Disadvantages: high code complexity
x_list, y_list, z_list = [], [], []
for x in x_list:
    for y in y_list:
		for z in z_list:
     		None
# itertools standard library
# Disadvantages: inconvenient debugging
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
	None

[extended scenario 2]: intersection, union, difference

a=[2,3,4,5]
b=[2,5,8]
# intersection 
print(list(set(a).intersection(set(b))))
# Union
list(set(a).union(set(b)))
# Difference set
list(set(b).difference(set(a))) # What is in b but not in a
list(set(a).difference(set(b))) # What is in a but not in b

tuple

How to understand: tuples can be regarded as non editable list s (this type is rarely used)

('a','b','c','d')

Dictionaries

How to understand: key value pairs

The key points must be mastered!!!

personinfo = {'name': 'joe', 'age':'20', 'hobby':'football'}
personinfo['name']

The key points of traversal iteration must be mastered!!!

personinfo = {'name': 'joe', 'age':'20', 'hobby':'football'}
for k, v in personinfo.items():
    print(k, v)

[practical scenario 1] merge and copy

# merge
date_info = {'year': "2020", 'month': "01", 'day': "01"}
track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'}
all_info = {**date_info, **track_info}
# add value
date_info = {'year': '2020', 'month': '01', 'day': '7'}
event_info = {**date_info, 'group': "Python Meetup"}
# Overwrite specific values while copying / merging Dictionaries
event_info = {'year': '2020', 'month': '01', 'day': '7', 'group':'Python Meetup'}
new_info = {**event_info, 'day': "14"}

[practical scenario 2] the key points of json and dictionary conversion must be mastered!!!

import json
data = {"spam" : "foo", "parrot" : 42} # Convert python objects to json
python_to_json = json.dumps(data)
print(python_to_json)
json_to_python = json.loads(python_to_json) # Convert json to python object
print(json_to_python)

expand

isinstance: used to judge the type of an object, or whether an object is an instance of a class

# [common scenario 1]: judge the type of object
py_int = 1
py_str = 'a'
py_list = ['a','b']
py_dict = {'a':1,'b':2}
isinstance(py_int, int)

# [common scenario 2]: whether an object is an instance of a class
class C():
	pass
cc = C()
isinstance(cc, C)

Format: used to assemble and format data

# [common scenario 1]: load string
py_str = "hello {0}".format("world")
py_str = "hello {}{}".format("great","world!")
# [common scenario 2]: loading list
a = [1,2]
py_list = 'List first: {0}; List second: {1}'.format(a[0],a[1])
py_list = 'List first: {0[0]}; List second: {0[1]}'.format(a)
# Common scenario 3: loading dictionary
student = {"name": "zhao", "age": 5}
"My name is {} and my age is {}".format(student['name'],student['age'])
"My name is {pig[name]} and my age is {pig[age]}".format(pig=student)

As always, make a summary

01 python variables are the basis of python syntax and the most important of the important;

02 be sure to do it again.

Added by jakeklem on Sun, 02 Jan 2022 04:50:08 +0200