[Burning liver update] Chapter 2: Python basic grammar - nanny level, super ten thousand words!

In this chapter, we start to learn the basic syntax of Python, including literals, operators, variables, string formatting, input functions, etc. This chapter is to lay a good foundation for learning the entire Python system, so we must pay attention to it.

Students who are used to watching videos can watch this free tutorial:

https://www.bilibili.com/video/BV1ZK411Q7uX/?vd_source=704fe2a34559a0ef859c3225a1fb1b42&wxfid=o7omF0RELrnx5_fUSp6D59_9ms3Y

For the description of this tutorial, you can read the previous article:

I plan to write a set of basic and practical Python graphic tutorials - this is the first one

Ok, next is the content of this chapter.

Literal

learning target:

  • Grasp the meaning of the literal

  • Learn about common literal types

  • Complete various literal output based on the print statement  

What is a literal

In the code, the fixed value that is written down is called a literal. In Python, which values ​​can be written out? Literals are divided into the following 6 types, see the table below:

Don't panic when you see so many types. At the beginning, let's focus on mastering the number types. In the introductory stage, we mainly learn the three types of integers, floating-point numbers, and strings in the number types.

Integers: Integers actually have the same meaning as integers in our mathematics, such as 10 or -10.

Floating-point numbers: That is, decimals in mathematics, such as 13.14, or -13.14.

String: Refers to any number of characters such as Chinese, English, numbers, and symbols. For example:

  • "Dark Horse Programmer"

  • "Learn Python to be a dark horse"

  • "!@#$%^&"

  • "The stock code of Chuanzhi Education is: 003032"

Note that in Python, strings need to be surrounded by double quotes, or anything surrounded by double quotes is called a string. After understanding the meaning of integers, floating-point numbers, and strings, let's look at how these types are represented in code. For integers and floating-point numbers, the writing in the program is exactly the same as in real life. The difference is the string. When writing a string in the program, you need to add double quotation marks.

How to write literals in code

How to express the types we are going to learn in code?

type

How to write in the program

illustrate

integer

666,-88

Consistent with the writing in reality

float (decimal)

13.14,-5.21

Consistent with the writing in reality

string (text)

"Dark Horse Programmer"

The program needs to add double quotes to represent the string

Note: The string must use English double quotation marks.

Now I want these 3 literals to be displayed on the screen, how should I do it? Did we use a print statement when we were learning Hello World before? Next, we use print to output these three data types. When printing strings, we need to add an English double quotation mark:

 
 
 
 

print(666)
print(13.14)
print("Dark Horse Programmer")

Then click the small green arrow in the upper right corner of Pycharm, run it and the result will come out:

 
 
 
 

666
13.14
Dark Horse Programmer

note

learning target:

We need students to understand the role of comments, and to be able to use single-line comments and multi-line comments. 

The role of comments

First, let's take a look at the code in the previous section:

 
 
 
 

666
13.14
"Dark Horse Programmer
print(666)
print(13.14)
print("Dark Horse Programmer")

Code without comments    

 
 
 
 

"""
Demo:
- How to write various literals
- Output various literals through print statements
"""
# Write an integer literal
666
# Write a floating point literal
13.14
# Write a string literal
"Dark Horse Programmer "

# Output various literal quantities through the orint statement
print(666)
print(13.14)
print("Dark Horse Programmer")

code using comments

By observing, students should be able to find that the code with comments seems to be easier to understand, and this is also the role of comments. So what are annotations?

Comment: The text explaining the program code in the program code.

Function: Comments are not programs and cannot be executed. They just explain the program code so that others can understand the function of the program code, which can greatly enhance the readability of the program.

Classification of comments

Single-line comments: start with #, and all the text on the right of # is used as an explanation, not the actual program to be executed, and serves as an auxiliary explanation.

 
 
 
 

# I am a single-line comment
print ("Hello World")

Note that it is generally recommended to separate the # sign and the comment content with a space.

A specification is a suggested requirement, not a mandatory requirement. Although it will not affect the operation of the program if you do not comply, we recommend that students abide by the Python specification. After all, the official and big factory codes are abiding by the specification, which will also make our code more advanced. This is how single-line comments are used. Multi-line comment: Use a pair of three double quotation marks ( ) to explain the function and use of a piece of code.

 
 
 
 

"""
I am a multi-line comment.
Poem title: Compassionate farmers
Author: Li Shen
"""

