The third day of Python basic learning: Python syntax

Execute Python syntax

As we learned in the previous section, the syntax for executing Python can be written directly on the command line:

>>> print("Hello, World!")
Hello, World!

Or by creating a python file on the server, with a .py file extension, and running it on the command line:

C:\Users\Your Name>python myfile.py

Python indentation

Indentation refers to spaces at the beginning of lines of code.

In other programming languages, code indentation is only for readability, but in Python indentation is very important.

Python uses indentation to indicate code blocks.

example

if 5 > 2:
  print("Five is greater than two!")

run instance

insert image description here

If the indentation is omitted, Python errors out:

example

Grammatical errors:

if 5 > 2:
print("Five is greater than two!")

run instance

insert image description here

The number of spaces is up to the programmer, but at least one is required.

example

if 5 > 2:
 print("Five is greater than two!")  
if 5 > 2:
        print("Five is greater than two!") 

run instance

insert image description here

You must use the same amount of spaces in the same code block, otherwise Python errors out:

example

Grammatical errors:

if 5 > 2:
 print("Five is greater than two!") 
        print("Five is greater than two!")

run instance

insert image description here

Python variables

In Python, variables are created when they are assigned a value:

example

Variables in Python:

x = 5
y = "Hello, World!"

run instance

insert image description here

Python command without declaring variable

In the Python variables chapter we learn more about variables.

note

Python has the ability to comment code within documentation.

Comments start with # and Python renders the rest as comments:

example

Notes in Python:

#This is a comment.
print("Hello, World!"

run instance

insert image description here

at last

Today's knowledge sharing ends here

If you have any questions, you can find me

Guess you like

Origin blog.csdn.net/yxczsz/article/details/132517603