This article entitle Python Basic Syntax is a continuation of the previous article entitled Python Setup Environment Variables.
Python Basic Syntax is a set of rules used to create Python statements while also creating a program in Python. The syntax is almost similar to C, Perl, and Java programming languages. But still, there are some differences between their functionalities.
What Is Python Basic Syntax?
In Python, basic syntax is a requirement that we need to know when creating a program in Python, and we use indentation in order to represent the block of a code.
Let us try to run a (Hello, World) program in Python in a different mode of programming.
Interactive Mode Programming In Python
We can use the Basic Python interpreter from a command line by simply writing python in the command prompt.
Example
C:\Users\Glenn>python Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.
Python command prompt will denotes which allows you to type your Python command. Type the following text on the command prompt and simply press enter.
print ("Hello, World!")
Output
Hello, World!
Script Mode Programming In Python
We can use the Python interpreter and a script parameter that will start the execution of the script and will continue once the script is done. Once the script is finished from execution, the interpreter is no longer active.
Now let us create a Python program in a script file. Python script files have a (.py) extension.
Example
print ("Hello, World!")
I will assume that you have an interpreter path in Python to set the path variable. So, let us try to run the program.
$ python test.py
Output
Hello, World!
Identifiers In Python
The identifier in Python is used to identify the variable, class, function, module, or other declared objects in a program. The identifier mainly starts from the letter A to Z or a to z or underscore (_) which has been followed by letters or zero, digits (0 to 9), and underscores.
Python did not allow any punctuation characters such as $, @, and % inside the identifiers.
Take Note
Python programming language is case-sensitive, Example Superpower and superpower is a different Python identifier.
The following list are naming conventions of Python identifiers
- Python name class should start with an uppercase letter and all other identifiers will start with a lowercase letter.
- An identifier that starts with a single leading underscore indicates which identifier is a private identifier.
- Once the identifier starts with two leading underscores it indicates a strongly private identifier.
- Once the identifier ends with two trailing underscores the identifier is a language-defined special name.
Reserved Words In Python
The following are reserved keywords that cannot be used as a variable or constant or any other identifier names and all Python keywords can contain lowercase letters only.
and | as | assert |
break | class | continue |
def | del | elif |
else | except | False |
finally | for | from |
global | if | import |
in | is | lambda |
None | nonlocal | not |
or | pass | raise |
return | True | try |
while | with | yield |
Lines and Indentation In Python
Python provides no braces in order to indicate blocks of code for a function and class which defines the control flow. Further, blocks of codes are denoted by the line indentation which is enforced rigidly.
Example
if True: print ("True") else: print ("False")
Still, the following block will generate an error.
if True: print ("Answer") print ("True") else: print ("Answer") print ("False")
All the continuous lines which have been intended with the same number of spaces will form a block.
Example
import sys try: # open file stream file = open(file_name, "w") except IOError: print "There was an error writing to", file_name sys.exit() print "Enter '", file_finish, print "' When finished" while file_text != file_finish: file_text = raw_input("Enter text: ") if file_text == file_finish: # close the file file.close break file.write(file_text) file.write("\n") file.close() file_name = raw_input("Enter filename: ") if len(file_name) == 0: print "Next time please enter something" sys.exit() try: file = open(file_name, "r") except IOError: print "There was an error reading file" sys.exit() file_text = file.read() file.close() print file_text
Multiline Statements In Python
Python statements typically end with a new set of lines which Python language does. Although it allows the use of line continuation character () backslash in order to denote that the line will continue.
Example
total = item_one + \ item_two + \ item_three
A statement that contains {}, [], or () brackets does not need to use a line continuation character.
Example
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Python Quotations
Python accepts both single (‘), double (“) and triple (”’ or “””) quotes just to denote a literal string, you can use it as long as the type of quote will start and end the string.
The triple quotes were used to span the string all over the multiple lines.
word = 'ITSOURCECODE' sentence = "This is Glenn Magada Azuelo." paragraph = """ ITSOURCECODE is a site that provides free source code and tutorials"""
Python Comments
A comment is a way for a programmer to write an explanation for the lines of code they have been writing. The purpose of the comment is to make the source code easier to read for another programmer to understand and Python comments is been ignored by a Python interpreter.
Just like other modern programming languages, Python also supports single-line (or end-of-line) and multi-line (block) comments. Comments in Python are very similar to programming languages such as Java, PHP, Perl, and BASH programming languages.
The hashtag sign (#) which is not inside a literal string starts the comment. This means that all the characters after hashtag (#) and up to the end of the line are considered to be part f the comment and the Python interpreter will ignore them.
Example
# First comment print ("Hello, World!") # Second comment
Output
Hello, World!
The following triple-quoted string is Python comments which are also ignored by the Python interpreter and can be used also as multiline comments.
''' This is a multiline comment with a triple qouted string. '''
Python Blank Lines
The Blank line in Python is a line that contains only white space and possibly with a comment and the Python interpreter ignores it totally.
In the interactive interpreter session, you must provide an empty physical line in order to terminate a multiline statement.
Multiple Statements on a Single Line in Python
A semicolon ( ; ) can allow multiple statements in a single line which has been given neither a statement starts a new set of the code block.
Example
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Multiple Statement Groups as Suites In Python
The group of individual statements that make a single block of code is also known as SUITES in Python syntax. This complex or compound statements such as while, if, def, and class require a line header and a suite.
Header lines start in the statement with a keyword and will be terminated with a colon ( ; ) and followed by one or multiple lines that make up the suite.
Example
if expression : suite elif expression : suite else : suite
Python Command Line Arguments
Many Python programs can be run to provide some basic information on how they should run. Python can enable you to do this with an -h —
Example
$ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc. ]
Summary
In summary, you have read about Python Basic Syntax. We also discussed in this article what Is basic syntax, interactive mode programming, script mode programming, identifiers, reserved words, Lines and indentation, multiline statements, quotations, comments, blank lines, multiple statements on a single line, multiple statement groups as suites, and python command line arguments.
I hope this article about Python Basic Syntax could help you a lot to continue pursuing learning this powerful programming language.
If you want to learn more check out my previous and latest articles for more career-changing articles.