preloader

Python101: 2. Basic Syntax

post thumb
Python
by Admin/ on 30 Jun 2021

Python101: 2. Basic Syntax


Python is a scripting language.

A scripting language is a special language between HTML and programming languages such as Java, Visual Basic, C++, etc. Although it is closer to the latter, it does not have the complex and rigorous syntax and rules of programming languages. Some scripting languages have evolved, such as Python, and perl can be compiled into intermediate code and then executed, so that they can be called compiled scripting languages.

The “advantage” of scripting languages is that they don’t need to be “compiled” beforehand. So instead of having to compile and then run the language like Java or C++, a scripting language can just read a text file and execute it as it is interpreted.

Python is a unique scripting language, and a quick overview of its main points are.

  • Object-Oriented: Every variable is a class, with its own attribute and method.
  • Syntax blocks: indentation (four spaces) rather than semicolons, brackets, and other symbols are used to mark them. Therefore, spaces at the beginning of lines cannot be written arbitrarily.
  • Comments: in-line “#” signs are used, and inter-line comments are written between two consecutive sets of three single quotes: '''
  • Continuation: enter a backslash plus a space ('\ ‘) at the end of the line, then a line break. If the syntax at the end of the line is obviously unfinished (for example, ending with a comma), you can just continue the line.
  • print and input: functions print() and input(), note the sep and end arguments to print().
  • Variables: No need to specify variable types or declare variables in advance.
  • Delete variable: del()
  • Copy variable: Assign variable a to b directly, sometimes just copying a “reference”. Changes to b and a will still affect each other afterwards. Use a is b to determine if it is the same address if necessary.
  • Module: Load the module by import pandas (or import pandas as pd) and call the methods in the module with something like pandas.DataFrame (or pd.DataFrame). You can also use from pandas import DataFrame so that you can use DataFrame directly as the call name in the following.
  • help: Use the dir() and help() commands together; the former outputs all members of a variable.

Python Identifiers


An identifier is a collection of valid strings that are allowed as names in a computer language. Some of these are keywords, which form the identifiers of the language. Such identifiers cannot be used as identifiers for other purposes, or they will cause syntax errors (SyntaxError exceptions).

A legal Python identifier needs to adhere to the following rules.

  • The first character must be a letter or an underscore (_)
  • The remaining characters can be letters and numbers or underscores
  • Case-sensitive
  • They cannot be Python keywords, such as def, class, or any other identifier

Identifiers that begin with an underscore have a special meaning. A single underscore _foo represents a class attribute that cannot be accessed directly, but must be accessed through the interface provided by the class, and cannot be imported using from xxx import *.

__foo starting with a double underscore represents a private member of a class, and __foo__ starting and ending with a double underscore represents a special method-specific identifier in Python, such as __init__() for a class constructor.

Python can display multiple statements on the same line by separating them with a semicolon ;, e.g.

print("hello");print("world")
# hello
# world

Python keywords


The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or any other identifier names.

All Python keywords contain only lowercase letters.

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

Indentation


Python is known for its ‘elegance and simplicity’, and one of the most important reasons for this is its ‘indentation’.

While most programming languages use “{}” to represent a block of statements or code segments, Python uses an indentation hierarchy to organize blocks of code, and the convention is that an indent is represented by ‘4 spaces’, so be sure to follow the convention of Be sure to stick to the convention of using 4-space indentation.

If you are using a text editor or IDE, you can automatically convert Tab to 4 spaces and then use the tab key to use indentation, making sure you don’t mix Tab and spaces.

The amount of indented whitespace is variable, but all block statements must contain the same amount of indented whitespace, and this must be strictly enforced. This is shown below.

if True:
    print("neo")
else:
    print("smile")

The following code will execute with an error.

if True:
    print("neo")
else:
    print("smile")
   print("it")  

Therefore, you must use the same number of indented spaces at the beginning of a line in a Python block of code.

Multi-line statements


Python statements are generally terminated by a new line.

But we can use a slash () to split a one-line statement into multiple lines, as follows.

total = item_one + \
        item_two + \
        item_three

Statements containing [], {} or () brackets do not need to use multi-line concatenation. The following example.

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Python quotation marks


Python accepts single quotes (’ ), double quotes (" ), and triple quotes (''' “"") to represent strings, and the quotes must start and end with the same type.

Where triple quotes can be composed of multiple lines, a shortcut syntax for writing multi-line text, commonly used document strings, in specific locations in the file, is used as a comment.

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Python comments


Statements that begin with ‘#’ are comments, and they don’t have to appear at the beginning of a line; you can also add comments after certain statements; they are for human eyes and can be anything you want; the interpreter will ignore them, but be careful not to use meaningless comments.

Python has single-line comments starting with #, and Python doesn’t have block comments, so the recommended multi-line comments now use # as well, for example.

#! /usr/bin/python

# First comment
print("Hello, Python!"); # second comment

Output results.

Hello, Python!

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

name = "Madisetti" # This is again comment`

Multiple comments.

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Python spaces and blank lines


In Python, spaces and blank lines are sometimes too guiltily placed in code to make it look clearer and more readable. Spaces or blank lines, unlike code indentation, are not part of the Python syntax.

The Python interpreter will run without errors if you don’t insert spaces or blank lines when writing. But the purpose of spaces or blank lines is to separate two pieces of code that have different functions or meanings, so that the code can be maintained or refactored later.

Spaces and blank lines are used to increase the readability of the code.

For example, adding spaces when variables are copied.

hello = "world"

such as a blank line between class member functions and two lines between module-level functions and class definitions.

class A:
 
    def __init__(self):
        pass
         
    def hello(self):
        pass
         
         
def main():
    pass

print() defaults to newline output, if you want to implement no newline you need to add the end parameter.

x="a"
y="b"
print(x, end=' ')
print(y, end=' ')

Summary


This article has taught you about Python’s syntax and how Python is a concise scripting language, and how using indentation, spaces, line breaks, and other prescribed syntax can keep your program running properly and make it more readable.


Reference.

https://www.xjimmy.com/python-4-code.html
https://wizardforcel.gitbooks.io/w3school-python/content/3.html https://github.com/JustDoPython/python-100-day/tree/master/day-002

comments powered by Disqus