print("The noon of the day of hoeing")
print("Sweat dripping down the soil")
print("Who knows the Chinese food")
print ("Everything is hard work")

As the above code shows, we found that they also support line breaks. This is how multi-line comments are used. 

variable

learning target:

  • Understand the role and characteristics of variables

  • And master the definition of variables

Variable: An abstract concept that can store calculation results or represent values ​​when the program is running.

Simply put, variables are used to record data when the program is running.

We can imagine a variable as a box for recording data, such as recording a number 100, or a string "Hello".

So how are variables defined? The format is as follows:

Simply put, a variable is a "box" for recording data, which can store data such as the integer 100 or the string "Hello". The variable definition format is very simple, just write the variable name equal to the value of the variable in the code. In Python, many variables can be defined, and each variable has its own name (i.e. variable name) and stored value (i.e. variable value). The equal sign means assignment, and the value on the right side of the equal sign is assigned to the variable on the left. 

After understanding the variable and its definition format, now we operate it in Pycharm. We want to record the balance of the wallet through a variable, which can be defined by a variable:

 
 
 
 

money = 50

Whether this variable can really store the data of 50, how to verify it, we can output its content through the print statement, we can write print(), and add a comma, a character can be added before or after String output at the same time:

 
 
 
 

print('wallet:', money)

There are many uses of the print statement. The print statement can output a lot of data, so we can separate each piece of data with a comma. For example, my statement can output the string of "wallet", and at the same time, it can also output the content of the following variables to us, so to output multiple copies of data, you can separate them with commas. The result of the operation is:

 
 
 
 

Wallet: 50

In addition to the basic feature of recording data, are there other features of variables? The answer is of course yes.

variable characteristics

There is a word "change" in the name of the variable, but it does not mean that the quantity can be changed, so what does it mean?

Let me give you an example: suppose I bought an ice cream and spent 10 yuan. Does that mean that 10 yuan should be subtracted from the balance of the wallet? Can we use mathematical calculations to subtract 10 yuan from 50 yuan?

So how to write mathematical calculations in Python is actually very simple, just use 50-10 directly. But writing like this is not advanced at all, it is no different from writing a literal value of 40 directly. Because our own balance has changed, and 10 has been subtracted, is the balance recorded in the variable money? In fact, it can be written as money-10, so it looks more advanced.

I took out 50 yuan from my wallet to buy an ice cream and gave it to the boss. After the boss deducted 10 yuan, should he give me the rest of the money? Then how should this action be done in our code?

The variable value is: money-10

The variable name is equal to the variable value, do we need to define the second variable? No need, can we put the new content back into the money variable itself? Did you find that the content recorded in our variable has changed?

Then, let's verify it through the print statement:

 
 
 
 

# I bought an ice cream and spent 10 yuan
money = money - 10
print("I bought an ice cream and spent 10 yuan, and there is still left:", money, "yuan")

This way our variables are defined.

 
 
 
 

# Assume, every hour, output the balance of the wallet
print("It is 1 pm now, the remaining balance in the wallet:", money)
print("It is 2 pm now, the remaining balance in the wallet: ", money)
print(" It is 3 pm now, remaining wallet balance: ", money)
print("It is 4 pm, remaining wallet balance: ", money)

Here is a little trick. When the cursor is positioned on the print statement of the first line, you can directly copy multiple lines by directly pressing ctrl+D.

type of data

learning target:

Master the type of data viewed using the type() statement

Understand the concept that variables are untyped and data is typed

When learning literals, we learned that data has types. Currently in the introductory stage, we mainly come into contact with the following three types of data types:

type

describe

illustrate

string

string type

Data enclosed in quotes are all strings

int

integer (signed)

Number type, storing integers such as -1, 10, 0, etc.

float

float (signed)

Number type, store decimals such as -3.14, 6.66

The three English words string, int, and float are the standard names of types.

type() statement

So, here comes the question, how to verify the type of data? We can get the type of data through the type() statement, the syntax is as follows:

 
 
 
 

type (data of the type being viewed)

  1. 1. In the print statement, directly output the type information: (str is the abbreviation of string)    

  2. For example, write a string literal, or an integer literal, or a floating-point literal in type, and then output them as a whole through the print statement, and you can get the result of the type information . 

 
 
 
 

string_type=type("Dark Horse Programmer")
int_type = type(666)
float_type = type(11.345)
print(string_type)
print(int_type)
print(float_type)

