Python Syntax with Examples

FREE Online Courses: Enroll Now, Thank us Later!

Like any other programming language, Python has a set of rules. These rules define how to write a program in that language. It also explains how the interpreter understands the code. These rules are set on the runtime system and followed by the person writing the code.  Let’s take a look at some of the basic syntax for python.

What does “syntax” mean in Python?

The rules that define the structure of the language for python is called its syntax.  Without this, the meaning of the code is hard to understand. These include the usage of symbols, punctuations, words and how you should use them while you code in the language.     

Example of Python syntax

num=int(input("Please enter a number"))
if num>18:
    print("The number is greater than 18")
elif num<18:
    print("The number is less than 18")
else:
    print("The number is equal to 18")

Output:

Case 1: Number less than 10
Please enter a number
10
The number is less than 18
Case 2: Number greater than 10
Please enter a number
20
The number is greater than 18
Case 3: Number is equal to 18
Please enter a number
18
The number is equal to 18

Python Identifiers

The name you use to identify a function, module, class, variable, or any other object is called an Identifier. 

There are certain rules for creating these identifiers:

  • The identifier can start with a letter: A-Z or a-z.
  • It can start with the underscore character.
  • It cannot start with a number or any other special character.
  • The identifier can contain only alpha-numeric characters and underscore provided it does not start with a number.
  • And the variables are case sensitive so Apple and apple are two different variables.

Python also has rules that help describe the variable. 

  • While naming a class variable, the variable starts with an uppercase letter followed by all lowercase letters.
  • While naming a language-defined special name, the variable ends with two underscores. 
  • When naming a private variable, the variable starts with a single underscore.
  • While naming a strongly private variable, the variable starts with two underscores. 

Reserved keywords in Python

These are special keywords that python has reserved for specific functions. They provide certain predefined functionalities. They can be constants or variables or any other identifier. But once you set it as a constant or variable, the predefined function doesn’t work.

Hence, it is better to not use these keywords as constants or variables or any other identifier name. Here is the list of some of these reserved keywords:

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

Lines and Indentation in Python

Programming languages like C, Java and  C++ use brackets to show blocks of code.

In Python, you do not need to use braces or semicolons to say blocks of code. You state this using indentation.

While using indentation in Python the thumb rule followed is-

The block of code starts with the indentation and ends with the first unintended line. This indentation must be consistent throughout that block.

Example of use of Indentation in Python

num=int(input("Please enter a number \n"))
sum=0
for i in range(0,num):
    sum=sum+i
print("the total sum is",sum)

This shows an example with a correct indentation in Python.

Here you see that after each conditional statement there is a colon and the next line has an indentation. The basic rule is there has to be at least one space, you can have more, which is up to you as a programmer.  

Output

Please enter a number 
10
the total sum is 45

The output shows what happens when you run the code. When the indentations are correct, the code works perfectly and the IDLE shell pops up.  

Python End of Statements 

When you want to end a statement in python, you do not need to add a special character to specify the end.

Here you press enter to start a new statement. 

Example of EOL error

a=10
b=20
sum
=
a
+
b
print("a=",a)
print("b=",b)
print("sum=",sum)

Since each new line is a new line of code, running the code will throw an error message stating “invalid syntax”  as shown in the figure below.

Python Syntax

Once you fix this code, it will look something like this:  

Example of Code with correct EOL syntax

a=10
b=20
sum=a+b
print("a=",a)
print("b=",b)
print("sum=",sum)

Output

a= 10
b= 20
sum= 30

Multi-Line Statements in Python

Now that we have gone through how ending a line works, what do you do when you have to work with code that is too large to fit in one line or print statements that are too big to fit in one line. 

Generally, to enhance readability, you limit the length of any single line of code to 79 characters. So let us look at how to deal with lines of codes that have more than 79 characters. 

To split a line of code and state that the next line is not a new line, you use a backslash. 

Example of multi lines code

a=10
b=20
c=30
sum=a+\
     b+\
     c
print("a=",a)
print("b=",b)
print("c=",c)
print("sum=",sum)

Output

a= 10
b= 20
c= 30
sum= 60

The example above shows you how to write a line of code on multiple lines using a backslash. Here each time you use a backslash, python interprets it as a continuation of the previous line and not a new line. 

Example of Python multi-lines on print statements

print(\
    "Hello\
    Welcome\
    To\
    PythonGeeks")

Output 

Hello    Welcome    To    PythonGeeks

The example above shows how you would use the backslash for a print statement. Here, each time you have to print something with a lot of characters you can use the backslash like before. 

Quotation in Python

Quotations in python help distinguish between a word, a sentence, and a paragraph.

Example of Quotations in python

word = ‘PythonGeeks’

sentence = “Welcome to PythonGeeks”

paragraph = “‘Welcome to PythonGeeks, You are learning Python Syntax”‘

When you are defining a word or want to print a word using print statements, you define them by single quotations ‘ ‘

When defining a sentence, you use double quotes to define a sentence “ “.

And when defining a paragraph, you use triple quotes to do so as shown in the example above.

Blank Lines in Python

Python interpreters ignore any blank lines that you have left.

Comments in Python

When you’re coding in python, comments help explain the line of code. It provides insight into what the program is about and how it works. 

Example of comments in python

word=’PythonGeeks’  #This is a word

sentence=”Welcome to PythonGeeks”  #This is a sentence

paragraph=”‘Welcome to PythonGeeks, You are learning Python Syntax”‘ #This is a paragraph

The example above shows how comments work in python. To add a comment to your code you use a hashtag (#)  followed by the comment using Blank Lines.

Multiple Statements in a Single Line in Python

When you want to write multiple statements in a single line you use semicolons(;). 

Example of defining multiple variables in a single line in Python

a=10;b=20;c=30
sum=a+b+c
print("a=",a);print("b=",b);print("c=",c);print("sum=",sum)

The example above shows how you can compact your code. Instead of using 3 different lines to define a,b,c you use one line and separate each variable definition with a semicolon(;). 

Output 

a= 10
b= 20
c= 30
sum= 60

Python Docstrings

Python documentation strings (or docstrings) are an easy way for programmers to define the function, module, method, and class in Python. 

Example of Docstrings in Python

side=int(input("enter the side of the square\n"))
def areasquare(side):
    ''' Takes in the length of the side of the square as input and calculates the area'''
    print("The area of the square is", side**2)
areasquare(side)

You write the definition or the documentation string in triple-double quotes as shown in the example above

Output 

enter the side of the square
4
The area of the square is 16

Variables in Python

When you want to store values in a memory location in python, you use python variables. In python, you do not have to define the variable based on the data type, the python interpreter does it on its own. The interpreter also decides where to allocate the memory based on the data type. 

Example of variable definition in python

a=20
b=1.2
c="PythonGeeks"
d= True
print("The datatype of a is",type(a))
print("The datatype of b is",type(b))
print("The datatype of c is",type(c))
print("The datatype of d is",type(d))

Output

The datatype of a is <class ‘int’>
The datatype of b is <class ‘float’>
The datatype of c is <class ‘str’>
The datatype of d is <class ‘bool’>

The example above shows how to define a variable and in the output, you will see that the interpreter has automatically allocated the variable. The data type for each variable is also identified automatically.

String Formatting in Python

1. Format Method in Python

The format method in python lets you print statements with identifier values of your choice. Whereas each point you would want the value printed you put 0,1,2,.. in curly braces.

Example of format method in python:

a=10
b=20
sum=a+b
print("the sum of {0} and {1} is {2}".format(a,b,sum))

Output 

the sum of 10 and 20 is 30

2. F-strings in Python

It can be used for print statements as well. 

Example of F-strings  in python

a=10;b=20;sum=10+20
print(f"the sum of {a} and {b} is {sum}")

The example shows how to use f-strings. Wherever you would like to specify the variable values, use the curly braces and write the variable name. The variable value is printed where the variable name is specified as shown below.

Output

the sum of 10 and 20 is 30

3. % Operator in Python

It allows you to specify where you would like the values of identifiers to be printed.

Example of % operator  in python

a=10
b=20
sum=a+b
print("the sum of %s and %s is %s"% (a,b,sum))

The example shows the use of the % operator in python. Here the %s is the location where the identifier value gets displayed. 

Output

the sum of 10 and 20 is 30

Multiple Statement Groups as Suites in Python

In Python, individual statements grouped together make a single code block. These are called suites. To create a suite for cases like if, while, def, and class statements, we require a header line and a suite. 

Example of Suites in python

num=int(input("enter a number"))
sum=0
for i in range(0, num):
    sum=sum+i
print("the sum is",sum)
if sum>20:
    print("the sum is greater than 20")
elif sum<20:
    print("the sum is less than 20")
else:
    print("the sum is equal to 20")

The example shows the use of multiple lines to form a suite. Here the if, ifelse, else and print statements are different lines of code that together form one suite.   

Output

enter a number 10
the sum is 45
the sum is greater than 20

Python wait time

When you want to print statements after a certain time, you use the wait time function in Python. 

Example of wait time in python

import time
print('Hello, Welcome to PythonGeeks')
print('the next message will be printed in 3 seconds’)
time.sleep(3)
print('\n\nSleep time was 3 seconds')

The example above will print the first 2 print lines. The time.sleep function sets the time waited before printing the third print statement.

Output:

Hello, Welcome to PythonGeeks
the next message will be printed in 3 seconds
Sleep time was 3 seconds’

Frequently asked questions on Python Syntax

Q1. What rules should be followed when creating identifiers

Ans 1. They are a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore “ _ “.

You cannot start with a digit.

It is advised not to use reserved words or keywords as identifiers

Q2. What is the error in the following code?

fruit=
“mango”
print("fruit=",  fruit)

Ans 2. The above code will provide an EOL error.

Q3. How to write one statement or a line of code in multiple lines, give an example?

Ans 3. In python, pressing enter indicates the start of a new line. Hence, you cannot split a statement just using enter. 

You use a backslash (\) at the end of each line to indicate that the statement is continued on the next line.

For Example:

print(\
    "Hello\
    world")

Q4. What will the output be for the following code?

def findsqr(a):
sqr=a**2
return sqr

Ans 4. This code is not properly indented. Hence, the interpreter will consider each line to be a new line and not as a block of code.

Q5. Why do we use docstrings in Python, give an example?

Ans 5. DocStrings in python help majorly when multiple people are working on the same code or use the code. They help define the function, module, method and class that is being used and created.

For Example:

 def findsum(a,b):
        ''' Takes in a and b as input and calculates the sum'''
        total=a+b
        return total

Summary 

In this article, we looked at the basics of python and python syntax. We considered different rules that you should follow, why these rules are important and how to use them in your code. We have also looked at different ways you can work with the python programming language. 

Did you like this article? If Yes, please give PythonGeeks 5 Stars on Google | Facebook


5 Responses

  1. NUR AHMED says:

    Very informative.

  2. Morgan says:

    I love this comment, It truely provides an informational summary of how someone might reply to this Website.

  3. Zakir says:

    Very easy to learn, thanks for the way of teaching.

    I want to know the syntax to print the words of a number

    Thanks

  4. GOVT.HSS EXE.DINDORI says:

    pooja

Leave a Reply

Your email address will not be published. Required fields are marked *