Learning a language should be fun. Why make it hard?
Completed articles
The title | link |
---|---|
1. This is the right way to start learning Python | Juejin. Cn/post / 691636… |
This series of articles will be completed before the Spring Festival of 2021, welcome to follow, like, comment -- dream eraser
Basic Python data types and input and output functions
2.1 Basic data types
There are some basic types for every language, and Python is no exception, but data types in Python are much simpler than in other languages. There are basically the following types.
- Numeric data types, commonly integers and floating point numbers
- Boolean data types, often referred to as true and false
- String data type
Note that when it comes to data types, it specifically refers to the data types of variables. Learn how to look at data types in Python before you learn more about them. This function, which depends on the data type, is called type, so when we name variables, we also need to learn the official naming technique.
For example, look at the datatype of a variable x with a value of 10 as follows:
x = 10
print(type(x))
Copy the code
The run result is
<class 'int'>
Copy the code
The output indicates that the variable x has an integer data type. You can test a decimal in the same way.
x = 10.1
print(type(x))
Copy the code
The running result is as follows:
<class 'float'>
Copy the code
Yes, this is a floating point number.
2.1.1 Numerical data types
You’ve seen that there are two numeric data types in Python, one called integer and one called floating point, and the mathematical difference between one with a decimal point and one without one is essentially the difference.
If you add an integer and a floating-point number, the result is a floating-point number, which Python automatically converts to:
x = 10.1
y = 10
z = x + y
print(type(z))
Copy the code
So if I run this code, I can check that z is a float.
2.1.2 Different representations of integers
For learners of programming languages, you’ve probably heard that computers deal with binary, so programming languages are particularly difficult. Right? What? Learning a programming language has something to do with binary, but it has nothing to do with learning a trade that makes money. Or to put it more directly, if you have a salary of $10, 000 in Beijing, you may not need all kinds of base conversion.
Display integers in binary format note that we’re going to display integers in octal and hexadecimal in a second, but we’re dealing with integers, 1,2,3,4 without a decimal point, not floating point.
Once again, one that will become clear later is called Python’s built-in function. The function used to convert integers to binary format is called bin, and it looks like this:
x = 10
print(bin(x))
Copy the code
The output is:
0b1010
Copy the code
Binary starts with 0b followed by 1,0. If you see integers like this in Python code, realize that this is a normal number, just presented differently.
The built-in function used to convert integers to octal is OCT, and the code is optional. Octal displays numbers starting with 0o. Display integers in hexadecimal format. Numbers starting with 0x are displayed in hexadecimal format. The conversion function is hex. At this point, you have a rudimentary understanding of integers and the different representations of integers, and it doesn’t really matter. What matters is that when you learn Python code and see something that starts with one of these symbols, you know it’s just a normal integer.
2.1.3 Data Type Cast
This area is just the tip of the iceberg when it comes to casting, and the reason to learn it is because you already know integers and floating-point numbers, and presumably have a glimpse of how they differ. They can actually convert to each other before, but you have to take some risks to convert. Why? Let’s see.
x = 10.5
print(int(x))
Copy the code
In the above code, I cast a floating point number. Notice that I put a shell int in front of x, so we’ll learn after the function. Now you can imitate the code and understand what I’m talking about.
Int () = x; int() = x; int() = x; int(); It’s really lost, and you’re going to see that a lot in subsequent programming.
Int is also a built-in function in Python that attempts to convert a variable of any data type to an integer.
Similarly, if you can guess the name of the function that converts a variable of any data type to a floating-point number, you’re starting to get the hang of Python.
Int, float, float, float, float, float, float, float, float
2.1.4 Extend functions commonly used by several numeric data types
Although you haven’t learned much, you should have noticed one word by now — functions are extremely frequent in Python, which is why so many speakers of other languages despise Python as a language of functions.
Functions commonly used by numeric data types. Here are a few simple examples and we’ll learn more about them later.
- Abs () computes the absolute value
- Pow (alpha)
- Round ()
- Max () is the maximum value
- Min () goes to the minimum
Reference code as follows, copy 2 times to know what is doing on the line, the following code involves the concept of parameters in the function, do not do too much explanation.
# abs() calculates the absolute value
a = -1
print(abs(a))
# pow()
x = 2
c = 3
print(pow(x,c))
# round(
d = 34.6
print(round(d))
# Max () takes the maximum value
print(max(1.2.3))
# min() to the minimum
print(max(9.10.6))
Copy the code
2.1.5 Boolean data type
Boolean is a transliteration of Boolean. In Python there are two types of Boolean, one is True and the other is False. Using the type function to test a Boolean is a bool. Note that bool is also an integer in some places because True is cast to 1 and False is pre-cast to 0. The code is as follows:
x = True
print(int(x))
print(int(False))
Copy the code
Booleans will often be used in conditional judgment, which is a knowledge point that must be mastered, and we will encounter it later.
2.1.6 String Data type
Strings are the most commonly used data type in Python, and also the most popular data type to understand. In general, the part between two double quotes (“) or two single quotes (‘) is a string. For example:
my_name = "Dream Eraser"
print(my_name)
my_name = 'Dream Eraser'
print(my_name)
my_name = 'Dream eraser'
print(my_name)
print(type(my_name))
Copy the code
In the following sentence, remember that single and double quotation marks are used in pairs. Double quotation marks should be nested within single quotation marks, as in the third paragraph above.
Concatenation of strings Two strings can be concatenated by +, where the plus sign does not mean addition between numbers. The test is as follows:
a = "my"
b = "name"
c = a+b
print(c)
Copy the code
An error message is displayed when numbers and strings are added. If you do not want to report an error, you can passstr
The function converts a number to a string, for example:
a = 123
b = "name"
# STR (a) converts the integer variable a to a string
c = str(a) + b
print(c)
Copy the code
In the previous section, we learned that triple quotes can be used for comments, but the real use of triple quotes is still in the string scenario, representing multi-line strings.
my_str = """ I am the first line of the string I am the second line of the string I am the dream eraser I am the boy I once was ""
print(my_str)
Copy the code
Escape characters There are special characters in a string that need special handling. For example, if you want to use single quotes inside single quotes, you need to write them in the following format:
a = 'I\'m a girl '
print(a)
Copy the code
Note that you can use single quotes in single quoted strings by using \’, which is the escape character. Common escape characters are as follows:
Escape character | meaning |
---|---|
‘ | Single quotes |
“ | Double quotation marks |
\t | tabs |
\n | A newline |
\ | The backslash |
There are other escape characters, do not expand the initial learning stage, the above several in the code to try twice, or know what to do. | |
Sometimes, of course, you want to avoid escaping the transfer character, which requires adding a special letter before the whole stringr There are many special characters added to the front of the string. For example, the following code. |
a = r"I\nm a girl"
print(a)
Copy the code
In this case, the \n character is not escaped as a newline character, and the output is what the string looks like:
I\nm a girl
Copy the code
Using PyCharm, you can clearly identify escaped characters by color:
Quick string copying There is a unique trick in Python that allows you to quickly copy a string using the mathematical symbol *. For example, the following code will quickly copy a bunch of # signs.
print("#"*100)
Copy the code
2.2 Input and output
The core functions of this section are print and input. Before learning these two functions, a built-in help function is added, which can view the usage documents of other functions. For example, print tests:
help(print)
Copy the code
The output is shown in the following figure
This includes a complete description of the print function, the most important part being as follows:
print(value, ... , sep=' ', end='\n', file=sys.stdout, flush=False)
Copy the code
Among them:
- Value indicates the number of bytes to be output. Multiple bytes can be output using commas
.
separated - Sep Delimiter for output of multiple data. Default is space
- End Indicates the output symbol at the end of a line
- File output location, the default output console, is the black window, can be set to a specific file
- Flush Specifies whether to flush the data stream buffer. Default: False
All of this is actually called function parameters.
Write test code that can be copied and run:
# output multiple data
print("hello"."dream")
# Delimiter for multiple data outputs
print("i"."love",sep="#")
Copy the code
Run results and other parameters to test, the above content is mainly for multiple data output, namely print(a,b,d,d) must be mastered.
2.2.1 Format print output
In a lot of teaching materials, this part of the content will take up more time, in fact, it is unnecessary, because things are too miscellaneous, learned but forgotten, not as simple learning in the brain to leave a “boon, there is this thing” trace can.
Print: print: print: print: print: print: print: print: print: print: print: print: print: print
The first thing to learn is formatting characters, common ones are the following.
%d
Integer output%f
Floating point output%x
Hex output%o
octal%s
String output, actually know this one will do
For example, the following code is an example:
name = eraser
age = 18
score = 100
Format a variable output
print("I am % s" % name)
# Format multiple variable outputs
print("I'm % S. I'm % D. I got % D on my test." % (name,age,score))
Copy the code
Pay attention to the format, the front is a format string, the formatting characters as a special symbol in a string, equivalent to account for a hole, the string is followed by a %, fixed to the symbol %, is replaced in the behind of the content, can be a variable name, also can directly be value, if the previous placeholder is % d, It’s followed by a number, or a string if it’s %s. Generally, it will be illustrated with upper and lower pictures:
If the placeholder format character does not match the value of the actual variable given, for example, %d followed by a string given by age, an error will be reported:
name = eraser
age = 18
score = 100
print("I am % s" % name)
print("I'm % S. I'm % D. I got % D on my test." % (name,"nnn",score))
Copy the code
But if it is preceded by %s and followed by a string, it will be automatically converted to that.
name = eraser
age = 18
score = 100
print("I am % s" % name)
print("I'm % S. I'm % S this year. I got % D on my test." % (name,18,score))
Copy the code
So generally not strict, before the placeholder general %s can be used. It’s not rigorous, but it works
Precise control of the formatted output is mainly used for the output precision floating-point number, because the floating-point decimal point, control point display digits is important, don’t make much of this article involves, experience has taught me that many students learn and forget the past, you only need to remember the Python can be precise control of floating point Numbers display is ok.
2.2.2 the format function
The above % can also be used in the learning stage. In the actual formatting output, more operations are performed using format. Format is used to carry space through {} symbols, for example:
print("I am {}. This year {}, I got {} on the exam.".format(name,age,score))
Copy the code
Use {} for everything that needs to be occupied. There is no need to remember the various types, and there is no mysterious symbol %.
2.2.3 Input Data input
Input () and print ()
The parameter is relatively simple with only one input prompt. Test code:
name = input("Please enter your name:")
print("Enter the name {}".format(name))
Copy the code
The code runs by asking you to enter your name, and when you press enter, the output is formatted. By default, input data is stored in a variable, in this case name, which is of type string. If you need to get a user input number, use int to convert it.
Input is relatively simple, and I’ll cover those first in this article.
2.3 Summary of this blog
The core of the above content introduces the integer, floating point, Boolean and string data types, the key to master is the conversion between types and the preliminary understanding of string, for the formatting output part of the master format can cope with most of the following scenarios, the rest of the content as appropriate to forget, after all, learning programming is quite mental.
The last bowl of chicken soup
Keep learning and every day brings a new blow
O ha ha ~ O (studying studying)