This is the 16th day of my participation in the August More Text Challenge

Interactive programming

Interactive programming does not need to create the PY file, but to write the code through the interactive mode of the Python interpreter. Enter CMD and enter the Python command in the command line to start interactive programming. The prompt window is as follows:

C:\Users\Administrator> Python Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>Copy the code

Enter the following text at the Python prompt and press Enter to see what works:

>>> print("Hello, Python!" ) Hello, Python!Copy the code

Scripted programming

Start by writing the PY file using a text editor, and start executing the py file by calling the interpreter with python commands until it is finished. When the file execution is complete, the interpreter is no longer valid.

Let’s write a simple Python program. All Python files will have a.py extension. Copy the following source code into the first.py file.

print("Hello, Python!")
Copy the code

Execute the first.py file using the Python command

$ python test.py
Hello, Python!
Copy the code

Line and indent

The biggest difference between learning Python and other languages is that Python blocks of code do not use curly braces {} to control classes, functions, and other logical judgments. The most distinctive feature of Python is the indentation of modules.

The amount of indent white space is variable, but all code block statements must contain the same amount of indent white space, which must be strictly enforced. As follows:

if True:
    print("True")
else:
    print("False")
Copy the code

The following code will execute an error:

if True:
    print("Answer")
    print("True")
else:
    print("Answer")
    # No strict indentation, an error will be reported on execution
  print("False")
Copy the code

If you execute the above code, you will receive the following error notification:

$ python test.py  
  File "test.py", line 5
    if True:
    ^
IndentationError: unexpected indent
Copy the code

Unexpected IndentationError: Unexpected indent is when the Python compiler tells you “Hi, dude, there’s something wrong with the format in your file. Maybe TAB and space don’t align. “All Python is very strict about formatting.

IndentationError: unindent does not match any outer indentation level Indentation level

Therefore, the same number of indent Spaces must be used in Python blocks of code. It is recommended that you use a single TAB or two or four Spaces for each indentation level. Do not mix!

Digression: read an article said use the blank space key programmers earn more than the Tab key programmer at http://blog.csdn.net/lunaqi/article/details/74454425

Multi-line statement

To improve code readability, Python statements typically end with a new line. In other words, write only one statement in a row. If a statement is too long, it can make it difficult to read the code. How to do?

We can use a slash (\) to break a line into multiple lines, as follows:

total = item_one + \
        item_two + \
        item_three
Copy the code

Statements containing [], {}, or () parentheses do not require multi-line hyphens. Examples are as follows:

days = ['Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday']
Copy the code

Python quotes

Python can use quotation marks (‘), double quotation marks (“), triple quotation marks (” “, or “””) to represent strings. The start and end of quotation marks must be of the same type.

A quick syntax for writing multiple lines of text, often used in docstrings, as a comment at a particular point in a file

word = 'word'
sentence = "It's a sentence."
paragraph = """ This is a paragraph. Contains multiple statements """
Copy the code

Python annotation

Single-line comments in Python start with #.

# first comment
print("Hello, Python!")  # second comment
Copy the code

Output result:

Hello, Python!
Copy the code

Comments can be at the end of a statement or expression line:

name = "Madisetti" # This is a comment
Copy the code

Multi-line comments in Python use three single quotes (“”) or three double quotes (“””).

"" This is a multi-line comment, using single quotes. This is a multi-line comment using single quotes. This is a multi-line comment using single quotes. ' ' '

