Table of contents
1.
Introduction
2.
Python
3.
Python Syntax
3.1.
Python Variables
3.2.
Keywords
3.3.
Identifiers
3.4.
Comments
4.
Continuation of statements
5.
Quotations in Python
6.
Multiple Statements on a Single Line
7.
Execute Syntax
7.1.
Interactive Mode
7.2.
Script Mode
8.
Python Indentation
9.
Examples
9.1.
Check out this article - String slicing in Python
10.
Frequently Asked Questions
10.1.
Name some popular python frameworks.
10.2.
Name some common data types in Python.
10.3.
What is pip in Python?
10.4.
Is python a compiled or interpreted language?
10.5.
How to define a Python function?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Python Syntax

Author Komal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Welcome, Ninjas! Are you familiar with the Python language? Do you know about its features and syntax? Don’t worry; we got you covered.

python syntax
 

This blog will introduce the python language and its features, followed by the python syntax. We will also look into a few examples. 

Also see, Swapcase in Python, and  Convert String to List Python

Python

Let’s begin by introducing Python to familiarize you with it. 

python logo

Python is an open-source, interpreted high-level language. It is developed by Guido van Rossum. It is a dynamically typed language, i.e., the variables are assigned types at runtime. Python consists of various standard libraries such as machine learning and Open CV. Python finds various applications in Web Development, Machine Learning, desktop applications, etc. 

Python Syntax

Syntax, in simple terms, refers to the rules or instructions. Python Syntax refers to the rules used to write a python program to execute properly. Before executing a python program and looking into python syntax, let’s look at some basic python terms.

Python Variables

Variables are the named memory locations. Variables are used to store values of different data types. We can store integer values, characters, strings, bool values, etc.

Unlike other languages like C++ or Java, Python is a dynamically typed language, meaning the python variables are assigned a type at runtime. We do not give Python Variables a type when we initialize them. We simply write the variable name and the value we are initializing it to.

In this example, we first initialize the variables containing values of different types. Then we find their types using the type() function.

Example

#initializing the variables
index=4
str='Coding Ninjas'
value='a'
flag=True

#printing the type of data the variables are storing
print(type(index))
print(type(str))
print(type(value))
print(type(flag))
You can also try this code with Online Python Compiler
Run Code

 

Output

<class 'int'>
<class 'str'>
<class 'str'>
<class 'bool'>

Keywords

Keywords are reserved words that can not be used as the variable names. The keywords in python are represented as follows:

False None True and as assert
async await break class continue def
del elif else except finally for
from global if import in  is
lambda nonlocal not or pass raise
return try while with yield  

 

In python, we can print all the keywords as shown below.

Example

import keyword
#printing the list of keywords
print(keyword.kwlist)
You can also try this code with Online Python Compiler
Run Code

 

Output

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

 

What happens when we use the keyword name as a variable name?

It will give an ‘invalid syntax’ error, as shown below.

Example

#using keyword name 'pass' as a variable name
pass=20
You can also try this code with Online Python Compiler
Run Code

 

Output

SyntaxError: invalid syntax 

Identifiers

Identifiers, as the name suggests, help identify the variables by giving a name to them. Variables are the memory locations, and the names of those memory locations are called identifiers.  

Certain rules are followed for giving an identifier to a variable. 

They are as follows:

  • Identifiers are case sensitive, i.e., Codingninjas and CodingNinjas are different.
     
  • We cannot use keywords as identifiers.
     
  • An identifier can be a combination of alphabets, digits, and underscore. The first letter of the identifier can not be a digit.
     
  • There cannot be spaces while naming identifiers. E.g., Maximum Value =20; here, Maximum Value cannot be an identifier as it has spaces in between. Instead, we can use an underscore, ‘Maximum_Value’.
     

Some examples of identifiers are as follows:

  • helloWorld
     
  • Hello99
     
  • _codingninjas
     
  • Ninja123478coding
     
  • coding_ninjas2
     

Comments

Comments are sentences written along with the code, but they are not a part of the program when executed. Comments are written to explain the code you are writing. Comments in python always begin with a '#’.

In the following example, we have written a comment to let the user or the client know we are initializing a variable and then printing it.

Example

# initializing a variable
a=20
#printing the variable
print(a)
You can also try this code with Online Python Compiler
Run Code

 

Output

20

 

Multiline Comments can be written with the help of 3 single inverted commas.  Let’s have a look at an example to show how to write multiline comments.

Example

'''
printing
Coding Ninjas
'''
print("Coding Ninjas")
You can also try this code with Online Python Compiler
Run Code

 

Output

Coding Ninjas

Continuation of statements

We can write a single python statement by breaking it into multiple statements. We can make use of ‘/’-slash, ‘( )’ - paranthesis, ‘{ }’- braces, ‘[ ]’ - square brackets and  ‘;’ - semicolon for doing that.

The following example shows that the word “hello” can be printed by splitting it into multiple lines/statements with the help of a ‘\’

Example

word="h\
e\
l\
l\
o"

print(word)
You can also try this code with Online Python Compiler
Run Code

 

Output

hello 

 

The following example shows that the word “hello” can be printed by splitting it into multiple lines/statements with the help of a ‘( )’.

Example

word=('h'
'e'
'l'
'l'
'o')

print(word)
You can also try this code with Online Python Compiler
Run Code

 

Output

hello

Quotations in Python

