[Basic knowledge of python] 0.print() function

Preface

Python is a tool that can help you realize your needs. It is more like a master key. It is you who decides which door to open with it.

"A journey of a thousand miles begins with a single step." No matter where the destination is, "Python Basics Class" is the first milestone on our journey!

Basic Python grammar knowledge is like "internal strength". Only deep "internal strength" can better understand and master various moves.

At this time, I remembered Nietzsche's words in "Thus Spoke Zarathustra": "In fact, people are like trees. The more they yearn for the sunshine at high places, the more their roots will reach downwards." Deep underground...".

Maybe, during the learning process, you won't be able to type out particularly cool code at once, but you will continue to improve in the process, and that day will come as scheduled. "Diligence in study is like a seedling that rises in spring. You don't see its growth, but it grows with each passing day."

In the programming world, there is a very famous saying, "Talk is cheap, show me the code." - Talk is useless, show me the code.

I hope you can write more and practice more during the learning process, practice makes perfect!

let's start!

print() function

Congratulations, you have entered the new world of python. Let us use print() to start the first greeting to python! The usage of the print() function is as follows: alone - without quotes, with single quotes, with double quotes, with triple quotes, let's see each one one by one!

No quotes

Note that before formally typing the code, you must switch to English input mode and ensure that the brackets of the print() function use [English brackets], otherwise an error will be reported. [Tips for switching English input: For Mac systems, please press control+spacebar to switch between Chinese and English input, for Windows systems, please press ctrl+shift keys to switch between Chinese and English input]

print(520)

operation result:

520

I have prepared an easter egg for you below. You can copy it directly to your local computer and run it to see the results:

import time
print ('在'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+',我写了人生中第一行Python代码\n它的内容虽然简单,不过是平凡的一句print(520)\n但我知道:我的编程之路,将从最简单的520开始\n在我点击运行的同时,一切在这一刻开始变得不同\n以下,是这行代码的运算结果:' )
print(520)
print(520)
print(520)

operation result:

2023-06-05 16:19:50,我写了人生中第一行Python代码
它的内容虽然简单,不过是平凡的一句print(520)
但我知道:我的编程之路,将从最简单的520开始
在我点击运行的同时,一切在这一刻开始变得不同
以下,是这行代码的运算结果:
520
520
520

Everything starts to change at this moment, because you have successfully written the first line of Python code in your life!

You can achieve the "first experience" of interacting with the computer without the help of the print() function. This is also the first Python syntax knowledge point we are about to unlock.

Just now, although you just entered a simple print, behind the scenes, this Python code did some things like this for you:

(0) We issue an instruction to the computer: "Print '520'"; (1) Python compiles this line of code into machine language that the computer can understand; (2) The computer performs corresponding execution; (3) Finally, print The results are before us.

This is how we successfully communicate with computers through the tool Python.

Insert image description here
Next, you are about to enter the world of "Spirited Away" and further learn how to use the print() function in the story. (Tip: Even if you have not watched "Spirited Away", it will not affect your understanding of the following code knowledge.)

Chihiro and her parents strayed into a world where ghosts and gods rested. In order to save her parents who were turned into pigs due to gluttony, Chihiro needed to work for Granny Yu in this world and sign her name on the prostitution contract.

In the magical world of Python, if we want the computer to help write Qianxun's name, how should we use the print() function to issue instructions to the computer?

print('千寻')

Observe the structure of the above line of code, hit the Enter key again, copy the above line of code into the code box, click Run, and see what results will appear.

operation result:

千寻

Look, does Qianxun’s name appear on the screen? This is the main function of the print() function: print content.

Here, printing means: letting the computer display the results of the instructions you give it on the terminal on the screen.

Usage of single quotes

At this point, you have personally used the print() function twice. Let's take a look, what's the difference between the print() function statements you wrote twice?

print(520)

print('千寻')

Obviously, you will find that there print('千寻')is an extra pair of single quotes.

So the question comes again: What is this single quote used for? Why do I need to add quotation marks when printing text?

This is because computers have a special brain circuit: they can only understand numbers, but not text. Because numbers and mathematical operations are standardized and have a fixed format, but words can be ever-changing.

If you ask the computer directly print(千寻), it will look confused and report an error loudly: "What do these two words mean? You haven't clearly defined them. You don't understand..."

Insert image description here
This is the usage of quotation marks in the print() function: when there are quotation marks within the brackets, it is equivalent to telling the computer that you do not need to perform extra operations, and you will print whatever I input.

