Python Basic Syntax Definition and Examples

Python Basic Syntax

In this article, we will learn the Basic Syntax of Python. Python shares numerous similarities with Perl, C, and Java. Nonetheless, there are distinct differences between the languages. Python Basic Syntax is one of the fundamental criteria for writing code in Python.

In Python, the code block is represented by indentation. We must adhere to certain guidelines about the usage of indentation. Not only must we adhere to rules about indentation, but also the naming of variables.

What is Python Syntax?

Python syntax is the set of rules that describe how a Python program is written and executed (by both the runtime system and by human readers). Python shares numerous similarities with Perl, C, and Java.

When talking about a programming language, syntax is a set of rules for grammar and spelling. In other words, it means using character structures that a computer can figure out. For example, if a user tries to run a command without using the right syntax, it causes a syntax error, which usually makes the program stop working.

First Python Program

Let’s understand how to write and run a simple first Python program before we move on to learning its syntax. So there are two different types of modes of programming in Python.

Python's "if not" syntax explained ...
Python's "if not" syntax explained with examples.

Interactive Mode Programming

Interactive mode is a command-line shell that provides an instant response for each statement while executing previously issued commands in active memory. If you run the interpreter without passing a script file as a parameter, you’ll see the following prompt:

#Python 2.4.3 Version
C:\Users>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

#Python 3.9.13 Version
C:\Users>py
Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

At the Python prompt, type the following text and press Enter.

#Python 2.4.3 Version
>>> print "Hello, Python!"

If you are running a new version of Python, you must use the print statement surrounded by parentheses, as in print (“Hello, Python! “);.

#Python 3.9.13 Version
>>> print ("Hello, Python!");

But this leads to the following result in Python versions 2.4.3 and 3.9.13:

#Result on both Python 2.4.3 and 3.9.13
Hello, Python!

You can test the above example here:

Script Mode Programming

The Script Mode Programming, the Python code is written into a file. The Python interpreter reads the file, then runs it and gives the desired result. The program is put together in the command prompt. The interactive mode is better for writing short programs.

Let’s try our hand at writing a straightforward Python application in a script. The extension .py is used for Python files. In the test.py file that you have created, type in the following source code:

#Inside the <em>test.py </em>file
print "Hello, Python!"

We assume that the PATH variable contains the Python interpreter. Now, try running this program this way:

#command prompt or shell - running a Python 2.4.3
C:\Python Tutorial>python test.py

Here’s what happened when the Python command above was run:

#Result on Python 2.4.3
Hello, Python!

Python Identifiers

The first part of our Python Basic Syntax lesson is Identifiers. An identifier in Python is a name that can be used to point to a variable, function, class, module, or other objects. An identifier starts with a letter from A to Z, a to z, or an underscore (_). It is then followed by zero or more letters, underscores, and numbers (0 to 9).

Python doesn’t let you use punctuation marks like @, $, and % in identifiers. Python is a programming language that cares about cases. So, in Python, “Manpower” and “manpower” are not the same thing.

Here are some rules for naming Python identifiers:

  • The first letter of a class name is always capital. All the other identifiers start with a small letter.
  • If an identifier starts with a single underscore, it means that it is a private identifier.
  • When an identifier starts with two underscores, it means that it is very private.
  • If the end of the identifier also has two underscores, it is a language-defined special name.

Python Keywords

The Python keywords are shown in the list below. These are reserved words, which means you can’t use them as names for constants, variables, or anything else. There are no capital letters in any of the Python keywords.

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield
Python Keywords

Python Basic Syntax – Lines and Indentation

The first spaces in code lines are referred to as indentation. Python’s indentation is important, while indentation in other programming languages is just used to improve readability. A block of code is indicated by an indentation in Python.

The number of spaces in the indentation can vary, but all of the statements in a block must have the same number of spaces in the indentation. Let’s look at a simple example to see how the indentation works.

def sample_function():
    print("Hello, Python!")
    if True:
        print("Hi")
    else:
        print("Bye!")

print("Python is Fun!")

We’re not going to talk about the code and what it does. Instead, let’s look at the different levels of indentation.

# Functions
def sample_function():

It shows where the function starts, so every line of code that belongs to the function needs to be indented by at least one level. Notice that the print statements and the if statements are set back at least one level. But what about the last statement that says “print”? We can see that it is not part of the function because it is not indented at all.

Now, let’s go inside the function block, which is every statement that is at least one level away from the beginning of the function.

The first print statement is one level indented because it is only under the function and not under any other loop or condition. The second print statement, on the other hand, is part of the if statement.

if True:
    print("Hi")

The if statement is only indented one level, but any block of code that needs to be written under it should be indented one level more than the if statement. The same is also for the else statement.

Now, we have to follow certain rules when we indent code in Python. These are:

  • The backslash (“/”) character cannot be used to split an indentation into two or more lines.
  • If you try to indent the first line of code in Python, an IndentationError will be thrown. You can’t make the first line of code look different.
  • If you use a tab or a space to indent your code, it’s best to stick with the same spacing preference for the rest of your code. Don’t use a mix of tabs and whitespaces, because that could cause the wrong indentation.
  • For the first level of indentation, it is best to use 1 tab (or 4 whitespaces), and for each level after that, add 4 whitespaces (or 1 tab).

Python code looks better and more organized when it is indented. It gives you a good idea of how the code works with just one look. Also, the rules for indenting are simple, and if you’re writing code on an IDE, most of them will do it for you automatically.