output:
<class 'str'>
<class int>
<class ' float'>

In this result, we don't care about the meaning of the word class for the time being. We only need to care about the type information enclosed in single quotation marks. You may also think, I know what you just said about int and float. What is this str? In fact, str is an abbreviation of what we call string, so pay attention to this. 

2. Use variables to store the result (return value) of type():   

In addition to this method, we can also use variables to store the results of the type statement. The type statement will provide us with a return value after execution is completed, which is actually the result. For this result, we can use variables to store it. 

 
 
 
 

string_type=type("Dark Horse Programmer")
int_type = type(666)
float_type = type(11.345)

print(string_type)
print(int_type)
print(float_type)


output result:
# <class 'str'>
# <class int>
# <class 'float'>

The two ways we check are the type of <literal quantity>, can we check the data type stored in the variable? Of course: yes.

 
 
 
 

name="Dark Horse Programmer"
name_type = type(name)
print(name_type)

# <class str>

Do variables have types?

We can output the type through type (variable). Is this the type of variable or the type of data? What is being viewed is: the type of data stored by the variable. Because the variable has no type, but the data it stores has.

Okay, so in order to understand this sentence, let's look at an example: Let's assume there is a box with footballs in it, we can call it a football box; basketballs in the box, we can call it a basketball box. So, let me ask the students, when football and basketball are put in the box, will the box become football or basketball? Obviously not, right? Then our variable is the same, our variable stores string data, so will the variable become a string? Certainly not.

Different ways of defining the string type

Strings can be defined in 3 different ways:

  • Double quotes define the method "string"

  • single quote definition method 'string'

  • Triple quote definition method """string"""

The triple quotation mark definition method means that within the range of a bunch of three double quotation marks, all are strings, as follows:

 
 
 
 

text = """
In the enclosing circle of three quotation marks,
all are
strings, and
the writing is completed
"""

It should be noted that the inclusive range is: from the beginning of three quotation marks to the end of the next three quotation marks.

data type conversion

learning target:

  • Master how to convert between strings, integers, and floating point numbers

  • Know the dos and don'ts of conversion

Why do type conversions need to be done? Data types can be converted to each other in specific scenarios, such as strings to numbers, numbers to strings, etc. So, why do we convert them? Data type conversion will be a function we will often use in the future. like:

  • The number read from the file, the default is a string, we need to convert it into a number type

  • For the input() statement to be learned later, the default result is a string, and if a number is needed, it needs to be converted

  • Convert numbers to strings for writing out to external systems

There are many uses, so let's learn how to convert it.

We are currently exposed to 3 types of data types, so we will only explain how to convert between these 3 types.

statement (function)

illustrate

int(x)

convert x to an integer

float(x)

Convert x to a float

str(x)

convert the object x to a string

These three sentences are also relatively simple to understand. Int(x) means that if you put x in, he will convert x into an integer for you. Because we know that int represents an integer type! Putting an x ​​in the same float means converting x to a floating point number, and the same str below means converting x to a string.

But there is one thing we need to pay attention to. These three statements, like the type statement we learned earlier, all have results. For these statements with results, we can directly use print() to output their results .

Students can take the following code to do some exercises

 
 
 
 

#Convert number type to string
num_str = str(11)
print(type(num_str), num_str)

float_str = str(11.345)
print(type(float_str), float_str)

#Convert string to number
num = int(" 11")
print(type(num), num)

num2 = float("11.345")
print(type(num2), num2)

# Integer to floating point number
float_num = float(11)
print(type(float_num), float_num)

# Convert floating-point number to integer
int_num = int(11.345)
print(type(int_num), int_num)

Type conversion considerations

Type conversion is not a panacea. After all, twisted melons will not be sweet. We need to pay attention to:

  1. Any type can be converted to a string by str()

  2. The string must really be a number before the string can be converted to a number as follows:

 
 
 
 

v_str = "I am not a number"
num = int(v_str)

An error will appear.

 
 
 
 

Traceback (most recent call last):
File "C:\Users\itcast\PycharmProjects\pythonProject1\python book exercises\2.3 variables.py", line 24, in <module>
num = int(v_str)
ValueError: invalid literal for int () with base 10: 'I am not a number'

identifier

learning target:

  • understand what is an identifier

  • Master the naming rules of identifiers

  • Master variable naming conventions

In a Python program, we can give names to many things, such as:

  • variable name

  • method name

  • class name, etc.