Insert image description here

Usage of double quotes

Not only can you use single quotes, but you can also use double quotes within the print() function. There is no difference in the effect of the two, and both allow you to print a line of text.

Sometimes, single quotes and double quotes may appear at the same time within parentheses, for example print("Let's play").

In this case, you need to pay attention to clearly distinguish which quotation marks belong to the print() function structure and which quotation marks belong to the content you want the computer to print. Don't "mix and match" them.

Having said that, you will understand after running the code. Click Run directly in the code box below to observe the running results. (Before clicking Run, think about which quotation mark belongs to the print() function structure in the third print() function)

# 括号内是单引号的情况。
print('一起玩吧')

# 括号内是双引号的情况。
print("一起玩吧")

# 括号内单双引号同时存在的情况。
print("Let's play")

operation result:

一起玩吧
一起玩吧
Let's play

We observe the above code and find that there are some more statements with "#". What is it?

In fact, in python, "#" is often used as a single-line comment symbol to explain a single line of code. For example, "# when there are single quotes in brackets" is used to explain the code "print('Let's play together')". Any data after the # sign will not be output while the code is running.

Back to the print() function, in print("Let's play"), the quotation marks that are not printed belong to the print() function structure.

However, in the print() function, the content in quotation marks does not necessarily have to be text, it can also be English and numbers.

Accordingly, when there are no quotation marks within the brackets, we should put content inside the brackets that the computer can "understand", such as numbers or mathematical operations.

At this time, the print function will let the computer try to "read" the content in the brackets and print the final result.

Therefore, when the computer understands the data numbers, it prints the data. After understanding the numerical operations, the operation results are printed.

Otherwise, let's guess what the computer will output in the terminal if we enter the following code in the code box?print(1+1)

Is it 1+1 or 2?
The correct answer is 2
! But why is the printed result 2, not 1+1?

Here, the computer does not print "1+1" as it is, because print(1+1) is a mathematical operation that the computer can directly understand, so it will directly print out the final operation result: "2". This is how the computer “understands the content.”

Regarding the knowledge related to "operation", we will further explain it tomorrow when we explain data types. Now, you just need to understand the print() function and the difference between its usage with and without quotes.

At this point, the knowledge related to the print() function is finished.

Next, let’s try to use the print() function to print out “Qianxun’s Deed of Prosecution”.

In order to let Qianxun work for her, Yubaba drew up an anti-human "blood and sweat clause":

我愿意留在汤婆婆的澡堂里工作两年,如果我违背工作内容的话,将在这个世界变成一头猪。

So, how to display this contract in Python? Please print out this contract in the code box below (note: use the print() function, and the text part can directly copy the above content).

Reference answer:

print('我愿意留在汤婆婆的澡堂里工作两年,如果我违背工作内容的话,将在这个世界变成一头猪。')

I believe you have successfully printed out Qianxun's contract (this also means that our little Qianxun will have to start working as a working girl...).

Usage of triple quotation marks

But, the demanding Tang Granny thinks that the layout of the Deed of Surrender is not good enough. I hope you can make the text of the Deed of Surrender appear in a new line after each comma, and print out the effect of "automatic line wrapping".