""" This is a multi-line comment, in double quotes. This is a multi-line comment, in double quotes. This is a multi-line comment, in double quotes. "" "
Copy the code

Python is a blank line

A blank line separating functions or methods of a class indicates the beginning of a new code. The class and function entry are also separated by a blank line to highlight the beginning of the function entry.

Unlike code indentation, blank lines are not part of Python syntax. Write without inserting blank lines, and the Python interpreter runs without error. However, blank lines are used to separate two pieces of code with different functions or meanings for future maintenance or refactoring.

Remember: blank lines are part of the program code.

Multiple statements are displayed on the same line

Python can use multiple statements on the same line (but is not recommended), with semicolons (;) between statements. Here is a simple example of splitting:

str='a' ; str1='b' ; print(str);print(str1) # Notice the space
Copy the code

Execute the above code and enter the result as follows:

a
b
Copy the code

The output

To print the specified text to the screen, use print() to enclose the string in parentheses. For example, output ‘hello, world’ with code like this:

print('hello, world')
Copy the code

The print() function can also take multiple strings separated by commas (,) to form a single output:

print('The quick brown fox', 'jumps over', 'the lazy dog')
The quick brown fox jumps over the lazy dog
Copy the code

Print () can also print integers, or compute results:


print(300)
300
print(100 + 200)
300
Copy the code

So we can print the result of 100 + 200 a little nicer:

print('100 + 200 ='.100 + 200)
100 + 200 = 300
Copy the code

Note that for 100 + 200, the Python interpreter automatically computes 300, but ‘100 + 200 =’ is a string, not a mathematical formula. Python treats it as a string.

The input

At this point, you can print the result you want with print(). But what if you want the user to type some characters from the computer? Python provides an input(), which lets the user enter a string and store it in a variable. For example, enter the user’s name:

name = input()
jerry
Copy the code

When you type name = input() and press Enter, the Python interactive command line is waiting for your input. At this point, you can type any character and press Enter to finish typing.

After typing, there is no prompt, and the Python interactive command line is back to the >>> state. So what happened to what we just typed? The answer is in the name variable. To view variable contents, type name:

name
'jerry'
Copy the code

To print out the contents of the name variable, instead of just writing name and pressing enter, you can use the print() function:

print(name)
jerry
Copy the code

With input and output, we can change the program that printed ‘hello, world’ to something meaningful:

name = input(a)print('hello,', name)
Copy the code

Running the above program, the first line of code will let the user enter any character as his name and store it in the name variable. The second line of code says hello to the user based on the user’s name, such as lidao:

python hello.py
lidao
hello, lidao
Copy the code

But the app runs without any prompt that says, “Hey, enter your name,” which is unfriendly. Fortunately, input() lets you display a string to prompt the user, so we changed the code to:

name = input('please enter your name: ')
print('hello,', name)
Copy the code

When you run the program again, you’ll notice that the program will print please Enter your name:, so that the user can type a name as prompted and get hello, XXX:

python hello.py
please enter your name: lidao
hello, lidao

Copy the code

Each time you run the program, the output will be different depending on the user’s input. On the command line, input and output are as simple as that. Input () and print() are the most basic inputs and outputs on the command line, but users can also input and output through other more advanced graphical interfaces, such as entering their name in a text box on a web page and clicking “OK” to see the output on the web page.

identifier

Identifiers in Python are names used to identify variables, functions, classes, modules, and other objects.

Naming rules:

  1. Identifiers can contain letters, digits, and underscores (_), but must begin with a non-numeric character.
  2. Letters only includeISO-LatinA-z and A-z in character sets.
  3. Identifiers are case sensitive, thereforeFOO and fooIt’s two different objects.
  4. A special symbol, such as$, %, @Cannot be used in an identifier.

Identifiers that begin with an underscore have special meaning. Foo, which starts with a single underscore (_), is a class attribute that cannot be accessed directly. It must be accessed through the interface provided by the class and cannot be imported using from XXX import *. An __foo starting with a double underscore represents a private member of the class; __foo__, which starts and ends with a double underscore, represents the Python identifiers for special methods, such as _init() for class constructors. In addition, words such as if, else, and for are reserved words and cannot be used as identifiers. The following table lists all reserved characters and their descriptions:

Reserved words

  • And is used for expression operations, logic and operations
  • As is used for type conversion
  • Assert assertion, used to determine whether the value of a variable or conditional expression is true
  • Break Interrupts the execution of a loop statement
  • Class is used to define classes
  • Continue continues the next loop
  • Def is used to define functions or methods
  • Del Removes the value of a variable or sequence
  • Elif conditional statement, used with if and else
  • Else conditional statement, used with if and elis. Also used for exceptions and loop statements
  • Except except contains a block of code that operates after an exception has been caught, and is used in conjunction with try and finally
  • Exec is used to execute Python statements
  • For for loop statement
  • Finally is used for exception statements, and after an exception occurs, the code block contained in finally is always executed. Used with try and except
  • From is used to import modules, in conjunction with import
  • Global defines global variables
  • If conditional statement, can be used with elif, else
  • Import is used to import modules and can be used in conjunction with FROM
  • In determines whether the value of a variable is in a sequence
  • Is determines whether the value of a variable is an instance of a class
  • Lambda defines anonymous functions
  • Not is used for expression operations, logical non-operations
  • Or is used for expression operations, logic, or operations
  • Pass represents an empty placeholder for a class, method, or function
  • Print print statement
  • Raise Indicates the operation to raise an exception
  • Return Specifies the return value of the function
  • Try A try contains statements that can exception. Used with except and finally
  • The while while loop statement
  • With simplifies Python statements
  • Yield is used to return values in sequence from a function

variable

What is a variable? Remember the basics of algebra you learned in junior high school math:

Let the sides of the square be a, then the area of the square is a x a. Taking side length A as a variable, we can calculate the area of the square according to the value of A. For example, if a=2, the area is a x a=2 x 2 = 4. If a=3.5, the area is a x a=3.5 x 3.5 = 12.25. In Python, variables are used to store data. For example, the sides of a square are actually 2 and 3.5.

In real development, if there is data to be stored in a variable, define the variable name and assign the corresponding data. Each variable contains information such as the variable name and data. Each variable must be assigned a value before it can be used, and then the variable can be created. In Python, the equal sign (=) is used to assign values to variables. The left side of the equal (=) operator is a variable name, and the right side of the equal (=) operator is the value stored in the variable. Such as:

counter = 100   # Assign integer variables
miles = 1000.0  # floating-point
name = "lidao" # string

print(counter)
print(miles)
print(name)
Copy the code

In the above example, 100,1000.0 and “lidao” are assigned to the counter, miles, and name variables, respectively. Executing the above program produces the following results:

100
1000.0
lidao
Copy the code

Multiple variable assignments

Python allows you to assign values to multiple variables at the same time. For example, if a = b = c = 1, create an integer with the value 1 and all three variables store the same data. It is also possible to specify multiple variables for multiple data. For example: A, b, C = 1, 2, “jingjing”jingjing, two integer data 1 and 2 are allocated to variables A and B, and the string object “jingjing” is allocated to variable C.

The variable name

In practical development, in theory, variable names can be arbitrarily named as long as they follow the naming rules of identifiers, as long as there is no conflict, but in order to make the code we write have certain readable characteristics, so when defining variable names, it should be as practical as possible.

# Define height variables
high = 175
Define the name variable
name = 'jerry'
# Define the age variable
age = 19
Copy the code