Python learning variables, strings, numbers, comments

Posted by mgelinas on Wed, 09 Feb 2022 21:46:44 +0100

Python learning (I) variables

Since the postgraduate study mainly uses Python and C + +, and has been busy with graduation design recently, the learning and sorting of Java language is the first step, and the next step is to complete the study of Python. In fact, most of the language specifications are interlinked. They are written here for easy reference and entry learning in the future, In the learning process, I mainly refer to the book "python programming from introduction to practice".

Environmental preparation

At present, the commonly used Python interpreter is 2 X and 3 For the two versions of X, python 3 usually corresponds to the newer version. It is recommended to use the version above Python 3 to learn python. The code of Python 3 may be incompatible with the version of Python 2. At the same time, python 2 does not support Chinese by default. The official download address of Python is given below:

Python download address

The Python interpreter version used in this article is 3.7.6 (the time difference between beginners of the 3. X interpreter will not be too large), the IDEA used is PyCharm, and the download address of PyCharm is below:

PyCharm download address

There are many installation tutorials online. I won't repeat them here. Next, I'll start learning Python syntax.


Use of variables

Different from other languages, Python is used for__ Indent__ There are strict requirements. You can't use Tab to adjust the code position at will. At the same time, you don't need to declare the type when defining variables. You can only write one statement per line. At the end of each statement, you don't need a semicolon to mark the end of the statement.

# An example of Python defining variables and outputting them. Note that there is no indentation, no type declaration, and no semicolon.

name = "Just want to fish"

#The common error name is not defined. This sentence appears in the trackback, indicating that the variable name at the time of printing may not match the variable name at the time of definition

Python's variable types mainly include integer int, floating-point float, Boolean bool (non-0 is true / True), complex, string, list, tuple and dictionary.

If you want to view the data type of a variable, you can use the type function. The usage of type is given below:

name = "Just want to fish"
age = 18
print(type(name))		#<class 'str'>
print(type(age))		#<class 'int'>

Naming of variables

The variable naming specification of Python is similar to that of Java language;

  1. Variable names can only include numbers, letters and underscores, and cannot start with an underscore;
  2. The variable name cannot contain spaces. You can use underscores_ To segment words;
  3. Keywords and function names cannot be used as variable names;
  4. The variable name should be short and easy to understand. It is recommended to use lowercase as the variable name.

You can use the following methods to view pre-defined keywords in Python__ import__ Keywords can be imported into a toolkit, which has different functions and other tools for developers to use:

import keyword

# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']

character string

Unlike other commonly used languages, Python has no character variables. As long as it is enclosed in quotation marks, whether it is double quotation marks or single quotation marks, it is a string.

name = 'A'
sex = "Male"
print(type(name))	#<class 'str'>
print(type(sex))	#<class 'str'>

Modify the case of strings

The following methods are commonly used to modify the case of strings: title(),upper(),lower;

The following will introduce the functions of these functions in turn;

#The main function of the title() function is to capitalize the first letter of each word

name = "talor swift"
print(name.title())		#Talor Swift

#The upper() function converts all lowercase words to uppercase

name = "Talor Swift"
print(name.upper())		#TALOR SWIFT

#The lower() function converts all uppercase words to lowercase

name = "Talor Swift"
print(name.lower())		#talor swift

String splicing

Python use__+__ Splice string number

first_name = "Talor"
last_name = "Swift"
full_name = first_name + " " + last_name
print(full_name)		#Talor Swift

Add blank (formatted output)

In programming, white space generally refers to all non printing characters, such as spaces, tabs and line breaks. White space can be used to organize the output, making the result easier to understand.

Similar to the C language, Python uses \ n to wrap lines and \ t to add tabs.


#	PythonCJava



We can use formatted output to make the code cleaner and more beautiful.

Delete blank

In Python, "Python" and "Python" are different. The interpreter will think that they are different characters and can find the extra white space of the latter, but sometimes white space is meaningless to us. Therefore, we need to delete the white space at both ends of the character when processing. The common methods are as follows: lstrip(),rstrip(),strip(),

#The lstrip() method is used to delete the white space to the left of the character. The quotation marks are added in the output to make it easier to observe whether there is a white space
name = " Python "
print(name.lstrip())		#"Python "

#The rstrip() method is used to remove the white space to the right of the character
name = " Python "
print(name.rstrip())		#" Python"

#The strip() method is used to delete all blanks on both sides of a character
name = " Python "
print(name.strip())			#"Python"

It should be noted that although the above operation outputs the result after deleting the blank, because the contents in the variable are not replaced, the output of name is still the result of processing, as shown below:

#The strip() method is used to delete all blanks on both sides of a character
name = " Python "
print(name.strip())			#"Python"
print(name)					#" Python "
name = name.strip()
print(name)					#"Python"

Therefore, if we want to delete the blank in the variable, we must re assign the processed result to the variable.

Common errors using strings

We may have the following problems when using single quotation marks and double quotation marks;

message = 'I 'm Lihua'

message = 'I 'm Lihua'
SyntaxError: invalid syntax
 This error indicates that there is a syntax problem. You need to carefully check the specific reason. But through the arrow, we can know that the error appears after the second single quotation mark
# In order to solve the above problems, we can use the escape symbol \

message = 'I \'m Lihua'
print(message)		#I 'm Lihua

#\The 'limit' symbol only represents the content inside the string, not the beginning or end of the string.



In Python, you can add (+), subtract (-), multiply (*), divide (/), multiply (* *), and remainder (%) to integers:

print(2 + 3)		#5
print(2 - 3)		#-1
print(2 * 3)		#6
print(2 / 3)		#zero point six six six six six six six six six six six six six six six six 	 Division in other languages usually results in integer digits only
print(2 ** 3)		#8
print(2 % 3)		#2

At the same time, you can also use () in Python to artificially determine the operation order

print((2-3)*4) #-4

Floating point number

Numbers with decimal points are called floating-point numbers. In most cases, the calculation of floating-point numbers will be expected, but sometimes the number of digits contained in the result may be uncertain:

print(2*0.3)		#0.6
print(3*0.1)		#0.30000000000000004	

This error mainly comes from the fact that the floating-point value comes from the fact that the binary system cannot accurately represent the fraction 1 10 \dfrac{1}{10} 101‚Äč.

Use the Str() function to convert a number to a string

In Python, numbers cannot be spliced directly with strings, as shown below:

number = 13.5
first_word = "I have"
last_word = "Yuan money"
print(first_word + number + last_word)

Traceback (most recent call last):
  File "E:/PythonLearning/", line 4, in <module>
    print(first_word + number + last_word)
TypeError: can only concatenate str (not "float") to str
 There is no way to put one in this sentence float A variable of type is converted to str Type.
#In order to make the splicing successful, we can use the str() function to convert numbers into strings

print(first_word + str(number) + last_word)		#I have 13.5 yuan


In Python, using # to identify comments, all elements on the same line after # will be ignored by the interpreter.

But sometimes we may want to divide the comment into several lines, which can be used at this time___ Three consecutive quotation marks___ To identify the beginning and end of the comment, and the part in the middle of the quotation marks will be interpreted and ignored.

Specific examples of the two notes have been shown above and will not be shown here.

Topics: Python string