The answer is: use triple quotes ''' (enter three single quotes consecutively) inside print to achieve cross-line output.

Hehe, I didn’t expect that in addition to single quotes and double quotes, there are also triple quotes in print(). Directly run the following code to see if you can achieve the effect Yubaba wants this time.

print('''我愿意留在汤婆婆的澡堂里工作两年,
如果我违背工作内容的话,
将在这个世界变成一头猪。
''')

operation result:

print('''我愿意留在汤婆婆的澡堂里工作两年,
如果我违背工作内容的话,
将在这个世界变成一头猪。
''')

Success! You have mastered the method of using triple quotes to wrap lines.

Now we have learned the four situations of the print() function - no quotes, single quotes, double quotes, and triple quotes. Then follow the teacher to review the differences between them and consolidate them.

Insert image description here
Insert image description here
Attention, [High Energy Warning Ahead], next, I am going to tell you about a code bug that 99% of beginners have encountered.

In Python, all correct grammar, including punctuation, is [English] by default. If you accidentally use Chinese punctuation, the computer will not be able to recognize it and will report an error.

In the terminal, the most common symbol error message you can see is [syntaxError: invalid syntax].

Insert image description here
When we are debugging (resolving program errors), we need to subconsciously look for whether we have made such a small but fatal mistake.

End of important reminder. At this moment, you have completed 60% of the progress bar of this level, and the level achievement is just around the corner!

escape character

You have successfully printed Qianxun's deed of betrayal using the print() function.

print('''我愿意留在汤婆婆的澡堂里工作两年,
如果我违背工作内容的话,
将在这个世界变成一头猪。
''')

In fact, there is a second way to achieve line breaks: use the escape character \n, like this:

print('我愿意留在汤婆婆的澡堂里工作两年,\n如果我违背工作内容的话,\n将在这个世界变成一头猪。')

In addition to \n, there are many escape characters. Their characteristics are: backslash + the first letter of the escape function you want to achieve.

For example, line feed \n represents [+newline]; backspace \b represents [+backspace]; carriage return \r represents [+return]. You can follow this method to remember the meaning of escape characters.

I have summarized some commonly used escape characters:

Insert image description here
Don't worry, you don't need to memorize the contents of this picture. Save the picture by taking a screenshot or taking a photo. You can just look at the picture to find it when you need to use escape characters in the future.

Variables and assignments

At this point, you have successfully printed out Qianxun's name and the deed of betrayal. At the same time, Qianxun also became a worker of Yubaba. Gradually, she forgot who she was and lost the information of her "name".

So, in the code world full of information, how should we better store information so that the computer can help you call up the information you want when you need it?

You need to use the power of [variables and assignment] to "collect" the complicated information one by one.

Let’s first take a look at the following line of code:

name='千寻'

This is a common action of "assigning a value to a variable". Here, name is a variable. The meaning of this line of code is to [assign] the two words "Qianxun" to the "name" [variable].

This is like, in order to make it easier for Qianxun to find her name on the computer in the future, we helped her put her name into a small box and put a label called "name" on the box.

Think about it, when we usually pack things, do we put the scattered things into different boxes and mark them? This kind of "storage" action can make the space tidy and make it easier for us to access things.

Insert image description here
In the same way, the computer does the same thing. It puts thousands of data in different "boxes" so that it can store and operate the data conveniently.

This "box" is called a variable in Python, and you can put whatever you want in this "box".

And this process of loading things into the box is called [assignment] in the magical world of code.

Insert image description here
After Chihiro signed the contract, Yubaba tore off the "label" of "name" from the "box" containing her name "Chihiro" and attached it to the "box" containing the name "Qianxian".

At this time, I took out the box with the "label" [name] on it, and the read content changed to "Xiaoqian":

name='小千'

Now, please run the following code and see what the final output of the print function is.

name='千寻'
name='小千'
print(name)

operation result:

小千

Is the result that appears on the terminal [Xiao Qian]? But why? Isn't our first assignment to the variable "name" ['Qianxun']? Why is the printed result the second assignment?

This involves the characteristics of variables: Variables are called variables because the data they store can be changed at will.

As we just said, we can treat a variable as a box. You can put anything in this box, but the box has its maximum capacity and cannot be filled with unlimited things.

But in the world of code, the capacity of the box is very small, only 1. So when you need to put something new in, you have to find a new box.

Insert image description here
In our case above, the first line of code: name='Qianxun' means: put the name Qianxun into the variable "box" of name.

Since the computer executes the code line by line from top to bottom, when the second line of code name='Xiao Qian' is run, the ['Qianxun'] stored in the variable "name" is replaced with [' Xiaoqian'].

Therefore, when we run to the third line of print(name), the result we print out is naturally Xiaoqian.

In fact, not only Qianxun, but also the name is meaningful to each of us. It helps you "position" yourself so that others can easily find you. Therefore, people's names cannot be chosen randomly. Similarly, naming variables also needs to follow certain standards.

Variable naming convention

For the naming of variables, we can follow the following specifications:

Insert image description here
For example, if the information is a name, then the variable can be named name; if the information is a number, then the variable name should be called number.

Many novices are accustomed to naming variables with English letters such as a, b, c, etc. when they first get started. Such a variable name will make it impossible for you to tell what is contained in the variable from a lot of information. This is equivalent to naming your child "Zhang Xiaohong" or "Wang Xiaoming", and you will be drowned in the vast sea of ​​people. .

In addition to variable naming, it is also important to note that in the code world, the assignment symbol = does not mean that the left side equals the right side. It only represents the assignment action: putting the content on the right into the box on the left.

The symbol that represents the equality of the left and right sides is a comparison operator ==. Although they look similar, they represent completely different meanings, so don't get confused. As for the comparison operator ==, you don’t have to worry about its usage. We will meet you again in the next level.

Insert image description here
It’s time to test your learning results. Please use the knowledge you just learned about variables and assignments to do a question: Please assign values ​​to the following three names in sequence, and make sure that the final printout is "Qianxun". (Tip: When using the print() function, the value of a variable is always equal to the last content assigned to it.)

I believe you have already printed out "Chihiro"'s name. The teacher’s answer is this:

name='魔法少女千酱'
name='夏目千千'
name='千寻'

print(name)

Finally, let’s summarize the knowledge points of this level:
Insert image description here
At this point, you may ask: What is the use of these simple codes I learned in this level?

Although the print() function is the simplest statement, in fact, almost any program you will do in the future is inseparable from the support of the print() function.

For example, you can use the print() function to create a cute best friend for yourself, "Artificial Retarded Little Bury". She will jump up to you and naughtyly ask you to guess her age.

Below is a piece of code that has been written. Please [run] directly. Come and play the age-guessing game with Xiaomi!

import random
import time

###提示语部分
print('你好,我是机器人小埋,我们来玩个猜年龄的小游戏吧~(◆◡◆)')
time.sleep(2)

print('''
=============================
   干物妹!うまるちゃんの年齢
