The Road to Python Learning (1)-Talking about the novice Xiaobai's understanding of the print() function

The Road to Python Learning (1)-Talking about the novice Xiaobai's understanding of the print() function

Write in front

  The author is currently a senior at school (some low-level 211), and college life is about to draw the end, but I have not really mastered a language, so I am ashamed. Participated in various cultural and sports activities during the university, won many speech contest awards, participated in many subject contests, won several small awards, and spent a lot of time on student work (finally served as Student Council President). These resumes seem to be pretty good to those who don't know why, or those who have just entered the university. The author himself was complacent about it before. However, it wasn't until I was ruthlessly lashed by many teachers at the interview school during the interview in September this year (the author was lucky enough to get a midstream 985), that I deeply realized my shortcomings. And I also deeply understand that the fancy resume is just for others to see. Only me knows how many catties are. Have the ability to fool others but not yourself. So I decided to learn Python (I knew it before, but I didn't learn it systematically), and recorded some of my learning experience in the blog, because I am a beginner (although I am already a senior, alas, I am ashamed) inevitably some things will go wrong, I beg you to give me some advice, I will definitely correct the mistakes, I hope to advise! If there are friends who are learning python like me, then we are welcome to communicate and learn with each other. In addition, all quoted content in this article will be marked with the source. If there is any omission, please remind me, I will definitely add and correct it.

1. The function and basic syntax of print()

  Friends who have had a programming foundation should know that the function of print() is to output, and those with a zero foundation don’t have to worry, at least we still know English, right (print in English means printing)

1.print() function role

  Is to print and output the content

2. Basic grammar:

print(1,2,...值n,sep=' ', end='\n')

Sep function: set the separator between the output
end function: used to set the symbol at the end of the output, the default is a newline character, of course we can also change to other characters

Here are a few simple examples:

(1) The simplest direct output

print("hello,world")
#输出内容为 hello,world

  For the output of other data types, I have ctrl+c and ctrl+v for the codes of other bloggers (because it is about to grab a meal with the freshmen, so I have to carry one) for your reference (of course all references) All are explained at the end, definitely not malicious plagiarism)

num = 19
print(num)  # 19  输出数值型变量
str = 'Duan Yixuan'
print(str)  # Duan Yixuan  输出字符串变量
list = [1, 2, 'a']
print(list)  # [1, 2, 'a']  输出列表变量
tuple = (1, 2, 'a')
print(tuple)  # (1, 2, 'a') 输出元组变量
dict = {
    
    'a': 1, 'b': 2}
print(dict)  # {'a': 1, 'b': 2} 输出字典变量

(2) Use of sep

name="Mr.Q"
age=21
height=178.5
weight=65
print(name,age,height,weight,sep="!")
print(name,age,height,weight)
#输出内容为 
#Mr.Q!21!178.5!65
#Mr.Q 21 178.5 65

  Separator between output variables is set using sep in the first output, and there is no setting in the second output, so the default output variables are spaces

(3) The use of end

name="Mr.Q"
age=21
height=178.5
weight=65
print(name)
print(age,end="+")
print(height,end="\n")
print(weight)
'''
输出结果为
Mr.Q
21+178.5
65
'''

  Through this example, we can clearly see the role of end in the