For writing a string in python, we can use single inverted commas, double inverted commas or triple inverted commas as long as the string ends with the same type of quotes. Note that the triple inverted commas are used for writing multi-line strings.

The following example shows the use of single, double and triple quotes.

Example

str1='hello'
str2="coding ninjas"
str3='''welcome to
coding ninjas'''

print(str1)
print(str2)
print(str3)
You can also try this code with Online Python Compiler
Run Code

 

Output

hello
coding ninjas
welcome to
coding ninjas

Multiple Statements on a Single Line

We usually write single statements on a single line. But what if we want to write multiple statements on a single line, how can we differentiate between the two statements? 

In python, we can write multiple statements on a single line by terminating each statement with a semicolon. Let us look at an example for the same.

Example

a=10; print(a);
You can also try this code with Online Python Compiler
Run Code

 

Output

10

 

In the following example, we are initializing the variables a and b and printing c in the same line with the help of semicolons.

Example

a=10; b=20; c=a+b; print(c);
You can also try this code with Online Python Compiler
Run Code


Output

30

Execute Syntax

Python can be run either in Interactive mode or Script mode.

Interactive Mode

In Interactive mode, python is run at the command prompt only. You can invoke the python interpreter by typing python in your command prompt and pressing enter.

Example

You can start writing your Python Code here. For example, let’s print “Welcome to Coding Ninjas Studio”.

print(“Welcome to Coding Ninjas Studio”)
You can also try this code with Online Python Compiler
Run Code

 

Output

Welcome to Coding Ninjas Studio

 

Script Mode

We can write the python code in a simple text file, save it with the extension ‘.py’, and then run it in our python interpreter. 

We have saved the below python script with the name cn.py.

#file is saved by the name cn.py
print("Welcome to Coding Ninjas Studio")
You can also try this code with Online Python Compiler
Run Code

 

To execute the program; first, we get to the directory containing the program and then invoke the interpreter by writing python file_name. In this case, we type python cn.py.

Example           

cd directory_name (in which you are storing the file cn.py)
python cn.py

 

Output

Welcome to Coding Ninjas Studio

Python Indentation

In coding languages, we usually use braces to indicate code blocks or functions. In Python, we don’t use braces to indicate code blocks. Instead, we use indentation and whitespace. 

We can use any variable number of spaces for an indentation. But for a particular code block, all the statements within it should be indented by the same amount. Let’s have a look at an example.

In this example, we have initialised x to a value of 20 and in the if loop, we are printing ‘x is greater than 18’ and incrementing it by 1 if x is greater than 18.

Example

x=20
if(x>18):
    x=x+1
    print("x is greater than 18")
You can also try this code with Online Python Compiler
Run Code

 

Output

x is greater than 18

 

Note that both the statements in the if statement are indented by the same amount. 

What if we write the code like this. In the following example, we have not indented the statements by the same amount.

Example

x=20
if(x>18):
      x=x+1
    print("x is greater than 18")
You can also try this code with Online Python Compiler
Run Code

 

Output

IndentationError: unindent does not match any outer indentation level

 

This code results in the IdentationError because the amount of indentation in the statements within the if block is not the same. 

Examples

Let us look at some more examples.

Example-1

The following example shows how to use a multiline comment. It also prints “Hello, World!”.

'''using
multiline
comment
'''
print("Hello, World!")
You can also try this code with Online Python Compiler
Run Code

 

Output

Hello, World!

 

Example-2

The following example has three variables a, b & c. The if statement compares the variables and prints the output accordingly.

a="Coding"
b="Ninjas"
c="Coding"
if(a==b):
    print("a & b are equal")
elif(a==c):
    print("a & c are equal")
else:
    print("All variables are different")
You can also try this code with Online Python Compiler
Run Code

 

Output

a & c are equal

 

Example-3

In the following example, we are running a loop for i=0 to i=9 and printing the output as i+1. 

#running a loop
for i in range(10):
    print(i+1)
#coming out of the code block by changing the amount of indentation
print("Hello")
You can also try this code with Online Python Compiler
Run Code

 

Output

1
2
3
4
5
6
7
8
9
10
Hello

 

Check out this article - String slicing in Python

Frequently Asked Questions

Name some popular python frameworks.

Some of the popular python frameworks are Django, Flask, etc.

Name some common data types in Python.

Some common data types in Python include integers, strings, floating point numbers, sets, lists, etc.

What is pip in Python?

Pip is a package manager for Python. It is used to install, upgrade, or manage Python packages and their dependencies.

Is python a compiled or interpreted language?

Python is an interpreted language.

How to define a Python function?

We define Python function using the def keyword.

Conclusion

We discussed the python syntax. Firstly, we introduced you to the Python language. Then we moved to the topic of python syntax, including variables, comments, etc. We finally concluded the blog on python syntax by looking at some examples.

If you found this blog interesting and insightful, refer to similar blogs:

Refer to the Basics of C++ with Data StructureDBMS, and Operating System by Coding Ninjas, and keep practicing on our platform Coding Ninjas Studio. You can check out the mock test series on code studio.

You can also refer to our Guided Path on Coding Ninjas Studio to upskill yourself in domains like Data Structures and AlgorithmsCompetitive ProgrammingAptitude, and many more! Refer to the interview bundle if you want to prepare for placement interviews. Check out interview experiences to understand various companies' interview questions.

Give your career an edge over others by considering our premium courses!

Live masterclass