0. Learning objectives
Python is a concise, easy to learn, object-oriented programming language. It not only has powerful native data types, but also provides simple and easy-to-use control statements. stay Python based variables and built-in data types In, we introduced the built-in native data types in Python. The main goal of this section is to introduce how Python programs use input and output statements to interact with users, as well as high-order assignment statements, so as to lay a foundation for subsequent learning. This paper will completely introduce the basic knowledge and basic ideas of Python required to learn data structures and algorithms, and give corresponding practical examples and explanations.
- Master Python to interact with users using input and output
- Understand and master Python high-order assignment statements
1. Input, output and comments
1.1 get user input
Programs often need to interact with users to obtain the data submitted by users. Python provides an input function that accepts user input data and returns a reference to a string.
The input function accepts a string as a parameter, which is used as the text to prompt the user for input. Therefore, it is also called Prompt string:
>>> number = input('Enter the number of students: ') Enter the number of students: 52 >>> number '52'
In the interactive interpreter, execute the first line number = input('Enter the number of students: '), which prints the string "Enter the number of students:", prompting the user to enter the corresponding information. Enter 52 here and press enter to get the user's input after the prompt string and store it in the number variable. Note that the value returned by the input function is of string type. If you need to convert this string to other types, you must provide corresponding type conversion to perform the required operations:
>>> score = input('Enter the total score: ') Enter the total score: 4396 >>> number = input('Enter the number of students: ') Enter the number of students: 52 >>> average_score = int(score) / int(number) >>> average_score 84.53846153846153
1.2 formatted output
1.2.1 basic methods
In the above example, we have seen the print function more than once, which provides a very easy way to print Python output. It accepts zero or more parameters. By default, a single space is used as the separator to display the results. The separator can be modified by the optional parameter sep. In addition, by default, each print ends with a newline character, which can be changed by setting the parameter end:
>>> print('Data', 'Structure', 'and', 'Algorithms') Data Structure and Algorithms >>> print('Data', 'Structure', 'and', 'Algorithms', sep='-') Data-Structure-and-Algorithms >>> print('Data', 'Structure', 'and', 'Algorithms', sep='-', end='!!!') Data-Structure-and-Algorithms!!!>>>
A format string is a template that contains words or spaces that remain unchanged, as well as placeholders for variables inserted later. Using the format string, you can change according to the value of the runtime variable:
print("The price of %s is %d yuan." % (fruit, price))
%Is a string operator, called a format operator. The left part of the expression is the template (also known as the format string), and the right part is a series of values used to format the string. The number of values on the right is consistent with% in the format string. These values will be swapped into the format string from left to right.
The format string can contain one or more conversion declarations. The conversion character tells the formatting operator what type of value will be inserted into the corresponding position in the string. In the above example,% s declares a string and% d declares an integer.
A format modifier can be added between% and format characters to achieve more complex output formats:
>>> print("The price of %s is %d yuan." % ('apple', fruits['apple'])) The price of apple is 5 yuan. >>> print("The price of %s is %10d yuan." % ('apple', fruits['apple'])) The price of apple is 5 yuan. >>> print("The price of %s is %+10d yuan." % ('apple', fruits['apple'])) The price of apple is +5 yuan. >>> print("The price of %s is %-10d yuan." % ('apple', fruits['apple'])) The price of apple is 5 yuan. >>> print("The price of %s is %10.3f yuan." % ('apple', fruits['apple'])) The price of apple is 5.000 yuan. >>> print("The price of apple is %(apple)f yuan." % fruits) The price of apple is 5.000000 yuan.
1.2.2 format function
Although the above methods can still be used, another recommended solution is template string format, which aims to simplify the basic format setting mechanism. It integrates and strengthens the advantages of the previous method. When the format function is used, each replacement field is enclosed in curly braces, which can contain the variable name, or the replacement field can have no name or reference the index as the name::
>>> "The price of {} is {} yuan.".format('apple', 5.0) 'The price of apple is 5.0 yuan.' >>> "The price of {fruit} is {price} yuan.".format(fruit='apple', price=price) 'The price of apple is 5.0 yuan.' >>> "The price of {1} is {0} yuan.".format(5.0, 'apple') 'The price of apple is 5.0 yuan.'
As you can see from the above example, the order of index and variable names is irrelevant. In addition, the format specifier (similar to the% operator) is used by combining the colon:, with:
>>> value = 2.718281828459045 >>> '{} is approximately {:.2f}'.format('e', value) 'e is approximately 2.72' >>> '{} is approximately {:+.2f}'.format('e', value) 'e is approximately +2.72' >>> '{} is approximately {:0>10.2f}'.format('e', value) 'e is approximately 0000002.72' >>> '{} is approximately {:0<10.2f}'.format('e', value) 'e is approximately 2.72000000' >>> '{} is approximately {:^10.2f}'.format('e', value) 'e is approximately 2.72 ' >>> '{:,}'.format(100000) '100,000' >>> '{} is approximately {:.2%}'.format('e', value) 'e is approximately 271.83%' >>> '{} is approximately {:.4e}'.format('e', value) 'e is approximately 2.7183e+00' >>> '{} is approximately {:0=+10.2f}'.format('e', value) 'e is approximately +000002.72'
From the above example, it is easy to summarize that: can be used to specify width, precision and thousand separator, etc. ^, <, > can be used for center, left alignment and right alignment respectively, and then can specify width and fill with a specified single character. By defau lt, it is filled with space or specifier =, Specifies that fill characters are placed between symbols and numbers.
Similarly, we can use b, d, o and x for data type conversion, which are binary, decimal, octal and hexadecimal respectively. c is used to convert data to Unicode code:
>>> "The number is {num:b}".format(num=1024) 'The number is 10000000000' >>> "The number is {num:d}".format(num=1024) 'The number is 1024' >>> "The number is {num:o}".format(num=1024) 'The number is 2000' >>> "The number is {num:x}".format(num=1024) 'The number is 400' >>> "The number is {num:c}".format(num=1024) 'The number is Ѐ'
1.3 notes
It's time to introduce annotations. Annotations are a great way to improve program readability, and they are easy to ignore. Python does not interpret text that follows a # symbol:
radius = 5.0 # Radius of circle side = 2.0 # Square side length # Difference between square area and circular area area_c = 3.14 * radius ** 2 area_s = side ** 2 diff = area_s - area_c
If you want to use multiline comments, you can place the comment statement between a pair of three double quotation marks ("" ") or a pair of three single quotation marks (''):
radius = 5.0 side = 2.0 area_c = 3.14 * radius ** 2 area_s = side ** 2 diff = area_s - area_c
2. High order assignment statement
We have learned how to assign values to variables or data elements of data structures, but there are other types of assignment statements that can be used to simplify the code and increase the readability of the code.
2.1 assignment operator
In addition to the most basic = assignment operator, you can also move the standard operator in the expression on the right to the front of the assignment operator = to form a new operator, such as + =, - =, * =, / =,% =:
>>> number = 1 >>> number += 4 >>> print(number) 5 >>> number //= 2 >>> print(number) 2 >>> number **= 2 >>> print(number) 4 >>> string_1 = 'Hello!' >>> string_1 *= 2 >>> print(string_1) 'Hello!Hello!'
Yes, this assignment method can be used not only for numerical data, but also for other data types (as long as the data type supports the binocular operator used).
2.2 parallel assignment
In addition to assigning values one by one, multiple variables can be assigned simultaneously (in parallel):
>>> a, b, c, d = 0, 1, 2, 3 >>> print(a, b, c, d) 0 1 2 3
In this way, you can simply exchange the values of multiple variables:
>>> b, c = c, b >>> print(a, b, c, d) 0 2 1 3
2.3 sequence unpacking
Sequence unpacking is to unpack an iteratable object and store the obtained value in a series of variables. However, the number of elements contained in the sequence to be unpacked must be the same as the number of variables listed on the left of the equal sign, otherwise an exception will be thrown:
>>> fruit, price = ['apple', 5.0] >>> print(fruit) apple >>> print(price) 5.0 >>> fruit, price, date = ('apple', 5.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: not enough values to unpack (expected 3, got 2) >>> fruit, price = ('apple', 5.0, '2021-11-11') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack (expected 2)
In order to avoid abnormal triggering, the asterisk operator * can be used to collect redundant values, so it is not necessary to ensure that the number of values and variables are the same. The right side of the assignment statement can be any type of sequence, but the variables with asterisks always get a list:
>>> fruits = ['apple', 'orange', 'lemon'] >>> fruit_a, *rest = fruits >>> print(rest) ['orange', 'lemon'] >>> fruits_a, *rest, fruits_b = fruits >>> print(rest) ['orange'] >>> fruits_a, fruits_b, fruits_c, *rest = fruits >>> print(rest) []
2.4 chain assignment
Chained assignment can associate multiple variables to the same value:
var_1 = var_2 = value
Equivalent to:
var_1 = value var_2 = var_1