output`
  Note: The output of the print() function in python is line feed by default.

Two, two output methods of variables

  All variables in python can be output through the print() function, such as integer, floating point, string, list, tuple, dictionary, etc. The author currently understands that there are two output methods: "+" splicing and "," comma-separated variables (named by yourself, please point out if there are errors) (formatted output will be discussed separately later)

1. "+" splicing

name="Mr.Q"
age=21
height=178.5
weight=65
print(name,str(age),str(height),str(weight),weight)
#输出内容
#Mr.Q 21 178.5 65 65

  The role of str() in the code is to convert the data type to a string type, because the "+" sign splicing method is used to output, it must be ensured that all data types are string types when outputting, remember, remember, remember!

2. "," separated by commas

  In fact, this method has been used again in the above example, here I will copy it again, and the forgotten friends can deepen the impression.

name="Mr.Q"
age=21
height=178.5
weight=65
print(name,age,height,weight,sep="!")
print(name,age,height,weight)
#输出内容为 
#Mr.Q!21!178.5!65
#Mr.Q 21 178.5 65

  All variables here are separated by ","

Three, formatted output

  First of all, I think there are many similarities between the formatted output in python and the output in C/C++. The formatted output that I have learned so far is "%" and format. The format is more powerful. It's more complicated (mainly because I haven't learned it yet, leaving tears of ignorance: () So in this article I will give you a brief introduction to the usage of "%", and I will have the opportunity to write an article about format later. (Because there are so many contents in the formatted output part, you are welcome to point out any improprieties)

1. Formatted output definition

The formatting definition is: the data is output according to some special requirements.
  If you input an integer, you want the integer to be output in hexadecimal, octal, if you input a decimal, you want the decimal to keep the next 2 digits and then output, or in scientific notation Way to output decimals. The output of the string is expected to be output in ten grids, or left-aligned, centered, etc.

Let's look at an example:

#要求输出的身高为两位小数
name = "Mr.Q"
age=21
height=178.5
print("%s的年龄为%d岁,身高为%.2f厘米"%(name,age,height))

'''
输出内容为:Mr.Q的年龄为21岁,身高为178.50厘米
其中"%s的年龄为%d岁,身高为%.2f厘米"这部分叫做:格式控制符
(name,age,height)这部分叫做:转换说明符
%字符,表示标记转换说明符的开始
'''

  The difference between python and C language is that the format control character and conversion specifier in python are separated by %, while the comma is used in C language. I think the others are similar. I will list the generalization of format characters and escape characters later. to sum up.

2. Output of different number systems

  Commonly used values ​​are binary, octal, decimal and hexadecimal
  %o —— oct octal
  %d —— dec decimal
  %x —— hex hexadecimal

print('%o' % 21)
#输出内容:25
print('%d' % 21)
#输出内容:21
print('%x' % 21)
#输出内容:15

3. Floating point formatted output

%f   ——Keep six significant
  digits after the decimal point %.3f, keep three digits after the decimal point
%e——Keep six significant
digits after the decimal point, output %.3e in exponential form , keep three digits after the decimal point, use scientific notation
% g ——On the premise of ensuring six significant digits, use decimal method, otherwise use scientific notation
  %.3g, keep 3 significant digits, use decimal or scientific notation
  
  Note:
   1. All reserved decimal places are truncated and reserved without rounding
   . 2. If it is required to keep more decimal places than the original number, add 0 at the end

print('%f' % 1.11)  # 默认保留6位小数
#输出内容:1.110000
print('%.1f' % 1.11)  # 取1位小数
#输出内容:1.1
print('%e' % 1.11)  # 默认6位小数,用科学计数法
#输出内容:1.110000e+00
print('%.3e' % 1.11)  # 取3位小数,用科学计数法
#输出内容:1.110e+00
print('%g' % 1111.1111)  # 默认6位有效数字
#输出内容:1111.11
print('%.7g' % 1111.1111)  # 取7位有效数字
#输出内容:1111.111
print('%.2g' % 1111.1111)  # 取2位有效数字,自动转换为科学计数法
#输出内容:1.1e+03

4. String formatted output

%s
%10s——right-justified, placeholder 10 digits
%-10s——left-justified, placeholder 10 digits
%.2s——intercept 2-digit string
%10.2s——10-digit placeholder, intercept two Bit string

print('%s' % 'hello world')  # 字符串输出
#输出内容:hello world
print('%20s' % 'hello world')  # 右对齐,取20位,不够则补位
#输出内容:         hello world
print('%-20s' % 'hello world')  # 左对齐,取20位,不够则补位
#输出内容:hello world
print('%.2s' % 'hello world')  # 取2位
#输出内容:he
print('%10.2s' % 'hello world')  # 右对齐,取2位
#输出内容:        he
print('%-10.2s' % 'hello world')  # 左对齐,取2位
#输出内容:he

5. Induction of format characters and escape characters

(1) Format characters

Format character Instructions
%s The string is displayed using str()
%r Display of string (repr())
%c Single character
%b Binary integer
%d Decimal integer
%i Integer
%The Octal integer
%x Hexadecimal integer
%e Index (base write e)
%E Index (base write E
%f,%F Floating point
%g Exponent (e) or floating point number (according to display length)
%G Exponent (E) or floating point number (according to display length)
%% character%

Note: Regarding the difference between %d and %i, I have also consulted many related documents. Some say that there is no difference, some say that %d is read as a decimal integer, and %i is read as an integer. Personally, I still prefer the latter The author's (however my stomach growls again), the author does not have a good way to prove it in the short term, but I will record this problem (return to study after eating), if you guys can solve this problem, please comment and point out ,Greatful!

(2) Escape character

Insert picture description here
  At the end of this article, if there is any content error or improper quotation of the information, you are welcome to criticize and correct (you also want to be merciful, do not like it).

Write at the end

  This is the author's first article in CSDN. It took a full day from collecting references to sorting out ideas and finally writing (because I have learned the basic grammar of python so far, so I did not count Learning time), but when I entered the blog and started writing, I found a lot of layouts, and I didn’t know how to typesetting. It took a long time to learn these things (dig a hole here, I have time to write an article about Xiaobai getting started with CSDN Tutorial for blog writing). In short, the road is long and long, I will search up and down. Learning is endless, let's work hard together! If you have any questions or errors in this article, you are welcome to point it out in the comment area~~
  Write to yourself: Strive for one update every two days, come on!

Four, quoted from

1.中国MOOC Python编程基础(河北软件职业技术学院)
2.菜鸟教程python部分
3.CSDN博客:(作者:TheGkeone)https://blog.csdn.net/sinat_28576553/article/details/81154912
4.百度经验:https://jingyan.baidu.com/article/22a299b5c1b2a99e19376a9d.html
5.博客园:(作者:RuiWo)https://www.cnblogs.com/qinchao0317/p/10699717.html
6.CSDN博客:(作者:站在风口)https://blog.csdn.net/abby1559/article/details/79960249

Guess you like

Origin blog.csdn.net/weixin_44578172/article/details/109272033
Recommended