Detailed Explanation of Input Output and High order Assignment of Python Foundation

  • 2021-12-13 08:52:03
  • OfStack

Directory 1. Input, Output, and Comments1.1 Get User Input 1.2 Formatted Output 1.2. 1 Basic Methodology 1.2. 2 format Formatting Functions1.3 Comments2. Higher-order Assignment Statements 2.1 Assignment Operators 2.2 Parallel Assignment 2.3 Sequence Unwrapping 2.4 Chain Assignment Summary

1. Input, Output, and Comments

1.1 Getting User Input

Programs often need to interact with users to obtain data submitted by users. Python provides the input function, which accepts user input data and returns a reference to a string.
The input function takes as an argument a string that is used as text to prompt the user for input, so it is also called a prompt string:


>>> number = input('Enter the number of students: ')
Enter the number of students: 52
>>> number
'52'

Execute line 1 number = input ('Enter the number ES22students:') in the interactive interpreter, which prints the string "Enter the number of students:" and prompts the user for the corresponding information. Here, enter 52 and press Enter to get the user's input after the prompt string, which is stored in the number variable. It should be noted that the value returned by the input function is a string type. If you need to convert this string to another type, you must provide the corresponding type conversion to do the required operation:


>>> 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 Formatting Output

1.2. 1 Basic methodology

We have seen the print function more than once in the above example, which provides a very easy way to print Python output. It accepts zero or more parameters and uses a single space as the delimiter to display the results by default, which can be modified with the optional parameter sep. In addition, every print ends with a line break by default, 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!!!>>>

The formatted string is a template that contains words or spaces that remain the same and placeholders for variables that are inserted later. Using formatted strings, you can change according to the value of runtime variables:


print("The price of %s is %d yuan." % (fruit, price)) 

% is a string operator, which is called a formatting operator. The left part of the expression is a template (also called a formatted string), and the right part is a series of values for formatted strings. The number of values on the right is equal to the number of% in the formatted string. These values are swapped into the formatted string from left to right.

The formatted string can contain one or more conversion declarations. The conversion character tells the formatting operator what type of value is inserted at the appropriate position in the string. In the above example,% s declares 1 string and% d declares 1 integer.

You can add a format modifier between% and formatted characters for 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 formatting function

Although the above method can still be used, another recommended solution is the template string format, which aims to simplify the basic formatting mechanism and integrates and strengthens the advantages of the previous method. When using the format formatting function, each substitution field is enclosed in curly braces, which can contain the variable name, or the substitution field can have no name or use 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 can be seen from the above example, the order in which the indexes and variable names are arranged is irrelevant. In addition, the format specifier (similar to the% operator) is used by combining the colon::


>>> 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 sum up that you can specify width, precision, thousand separator, etc. by using the: sign, < , > Centered, left-aligned, and right-aligned, and can be followed by a specified width, and can be filled with a specified single character, with spaces by default, or with the specifier =, which specifies that the fill character should be placed between symbols and numbers.
Similarly, we can use b, d, o and x for data type conversion, which are binary, decimal, octal and 106, respectively. c is used to convert data into 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  In fact, in fact, the '

1.3 Notes

It's time to introduce annotations. Annotations are a great way to improve the readability of programs, and they are also easy to overlook. Python does not interpret the text immediately following the # symbol:


radius = 5.0 #  The radius of a 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 multi-line comments, you can place the comment statement between 1-3 double quotation marks ("" ") or 1-3 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 statements

We've learned how to assign values to variables, or to data elements of a data structure, but there are other types of assignment statements that can be used to simplify code and make it more readable.

2.1 Assignment Operator

In addition to the most basic = assignment operator, you can also move the standard operator in the right expression before the assignment operator = to form new operators, such as +=, -=, *=, /=,% =, and so on:


>>> 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
0

This assignment can be used not only for numeric data, but also for other data types (as long as the data types support the binocular operators used).

2.2 Parallel assignment

You can assign values to multiple variables at the same time (in parallel), in addition to assigning one to one:


>>> 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

In this way, you can simply exchange the values of multiple variables:


>>> 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
2

2.3 Sequence unpacking

Sequence unpacking is to unpack an iterable object and store the resulting value in a series of variables, but the sequence to be unpacked must contain the same number of elements as the variables listed to 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)

To avoid exception triggering, you can use the asterisk operator * to collect redundant values, so you don't need to ensure that the number of values and variables is the same. The right side of the assignment statement can be any type of sequence, but the asterisk variables always end up with a list:


>>> 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
4

2.4 Chain assignment

Chain assignment can associate multiple variables with the same value:


>>> 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
5

Equivalent to:


>>> 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
6

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: