Python Basic Syntax With Examples And PDF

What is basic syntax in Python?

The basic syntax in Python refers to the set of rules and structures that govern how you write and format code in the Python programming language.

There are two different types of modes of programming in Python:

  1. Interactive Mode Programming
  2. Script Mode Programming

1. 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.

Example:

# Python Interactive Mode Programming
>>> print ("Hello, Python!");

Output:

# Result when you run the command
Hello, Python!

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.

Example:

For example, let’s write a straightforward Python application in a script. In the test.py file that you have created, type in the following source code:

# Inside the test.py file
print ("Python is FUN!")

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

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

Output:

# Result when you run the command
Pytho is FUN!

In order for you to test your Python code provided in this lesson, you must test the code on your code editor like PyCharm.

But if you wish to run this code online, we also have an Online Compiler in Python for you to test your Python code for free.

Now, here are some key elements of the basic syntax for Python:

Python Identifiers

An identifier in Python is a name that can be used to point to a variable, function, class, module, or other objects.

Here are some rules for naming Python identifiers:

  • You are not allowed to use reserved keywords or else it will throw SyntaxError.
  • You can’t name an identifier using numbers only.
  • You can’t start an identifier name with a number.
  • The first letter of a class name is always capitalized. All the other identifiers start with a small letter.
  • Identifiers are case-sensitive, "abc" and "ABC" are different identifiers.
  • 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 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.

Falseclassfinallyisreturn
Nonecontinueforlambdatry
Truedeffromnonlocalwhile
anddelglobalnotwith
aselififoryield
assertelseimportpass
breakexceptinraise

Lines and Indentations

The Lines and Indentations are white spaces in code lines. Python’s indentation is important, while indentation in other programming languages is just used to improve readability.

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.

Example:

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():

Quotation in Python

In Python, string objects are made with quotation marks. Python can read strings with one, two, or three sets of quotes.

Python supports three kinds of quotation marks:

  • 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 to create a multi-line comment in the comments section.

In Python, strings are declared with single and double quotes.

Newline Character in Python

The newline character in Python is the n character which is used to start a new line.

This character tells the computer that the end of a line has been reached, and any more characters will be printed on a new line.

Example:

sample1 = "This is an example\nThis is the sentence with new line."
print(sample1)

Output:

This is an example
This is the sentence with new line.

Comments in Python

A line of text that occurs in a program but is not executed by the program is referred to as a comment in Python. Comments in Python start with the # sign.

They can go at the start of a line, after a blank space, or after some code. If a string literal has the # character, it is part of the string.

Example:

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

This leads to the following:

Python is Fun!

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 line”, 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.

Multiple Statements on a Single Line

To write multiple statements in a single line in Python, you have to use the semicolon (;).

A semicolon lets you put more than one statement on one line, as long as none of the statements start a new code block.

Example:

Here is an example of how to use a semicolon:

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

Command Line Arguments

Command Line Arguments refer to the arguments given after the program’s name in the command line shell of the operating system.

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.

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.

Download Python Basic Syntax PDF

You can download the Python Basic Syntax PDF file by clicking the download button below:

Summary

In Python syntax, we covered interactive and script modes in this tutorial.

We talked about identifiers, keywords, lines and indentation, multi-line statements, quotes, comments, blank lines, user input, and command-line parameters.

I hope that this Python Basic Syntax helps you understand the basics of Python and how to write and execute a Python program.


Leave a Comment