In terms of basic syntax, Python 3 has a lot of similarities with Perl, PHP, and Ruby. Many tutorials would include Java, but that is not even remotely true. This post is an introduction to Python’s basic syntax designed for new learners of Python.
Your First “Hello, World!” Python Codes
Let us execute the same codes in different ways with Python.
Interactive Python Programming
By interactive programming, it means using the Python interpreter interactively where we type in codes, and we get immediate feedback. Okay, let us start the Python interpreter by running it without passing any arguments.
1 | C:\>python |
Then, we get the following interactive interface with another command prompt.
Type in the following codes and press the Enter.
1 | >>> print("Hello, World!") |
We get the following output.
Run Python Programs
We also refer to any Python program as a script file that conventionally has the .py extension, e.g., my-script.py. Assume that we the codes as the content of the script file.
1 2 3 4 5 | print("The program has started...") print("Welcome to Turreta Python tutorial") print("The program is now exiting...") |
When we run the script using the following command on the MS-DOS command prompt, we get some lines of text.
1 | python my-script.py |
The command outputs the following.
1 2 3 | The program has started... Welcome to Turreta Python tutorial The program is now exiting... |
Python Identifiers
A Python identifier is a name we give a function, variable, class, module, or other objects. It can start with a letter or an underscore (_) followed by letters, underscores, and digits from 0 to 9. Consider the following valid Python identifiers.
1 2 3 | _this_is_valid this_is_still_valid this0123456789isvalid |
Moreover, Python identifiers are case-sensitive. The following identifiers are not the same.
1 2 3 | This_Is_Valid this_is_valid |
When coding in Python, we can follow some conventions for identifiers.
- When naming classes, start their names start with uppercase letters. For naming other identifiers, begin with lowercase letters.
- Starting an identifier with a single leading underscore indicates that the identifier is private.
- Starting an identifier with two leading underscores indicates a resolutely private identifier.
- If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
Python Reserved Words
Python reserved words are built-in keywords that we cannot use as identifiers.
False | continue | if | return |
None | def | import | try |
True | del | in | while |
and | elif | is | with |
as | else | lambda | yield |
assert | except | nonlocal | |
async | finally | not | |
await | for | or | |
break | from | pass | |
class | global | raise |
Lines and Indentation
Many know Python for its non-usage of braces to create blocks of code. Instead, we need to use indentations. Therefore, the syntax for blocks requires the usage of indentations.
The indentation can vary but must be consistent within to make the block of codes standout. Consider the codes below. It has two blocks – if and else blocks, which we nested within the main block. The main block is a group of codes that has zero indentation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Zero indentation true_or_false = False # Zero indentation if true_or_false: # 4 spaces for indentation print("Value is True") print("") else: # 4 spaces for indentation print("Value is False") # Zero indentation print("This does not belong to any code blocks") |
To illustrate better the blocks, the following image should paint enough words.
Moreover, a block must have at least one line of Python codes. If we mess up the indentation resulting in an empty block, we get an error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Zero indentation true_or_false = False # Zero indentation if true_or_false: # Now with zero spaces for indentation print("Value is True") print("") else: # Now with zero spaces for indentation print("Value is False") # Zero indentation print("This does not belong to any code blocks") |
The error is as follows.
1 2 3 4 5 | C:\>python main.py File "main.py", line 8 print("Value is True") ^ IndentationError: expected an indented block |
What about multi-line statements? In Python, we can break a line of code into multiple lines using the line continuation character (\). The special character does not violate the rigid rule of indentation. Consider the following codes that we slightly modified.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # Zero indentation true_or_false = True # Zero indentation if true_or_false: # 4 spaces for indentation print("Value is True") print("") sum = 1 \ + 2 \ + 3 \ + 4 \ + 5 print("sum is " + str(sum)) else: # 4 spaces for indentation print("Value is False") # Zero indentation print("This does not belong to any code blocks") |
These codes will run without any error, as shown below.
1 2 3 4 | Value is True sum is 15 This does not belong to any code blocks |
How about spitting the lines on a functions’ commas? Let us try that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | def myfunction(em, e): print(str(em) + " & " + str(e)) # Zero indentation true_or_false = True # Zero indentation if true_or_false: # 4 spaces for indentation print("Value is True") print("") sum = 1 \ + 2 \ + 3 \ + 4 \ + 5 myfunction(2, 4) print("sum is " + str(sum)) else: # 4 spaces for indentation print("Value is False") # Zero indentation print("This does not belong to any code blocks") |
These codes, too, will run successfully. Cool, no? If we can do something like that on function calls, we can also do the same on array literals.
1 2 | user_options = ['Yes', 'No'] |
1 | 'Thursday', 'Friday'] |
Syntax For String Literals in Python
How do we create strings literals in Python? There are three ways! One, using single quotations.
1 | just_saying = 'Is Python cool?' |
Second, using double quotations.
1 | just_saying_again = "I doubt that" |
Third, using triple quotations which allows us to span the string literal over multiple lines.
1 2 3 4 5 6 7 8 9 10 | multi_line_text = """ "Human" I'm only human Of flesh and blood I'm made Human Born to make mistakes """ |
With the three quotations, the string can both have single and double quotes within it without any issue in the codes. So, when we run those codes above, we get the following output.
Comments in Python
There are two ways to write comments in Python – using a hash sign (#) and a pair of triple single quotes. Consider the following codes that have comments using hash sign symbols.
1 2 3 | print("Start") # this is a single-line comment print("End") |
The Python interpreter will not consider comments are codes to compile and run. Same with comments using a pair of three single quotations.
3 4 5 | ''' This is my comment about Python ''' |
Thank you for reading!
This Python’s Basic Syntax post is part of The Big Fat Serpent – A Python 3 Tutorial.