One problem with indentation is that it can be hard to fix even a single line’s indentation mistake if your code is long and has a lot of different levels of indentation.

Let’s look at some indentation mistakes to make sure you understand.

>>>     p = 5
  File "<stdin>", line 1
    p = 5
IndentationError: unexpected indent

As we’ve already talked about, we can’t indent the first line, so we get an IndentationError.

if True:
    print("Inside True Statement")
     print("Will throw error because of extra whitespace")
else:
    print("False")

An IndentationError will be raised because the second print statement uses a single indent but contains whitespace that is not permitted in Python.

if True:
print "True"
else:
print "False"

IndentationError will be thrown because the print statements inside the if and else are not indented by one level.

#Error Message from  Python
IndentationError: expected an indented block

Multi-Line Statements

Explicit line continuation

The backslash (\) operator, which is also called an explicit line continuation, can be used to split a long line of code into several shorter lines that are easier to read. For example,

total = item_one + \
item_two + \
item_three

Implicit line continuation

When you break up a statement with parentheses (), square brackets [], or curly braces {}, this is called implicit line continuation. You need to put the goal statement inside the given structure. For example,

months = ['Jan', 'Feb', 'Mar', 
'Apr', 'May']

Python Basic Syntax Quotation

In Python, string objects are made with quotation marks. Python can read strings with one, two, or three sets of quotes. String literals are made by putting a string of characters inside single quotes (‘hello’), double quotes (‘hello’), or triple quotes (“‘hello”‘ or “””hello”””).

There are three kinds of quotation marks that Python can understand.

  • single (‘)
  • double (“)
  • triple (”’ or “””)

They let the string go across more than one line. For instance, the following are all legal:

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

The triple quotation marks have already been used in the comments section. In Python, strings are declared with single and double-quotes.

Python Basic Syntax Comments

A line of text that occurs in a program but is not executed by the program is referred to as a comment in Python. A hashtag (#) can be used to announce a comment.

A new line of code or the end of an existing line of code can both contain comments. Code is explained through comments, which are also used for testing. All characters after the # and up to the end of the physical line are part of the comment, and the Python interpreter doesn’t care about them.

# First comment
print ("Python is Fun!") # Second comment

This leads to the following:

Python is Fun!

After a statement or expression, you can type a comment on the same line:

company = "ITSOURCECODE" # This is again comment

You can comment on more than one line in the ways below:

# First comment
# Second comment
# Third comment
# Fourth comment

The Python interpreter also doesn’t care about the following triple-quoted string, which can be used as a multiline comment:

'''
This is a multiline
comment.
'''

Using Blank Lines

A line that only has whitespace on it, possibly with a comment, is called a “blank lines,” and Python doesn’t care about it at all.

To end a multiline statement in an interactive interpreter session, you must type an empty line.

Waiting for the User

The waiting for the user (wait for the user) is an input from the user that invokes the program to proceed to the next statement. This waiting for the user in Python 2 is different from Python 3. In Python 2, uses raw_input() while in Python 3 uses input().

The next line of code shows the prompt, which says “Press the enter key to continue.” and waits for the user to do something.

# Python 2
raw_input("\n\nPress the enter key to continue.")

# Python 3
input("\n\nPress the enter key to continue.")

In this case, “\n\n” is used to make two new lines before the actual line is shown. The program ends when the key is pressed. This is a good way to keep a console window open until an application is finished.

Multiple Statements on a Single Line

To write multiple statements in a single line in Python, you have to use the semicolon (;). Semicolon lets you put more than one statement on one line, as long as none of the statements start a new code block. Here is an example of how to use a semicolon:

# using semicolon
import sys; x = 'foo'; sys.stdout.write(x + '\n')

Multiple Statement Groups as Suites

In Python, suites are a group of individual statements that make up a single block of code. Statements with more than one part, like if, while, def, and class, need a header line and a suite.

Header lines start the statement (with the keyword) and end with a colon (:). One or more lines that make up the suite come after the header lines. For instance,

if expression :
suite
elif expression :
suite
else :
suite

Python Basic Syntax Command Line Arguments

Command Line Arguments refers to the arguments given after the program’s name in the command line shell of the operating system. We use command line arguments to keep our program’s nature as general as possible.

For example, if we wrote a program to read a CSV file, entering a CSV file from the command line would make our program work for any CSV file, making it generic.

Our program is also safer because of the command-line arguments. How? We need to put some login information into the code so that we can use it somewhere else. If we put them in the script, anyone can see them and even run them. On the other hand, it’s safer if we use the command line to enter the login information.

So, how do we pass arguments on the command line in Python?

It’s simple. You need to run the python script from the terminal the way we talked about at the beginning of the article and then add the inputs.

# argument sample
python test_file.py arg1 arg2 … arg N

Here, test_file.py is the name of the script, and arg1 through argN are the N arguments that must be given on the command line.

You must be wondering how one could read the command line arguments. The most common way is to use the sys module.

You can also set up your script so that it will accept different choices. Command Line Arguments is a more advanced topic that you should study after you’ve learned the rest of our Python Tutorial.

Summary

In summary, there are two ways to write and run Python programs: the interactive mode and the script mode. And in this tutorial, we talked about the following: The identifiers, keywords, lines and indentation, multi-line statements, quotes, comments, blank lines, waiting for the user, multiple statements on a single line, groups of multiple statements called suites, and command-line arguments.

In the next tutorial, you will learn about the Python Variable Types. I hope that this Python Basic Syntax helps you understand how to write and execute a Python program.


Leave a Comment