These names, we collectively call them identifiers, are used to identify content.

Therefore, identifiers are a series of names used by users when programming to name variables, classes, methods, etc.

Since a name is to be named, there will be corresponding restrictions

Identifier Naming Rules

In Python, there are three main types of identifier naming rules:

  • Content limited

  • Case Sensitive

  • Keyword not allowed

Next, let's look at them one by one. First of all,

Identifier Naming Rules - Content Qualification

In identifier naming, only allowed to appear:

  • English

  • Chinese

  • number

  • underscore (_)

these four elements.

Anything else is not allowed.

In addition, there are some other things to pay attention to. For example, first, we do not recommend using Chinese. Although Python supports naming Chinese identifiers, the current support is not perfect. If we use Chinese, there may be some hidden Second, in the industry, most programmers use English to name identifiers, but rarely use Chinese, so in order to cater to the habits of the industry, we also do not recommend using Chinese.

Another point to note is that numbers cannot be used at the beginning. This is a rigid rule.

Let's look at some examples

① abc, abc123, _abc, hello (reasonable)

② 123abc, @abc, abc-123 (unreasonable)

Identifier Naming Rules - Case Sensitive

Let's look at the following code:

 
 
 
 

Andy = 'Andy1'
andy = 'Andy2'
print(Andy)
print(andy)

The output result is:

 
 
 
 

Andy 1
Andy 2

The uppercase and lowercase of the letter a are completely distinguishable.

Third rule: no keywords

What is a keyword?

Let's recall, in daily life, will there be some key phone numbers, such as 110120122119. Our mobile phone number cannot occupy these key numbers. Also in python, there are also a series of words called keywords.

Keywords have a specific purpose in Python and we cannot use them as identifiers.

Here are the 33 keywords:

 
 
 
 

False
True
None
and
as
assert
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

There is definitely no need to memorize so many keywords, because we say that these keywords will have specific uses, and each use is a function.

In the follow-up code, we will come into contact with these keywords one after another. If you write too much code, you will naturally memorize them all, so you don’t need to memorize them deliberately.

There is another key point. We just said that identifiers are case-sensitive, so this rule also applies to our keywords.

Then you can see that there are 3 keywords in our keywords, all of which are capitalized, and the rest are all lowercase, so for these keywords, if our capitalization is different from his, Then it is not counted as occupying keywords, but if your case is exactly the same as his, then you are equivalent to occupying keywords. We should pay attention to this point, keywords are also case-sensitive.

Through the following practice code, we can consolidate what we have just learned

 
 
 
 

# Rule 1: The content is limited, and it can only be used: Chinese, English, numbers, underscores, note: it cannot start with a number
# Wrong code demonstration: 1_name = "Zhang San"
# Wrong code demonstration: name_! = "Zhang San "
name_ = "Zhang San"
_name = "Zhang San"
name_1 = "Zhang San"

# Rule 2: case sensitive
Itheima = "Dark Horse Programmer"
itheima = 666
print(Itheima)
print(itheima)

# Rule 3: Not available Keyword
# Wrong example, keyword used: class = 1
# Wrong example, keyword used: def = 1
Class = 1

Variable naming convention

We just finished learning the naming rules of identifiers, let's learn the naming conventions of identifiers. As we said earlier, the specification is a suggested requirement, not mandatory, but if you don't follow it, the specification will make our code look less advanced, so what are the specifications for identifiers?

Our identifiers can have variable names, class names, and method names, so different identifiers have different specifications. Since we haven't learned classes and methods yet, so we only learn the naming conventions of variables. There are 3 naming conventions for variables

  • The first to know the name

  • Second underscore nomenclature

  • The third is called English letters all lowercase

The naming of our variables must achieve the first point, and it must be clear, that is, you can know what it means when you see the name.

Define two variables:

 
 
 
 

a = "Zhang San"
b= 11

Although the program works correctly, it doesn't look very advanced, when we replace the variables with:

 
 
 
 

name = "Zhang San"
age = 11

There is the effect of seeing the name and knowing the mind.

The second point of naming our variables is to be concise: try to reduce the length of the name while ensuring "clearness"

 
 
 
 

a_person_name = "Zhang San"

It's too long and unnecessary, we can just call it name.

 
 
 
 

name = "Zhang San"

Combining variable names with multiple words should be separated by underscores, which looks very refreshing.

 
 
 
 

firstnumber = 1
studentnickname = "Xiao Ming"