=============================
''')
time.sleep(1)


print('小埋的真实年龄在1到10之间哦~')
time.sleep(1)


print('不过,你只有5次机会哦~')
time.sleep(1)


print('下面,请输入小埋的年龄吧:')


#从0至10产生一个随机整数,并赋值给变量age
age = random.randint(1,10)


#设置次数
for guess in range(1,6):
   
   #输入玩家猜测的年龄
    choice=int(input())
    
    #判读玩家输入的年龄是否等于正确的年龄
    if choice<age:
        print('小埋的提示:你猜小了(;´д`)ゞ。。。。')
                
    elif choice>age:
        print('小埋的提示:乃猜大了惹(>﹏<)~~')
            
    else: 
        print('猜了'+str(guess)+'次,你就猜对惹~hiu(^_^A;)~~~')
        break   
                
#判断猜测次数 
if choice  == age:
    print('搜噶~那么小埋下线了~拜拜~( ̄︶ ̄)↗')
    
else:
    print('哎呀~你还是木有猜对啊~但是你只有5次机会诶~怎么办啊~')
    print('那好吧~心软的小埋只好告诉你,我才'+str(age)+'岁哦~(*/ω\*)')

operation result:

你好,我是机器人小埋,我们来玩个猜年龄的小游戏吧~(◆◡◆)

=============================
   干物妹!うまるちゃんの年齢
=============================

小埋的真实年龄在110之间哦~
不过,你只有5次机会哦~
下面,请输入小埋的年龄吧:
4
小埋的提示:你猜小了(;´д`)ゞ。。。。
7
小埋的提示:你猜小了(;´д`)ゞ。。。。
9
小埋的提示:乃猜大了惹(>﹏<)~~
8
猜了4次,你就猜对惹~hiu(^_^A;)~~~
搜噶~那么小埋下线了~拜拜~( ̄︶ ̄)↗

Did you successfully guess Xiaomi's age? In addition to the print() function and variable assignment, this code also uses conditional judgment if statements and input() functions. We will learn these two knowledge points in the second and third levels.

After learning the first half of basic grammar, you can also write a project like this independently and design your own "little bury"! So, don’t underestimate what we learn today, it will be the beginning of our big projects in the future.

In this level, we have mastered command thinking - giving the "print" command to the computer. However, on the road to communicating with computers, our learning has just begun.

After completing the entire Python basic syntax course, you will truly step into the door of Python and master the methods and thinking of using Python to solve problems.

Preview of next pass

In fact, the Python world is just a mirror of the real world, and everything in the Python world can find its counterpart in the real world. So what do the most common numbers and words in the real world look like in the mirror world? How do we use them?

For example, how can we use the data in the mirror world to perform complex scientific calculations, and output the numerical results and explanation language to the screen to display to the user?

Insert image description here
In the next level, we will go deep into the mirror world to explore the details and reveal the secrets of [Mirror World Data].

Insert image description here
Now, I can finally officially inform you: Congratulations on passing your first Python lesson in life!
See you in the next level!

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132688671