first_number = 1
student_nickname = "Xiao Ming"

The English letters in the named variable should be all lowercase. When we name it, whenever we use English letters, we don’t need to capitalize them. Just put all the English letters in the variable in lowercase.

 
 
 
 

name = "Zhang San"
age = 11

operator

learning target:

Learn about common

  • arithmetic (mathematical) operators

assignment operator

So first let's look at what arithmetic operators are? The arithmetic operators are actually used to do mathematical operations in simple terms, such as addition, subtraction, multiplication, division, rounding, division, remainder, and subnumbers, which are common 7 types. Then these 7 operators are actually exactly the same as the concept of 7 mathematical operations in our mathematical calculations

operator

describe

example

+

add

Add a + b to two objects and output the result 30

-

reduce

Get a negative number or a number minus another number a - b and output the result -10

*

take

Multiply two numbers or return a string a * b that is repeated several times and output the result 200

/

remove

b / a output result 2

//

Divisible

Returns the integer part of the quotient 9//2 outputs 4 , 9.0//2.0 outputs 4.0

%

Take the remainder

Returns the remainder of the division b % a outputs 0

**

index

a**b is 10 to the 20th power, and the output result is 100000000000000000000

Demonstration of Arithmetic Operators

Addition, subtraction, multiplication, division and squaring, we have used it before. Now bring: integer division and remainder, let's try it together.

 
 
 
 

print("1+1 result is: %d"%(1+1))
print("2-1 result is: %d"%(2-1))
print("1*3 result is:%d" %(1*3))
print("9/3 result is: %d"%(9/3))
print("9//2(9 divisible by 2) result is: %d"%(9//2 ))
print("9%%2(the result of 9 remaining 2 is) the result is: %d"%(9%2))
print("2 to the 6th power is: the result is:%d"%(2* *6))

output result

 
 
 
 

# 1+1 result is: 2
# 2-1 result is: 1
# 1*3 result is: 3
# 9/3 result is: 3
# 9//2(9 divisible by 2) result is: 4
# 9%2 (The result of 9 remaining 2 is) The result is: 1
# 2 to the 6th power is: The result is: 64

assignment operator

Then the operators in Python, in addition to arithmetic operators, there are also assignment operators. For example, in Python, assignment operators can be divided into two categories: the first category is a standard assignment operator, which is an equal sign, and its meaning is to assign the result on the right side of the equal sign to the variable on the left. When defining a variable, the assignment operator is essentially already used. 

operator

describe

example

=

assignment operator

Assign the result on the right side of the = sign to the variable on the left, such as num = 1 + 2 * 3, and the value of the result num is 7

compound assignment operator

In addition to the standard assignment operators, we have compound assignment operators such as addition, etc., subtraction, etc., multiplication, etc., division, etc., remainder, etc., square, etc., and integer division. These operators mean to perform an operation on the variable itself, and then assign the result to the variable itself. As shown in the following table:

operator

describe

example

+=

Additive assignment operator

c += a is equivalent to c = c + a

-=

subtraction assignment operator

c -= a is equivalent to c = c - a

*=

multiplication assignment operator

c *= a is equivalent to c = c * a

/=

division assignment operator

c /= a is equivalent to c = c / a

%=

modulo assignment operator

c %= a is equivalent to c = c % a

**=

power assignment operator

c = a is equivalent to c = c a

//=

integer division assignment operator

c //= a is equivalent to c = c // a

Next, let's demonstrate it through code:

 
 
 
 

# 见值电视符
num = 1 + 2 * 3
# 投稿赋值电视符
# +=
num = 1
num += 1 # num = num + 1
print("num += 1: ", num)
num -= 1
print( "num -= 1: ", num)
num *= 4
print("num *= 4: ", num)
num /= 2
print("num /= 2: ", num)
num = 3
num %= 2
print ("num %= 2: ", num)

num **= 2
print("num **=2: ", num)

num = 9
num //= 2
print("num //= 2:", num)

result:

 
 
 
 

1 + 1 = 2
2 - 1 = 1
3 * 3 = 9
4 / 2 = 2.0
11 // 2 = 5
9 % 2 = 1
2 ** 2 = 4

string expansion

Three ways to define strings

We have learned how to define strings, but what we defined at that time was the content surrounded by double quotes, which we called strings. This definition method is called the definition method of double quotation marks. Strictly speaking, strings have multiple definitions in Python:

1. Single quote definition method: name = "Dark Horse Programmer"

2. Double quotation mark definition method: name = "Dark Horse Programmer"

3. Three quotation marks definition method: name = """Dark Horse Programmer"""

The three-quote definition method, like the writing method of multi-line comments, also supports line break operations.

  • Use a variable to receive it, it's just a string

  • Receive it without using a variable, it can be used as a multi-line comment

Let's demonstrate it in code:

 
 
 
 

# Single quotation mark definition method, use single quotation marks to surround
name = 'Dark Horse Programmer'
print(type(name))

# Double quotation mark definition method
name = "Dark Horse Programmer"
print(type(name))

# Triple quotation mark definition method, The writing method is the same as multi-line comments
name = """
I am
a dark horse
programmer
"""
print(type(name))

result:

 
 
 
 

<class 'str'>
<class 'str'>
<class 'str'>

Thinking: If the string I want to define itself contains: single quotes, double quotes themselves? how to write 1234567890

  • Single quotation mark definition method, can contain double quotation marks

  • Double quotes definition method, can contain single quotes

  • You can use the escape character (\) to deactivate the quotation marks and turn them into ordinary strings

  • An escape character is a special character used in computer programming that changes how the following characters are interpreted. 

 
 
 
 

# Include double quotes in the string
name = '"Dark Horse Programmer"'
print(name)

# Include single quotes in the string
name = "'Dark Horse Programmer'"
print(name)

# Use the escape character \ to dequote Utility
name = "\"Dark Horse Programmer\""
print(name)

name = '\'Dark Horse Programmer\''
print(name)

result:

 
 
 
 

"Dark Horse Programmer"
'Dark Horse Programmer'
"Dark Horse Programmer"
'Dark Horse Programmer'

string concatenation

If we have two string (text) literals, we can concatenate them into a string, which can be done by + sign, such as:

 
 
 
 

print("Learn IT to be a dark horse" + "monthly salary over 10,000")

Output result:

 
 
 
 

Learn IT to come to the black horse with a monthly salary of over 10,000

However, under normal circumstances, the simple splicing of two string literals seems dull. Generally, splicing is used between literals and variables or between variables, such as:

 
 
 
 

name="Dark Horse Programmer"
print("My name is: "+name+", I can teach you IT skills")

Output result:

 
 
 
 

My name is: Dark Horse Programmer, I can teach you IT skills

Now that strings and variables are concatenated, let's complete a small requirement:

Define 2 variables:

  • name, the content is "Dark Horse Programmer"

  • address, the content is "Building Material City East Road No. 9"

It is required to write a program to output through the print statement and string splicing:

 
 
 
 

"I am: Dark Horse Programmer, my address is: Courtyard No. 9, Jiancaicheng East Road"
 

 
 
 
 

name="Dark Horse Programmer"
address="No. 9 Building Material City East Road"
print("I am: "+name+", my address is: "+address)

Output result:

 
 
 
 

I am: Dark Horse Programmer, my address is: Courtyard No. 9, Jiancaicheng East Road

Since splicing with string variables can be completed, can it be spliced ​​with other variable types such as numeric types? Let's try it.

 
 
 
 

name="Chuanzhi Podcast"
set_up_year =2006
print("I am: "+name+", I was founded in: "+set_up_year)

It can be seen that variables of different types cannot be spliced, and the output result is:

 
 
 
 

Traceback (most recent call last):
File "C:\Users\itcast\PycharmProjects\pythonProject1\python book exercises\2.3 variables.py", line 1512, in <module>
print("I am: "+name+", I Set in: "+set_up_year)
TypeError: can only concatenate str (not "int") to str

Here it prompts a type error called type error, what is this? This actually means to tell us that there is no way for our strings to be spliced ​​with plus signs and integers. In fact, it is not just integers, including floating point numbers or some other types. There is no way for us to directly use plus signs and strings. The splicing is complete, so we need to pay attention to this point. 

string formatting

learning target:

  • Master the concatenation of strings in the form of placeholders (string formatting)

We will find that this concatenated string is not easy to use for the following reasons:

1. There are too many variables, it is too troublesome to stitch together

2. Strings cannot be concatenated with numbers or other types.

print("I am "+name+", my gender is: "+sex+", I live in: "+address+", my hobby is: "+hobby)

So, is there any other way that is convenient and supports splicing other types? This method is the formatting of the string.

We can complete the quick splicing of strings and variables through the following syntax. where "%s"

  • % means: I want to occupy a place

  • s means: turn the variable into a string and put it in the placeholder

So, the overall meaning is: I will occupy a place first, and a variable will come later, and I will turn it into a string and put it in the place:

 
 
 
 

name="Dark Horse Programmer"
message="Learn IT and come to %s" %name
print(message)

Output result:

 
 
 
 

Learn IT and come to dark horse programmers

What about numeric types? Can I take a seat? That must work, let's try the following code:

 
 
 
 

class_num = 57
avg_salary = 16781
message="Python big data subject, Beijing %s period, average salary after graduation: %s" %(class_num,avg_salary)
print(message)

Output result:

 
 
 
 

Python big data subject, Beijing 57th period, graduation average salary: 16781

Here we have a question, how can numbers also use %s to take place? The s in %s means to turn the variable into a string and put it in the placeholder. Why can’t you match the type? In fact, through the demonstration of the code just now, we found that it is really possible. Here it converts the number into a string, that is, the number 57 or the number 16781 becomes the string 57 or the string 16781 and puts it where it should occupy. 

The digital type is too useless, and it should be converted into a string splicing. Is there a decent way to splice the numbers in as they are? Python actually supports a lot of data types, the most commonly used are the following three types:

formatting symbols

convert

%s

Convert the content into a string and put it in the placeholder

%d

Convert the content to an integer and place it in the placeholder

%f

Convert the content to a float and place it in the placeholder

The following code completes the placeholders for three different types of variables: strings, integers, and floating-point numbers:

 
 
 
 

name="传智播客"
set_up_year = 2006
stock_price = 19.99
message="我是:%s,我成立于:%d,我今天的股价是:%f"%(name,set_up_year,stock_price)
print(message)

输出结果:

 
 
 
 

我是:传智播客,我成立于:2006,我今天的股价是:19.990000

格式化的精度控制

学习目标:

  • 掌握格式化字符串的过程中做数字的精度控制

字符串格式化

上一节的代码,完成字符串、整数、浮点数,三种不同类型变量的占位,细心的同学可能会发现:浮点数19.99,变成了19.990000输出,这里我们就要讲解一下,字符串格式化之“数字精度控制”。

字符串格式化 - 数字精度控制

我们可以使用辅助符号"m.n"来控制数据的宽度和精度

  • m,控制宽度,要求是数字(很少使用),设置的宽度小于数字自身,不生效

  • .n,控制小数点精度,要求是数字,会进行小数的四舍五入

示例:

  • %5d:表示将整数的宽度控制在5位,如数字11,被设置为5d,就会变成:[空格][空格][空格]11,用三个空格补足宽度。

  • %5.2f:表示将宽度控制为5,将小数点精度设置为2

小数点和小数部分也算入宽度计算。如,对11.345设置了%7.2f 后,结果是:[空格][空格]11.35。2个空格补足宽度,小数部分限制2位精度后,四舍五入为 .35 •%.2f:表示不限制宽度,只设置小数点精度为2,如11.345设置%.2f后,结果是11.35 体验一下如下代码的快乐吧,输入:

 
 
 
 

num1 = 11
num2 = 11.345
print("数字11宽度限制5,结果:%5d"%num1)
print("数字11宽度限制1,结果:%1d"%num1)
print("数字11.345宽度限制7,小数精度2,结果:%7.2f"%num2)
print("数字11.345不限制宽度,小数精度2,结果:%.2f"%num2)

输出结果:

 
 
 
 

数字11宽度限制5,结果:11 # 宽度5,补了3个空格
数字11宽度限制1,结果:11 # 宽度小于数字本身,无影响
数字11.345宽度限制7,小数精度2,结果:11.35 # 宽度7,补了2个空格,小数精度2,四舍五入后为.35
数字11.345不限制宽度,小数精度2,结果:11.35 # 不限制宽度,小数点后四舍五入后为.35

字符串格式化方式2

字符串格式化 - 快速写法

目前通过%符号占位已经很方便了,还能进行精度控制。

可是追求效率和优雅的Python,是否有更加优雅的方式解决问题呢?

那当然:有。

通过语法:f"内容{变量}"的格式来快速格式化,看如下代码:

 
 
 
 

name="传智播客"
set_up_year = 2006
stock_price = 19.99
print(f"我是{name},我成立于:{set_up_year},我今天的股票价格是:{stock_price}")

输出结果:

 
 
 
 

我是传智播客,我成立于:2006,我今天的股票价格是:19.99 #不做精度控制,原样输出

注意:这种写法不做精度控制,也不理会类型,适用于快速格式化字符串。

对表达式进行格式化

学习目标:

  • 了解什么是表达式

  • 掌握对表达式进行字符串格式化

字符串格式化 - 表达式的格式化

刚刚的演示,都是基于变量的。

可是,我想更加优雅些,少写点代码,直接对“表达式”进行格式化是否可行呢?

那么,我们先了解一下什么是表达式。

表达式:一条具有明确执行结果的代码语句

如:1 + 1、5 * 2,就是表达式,因为有具体的结果,结果是一个数字

又或者,常见的变量定义:name = “张三” age = 11 + 11

等号右侧的都是表达式呢,因为它们有具体的结果,结果赋值给了等号左侧的变量。那么,对于字符串格式化,能否直接格式化一个表达式呢?可以,上代码:

 
 
 
 

print("1*1的结果是:%d"%(1*1))
print(f"1*1的结果是:{1*1}")
print("字符串在Python中的类型是:%s"%type('字符串'))

输出结果:

 
 
 
 

1*1的结果是:1
1*1的结果是:1
字符串在Python中的类型是:<class 'str'>

在无需使用变量进行数据存储的时候,可以直接格式化表达式,简化代码哦。

练习:

股价计算小程序 定义如下变量:

  • name,公司名

  • stock_price,当前股价

  • stock_code,股票代码

  • stock_price_daily_growth_factor,股票每日增长系数,浮点数类型,比如1.2

  • growth_days,增长天数

计算,经过growth_days天的增长后,股价达到了多少钱 使用字符串格式化进行输出,如果是浮点数,要求小数点精度2位数。示例输出:

提示:

红色框框都是变量,要使用格式化的方式拼接进去 提示,可以使用:当前股价*增长系数增长天数,用来计算最终股价哦 如,股价19.99 * 系数1.2 7天 = 71.62778419199998,小数点现在精度2位后结果:71.63

参考代码:

 
 
 
 

# 定义需要的变量
name = "传智播客"
stock_price = 19.99
stock_code = "003032"
# 股票 价格 每日 增长 因子
stock_price_daily_growth_factor = 1.2
growth_days = 7

finally_stock_price = stock_price * stock_price_daily_growth_factor ** growth_days

print(f"公司:{name},股票代码:{stock_code},当前股价:{stock_price}")
print("每日增长系数: %.1f,经过%d天的增长后,股价达到了:%.2f" % (stock_price_daily_growth_factor, growth_days, finally_stock_price))

掌握input语句(函数)的使用

学习目标:

  • 掌握input语句(函数)的使用

获取键盘输入

试想一下,我们经常遇到过程序需要我们输入信息的场景。

比如:银行取钱的过程,是去银行,输入需要取款的钱数,然后银行给到你对应的钱。

如何在Python中做到读取键盘输入的内容呢?这里就要请出input语句了。

input语句(函数)

我们前面学习过print语句(函数),可以完成将内容(字面量、变量等)输出到屏幕上。

In Python, there is also an input statement corresponding to it, which is used to obtain keyboard input.

  • Data output: print

  • Data input: input

It is also very simple to use:

  • Use the input() statement to get input from the keyboard

  • Use a variable to receive (store) the keyboard input data obtained by the input statement

 
 
 
 

print("Please tell me who you are?")
name = input()
print("Get!!! You are: %s" % name)

Requires keyboard input:

 
 
 
 

please tell me who are you
Dark Horse Programmer# Keyboard output content and press Enter
Get!!! You are: Dark Horse Programmer

In the preceding code, the print statement that outputs "Please tell me who you are?" is redundant.

The input() statement can actually output the prompt content before asking the user to input the content. The method is as follows:

 
 
 
 

name = input("Please tell me who you are?")
print("Get!!! You are: %s" % name)

Output result:

 
 
 
 

please tell me who are you Dark Horse Programmer
Get!!! You are: Dark Horse Programmer

As shown in the figure, just fill in the prompt content directly in the brackets of the input.

The data type obtained by the input statement

All we have just experimented with input string type data.

So what happens if we enter numeric types or other types?

So, let us verify the data type of the input content through the type() statement we learned earlier.

It can be seen that no matter what type of data is entered by the keyboard

The final result is: data of string type

Go and try it yourself!

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130391798