The Wayback Machine - https://web.archive.org/web/20240907042252/https://www.geeksforgeeks.org/python-syntax/
Open In App

Python Syntax

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python is known for its clean and readable syntax, which makes it an excellent language for beginners, but also powerful enough for advanced applications. In this article, we will learn about the basic elements of Python syntax.

Prerequisites: Before diving into Python syntax, ensure you have:

  • Install Python (preferably Python 3.x).
  • A text editor or IDE (Integrated Development Environment) like VSCode, PyCharm, or even IDLE (Python’s built-in IDE).

What is Python Syntax?

Python syntax refers to the set of rules that defines the combinations of symbols that are considered to be correctly structured programs in the Python language. These rules make sure that programs written in Python should be structured and formatted, ensuring that the Python interpreter can understand and execute them correctly. Here are some aspects of Python syntax: Along with this article you can also go through our Free Python Course to understand the concept of Python Syntax.

Running Basic Python Program

There are different ways of running Python programs. Below are some of the most widely used and common ways to run the Python program.

Python Hello World

This is the simple printing of hello world program in Python.

Python
print("Hello, World!")

Output:

Hello, World!

Python Interactive Shell

  1. Start the Python interpreter by simply typing python (or python3 on some systems) in the terminal or command prompt. We can then run Python commands interactively.
  2. To exit, we can type exit() or press Ctrl + D.

Example of Python Interactive Shell

Screenshot-2023-10-11-135100

Running a Python Script

Create a script with the .py extension, e.g., Namaste.py.

Screenshot-2023-10-11-135421

Run it from the terminal or command prompt using: python script.py (or python Namaste.py).

Screenshot-2023-10-11-135608

Indentation in Python

Python Indentation refers to the use of whitespace (spaces or tabs) at the beginning of a line of code in Python. It is used to define the code blocks. Indentation is crucial in Python because, unlike many other programming languages that use braces “{}” to define blocks, Python uses indentation. It improves the readability of Python code, but on other hand it became difficult to rectify indentation errors. Even one extra or less space can leads to identation error.

Python
if 10 > 5:
    print("This is true!")

if 10 > 5:
    print("This is true!")

Python Variables

Variables in Python are essentially named references pointing to objects in memory. Unlike some other languages, in Python, you don’t need to declare a variable’s type explicitly. Based on the value assigned, Python will dynamically determine the type. In the below example, we create a variable ‘a’ and initialize it with interger value so, type of ‘a’ is int then we store the string value in ‘a’ it become ‘str’ type. It is called dynamic typing which means variable’s data type can change during runtime.

Screenshot-2023-10-11-123058

Python Identifiers

In Python, identifiers are the building blocks of a program. Identifiers are unique names that are assigned to variables, functions, classes, and other entities. They are used to uniquely identify the entity within the program. They should start with a letter (a-z, A-Z) or an underscore “_” and can be followed by letters, numbers, or underscores. In the below example “first_name” is an identifier that store string value.

first_name = "Ram"

For naming of an identifier we have to follows some rules given below:

  • Identifiers can be composed of alphabets (either uppercase or lowercase), numbers (0-9), and the underscore character (_). They shouldn’t include any special characters or spaces.
  • The starting character of an identifier must be an alphabet or an underscore.
  • Certain words in Python, known as keywords, have specific functions and meanings. These words can’t be chosen as identifiers. For instance, “for”, “while”, “if”, and “else” are keywords and cannot be used as identifiers. Even though “print” is not a keyword, it is a built-in function, so it should not be used as an identifier to avoid conflicts.
  • Within a specific scope or namespace, each identifier should have a distinct name to avoid conflicts. However, different scopes can have identifiers with the same name without interference.

Python keywords

Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. They cannot be used as identifiers (names for variables, functions, classes, etc.). Below is the list of keywords in Python:

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

With different versions of Python some keywords may vary. We can see all the keywords of current version of Python using below code.

>>>import keyword
>>>print(keyword.kwlist)

Screenshot-2023-10-11-120355

Comments in Python

Comments in Python are statements written within the code. They are meant to explain, clarify, or give context about specific parts of the code. The purpose of comments is to explain the working of a code, they have no impact on the execution or outcome of a program.

Python Single Line Comment

Single line comments are preceded by the “#” symbol. Everything after this symbol on the same line is considered a comment and not considered as the part of execution of code. Below is the example of single line comment and we can see that there is no effect of comment on output.

Python
first_name = "Reddy"
last_name = "Anna"

# print full name
print(first_name, last_name)

Output
Reddy Anna

Python Multi-line Comment

Python doesn’t have a specific syntax for multi-line comments. However, programmers often use multiple single-line comments, one after the other, or sometimes triple quotes (either ”’ or “””), even though they’re technically string literals. Below is the example of multiline comment.

Python
# This is a Python program
# to explain multiline comment.

'''
Functions to print table of
any number.
'''
def print_table(n):
  for i in range(1,11):
    print(i*n)
    
print_table(4)

Output
4
8
12
16
20
24
28
32
36
40

Multiple Line Statements

Writing a long statement in a code is not feasible or readable. Writing a long single line statement in multiple lines by breaking it is more readable so, we have this feature in Python and we can break long statement into different ways such as:

Using Backslashes (\)

In Python, you can break a statement into multiple lines using the backslash (\). This method is useful, especially when we are working with strings or mathematical operations.

Python
sentence = "This is a very long sentence that we want to " \
           "split over multiple lines for better readability."

print(sentence)

# For mathematical operations
total = 1 + 2 + 3 + \
        4 + 5 + 6 + \
        7 + 8 + 9

print(total)

Output
This is a very long sentence that we want to split over multiple lines for better readability.
45

Using Parentheses

For certain constructs, like lists, tuples, or function arguments, we can split statements over multiple lines inside the parentheses, without needing backslashes.

Python
# Create list
numbers = [1, 2, 3,
           4, 5, 6,
           7, 8, 9]

def total(num1, num2, num3, num4):
  print(num1+num2+num3+num4)
  
# Function call
total(23, 34,
      22, 21)

Output
100

Triple Quotes for Strings

If we are working with docstrings or multiline strings, we can use triple quotes (single ”’ or double “””).

Python
text = """GeeksforGeeks Interactive Live and Self-Paced
Courses to help you enhance your programming.
Practice problems and learn with live and online
recorded classes with GFG courses. Offline Programs."""

print(text)

Output
GeeksforGeeks Interactive Live and Self-Paced
Courses to help you enhance your programming.
Practice problems and learn with live and online
recorded classes with GFG courses. Offline Programs.

Quotation in Python

In Python, strings can be enclosed using single (‘), double (“), or triple (”’ or “””) quotes. Single and double quotes are interchangeable for defining simple strings, while triple quotes allow for the creation of multiline strings. That we have used in above example. The choice of quotation type can simplify inserting one type of quote within a string without the need for escaping, for example, using double quotes to enclose a string that contains a single quote. Below is the example of using single and double quotes.

Python
# Embedded single quote inside double.
text1 = "He said, 'I learned Python from GeeksforGeeks'"

# Embedded double quote inside single.
text2 = 'He said, "I have created a project using Python"'

print(text1)
print(text2)

Output
He said, 'I learned Python from GeeksforGeeks'
He said, "I have created a project using Python"

Continuation of Statements in Python

In Python, statements are typically written on a single line. However, there are scenarios where writing a statement on multiple lines can improve readability or is required due to the length of the statement. This continuation of statements over multiple lines is supported in Python in various ways:

Implicit Continuation

Python implicitly supports line continuation within parentheses (), square brackets [], and curly braces {}. This is often used in defining multi-line lists, tuples, dictionaries, or function arguments.

Python
# Line continuation within square brackets '[]'
numbers = [
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
]

# Line continuation within parentheses '()'
result = max(
    10, 20,
    30, 40
)

# Line continuation within curly braces '{}'
dictionary = {
    "name": "Alice",
    "age": 25,
    "address": "123 Wonderland"
}

print(numbers)
print(result)
print(dictionary)

Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
40
{'name': 'Alice', 'age': 25, 'address': '123 Wonderland'}

Explicit Continuation

If you’re not inside any of the above constructs, you can use the backslash ‘\’ to indicate that a statement should continue on the next line. This is known as explicit line continuation.

Python
# Explicit continuation
s = "GFG is computer science portal " \
    "that is used by geeks."

print(s)

Output
GFG is computer science portal that that is used by geeks.

Note: Using a backslash does have some pitfalls, such as if there’s a space after the backslash, it will result in a syntax error.

Strings

Strings can be continued over multiple lines using triple quotes (”’ or “””). Additionally, if two string literals are adjacent to each other, Python will automatically concatenate them.

Python
text = '''A Geek can help other
Geek by writing article on GFG'''

message = "Hello, " "Geeks!"

print(text)
print(message)

Output
A Geek can help other
Geek by writing article on GFG
Hello, Geeks!

String Literals in Python

String literals in Python are sequences of characters used to represent textual data. Here’s a detailed look at string literals in Python. String literals can be enclosed in single quotes (‘), double quotes (“), or triple quotes (”’ or “””).

Python
string1 = 'Hello, Geeks'
string2 = "Namaste, Geeks"

multi_line_string = '''Ram learned Python
by reading tutorial on
GeeksforGeeks'''

print(string1)
print(string2)
print(multi_line_string)

Output
Hello, Geeks
Namaste, Geeks
Ram learned Python
by reading tutorial on
GeeksforGeeks

Command Line Arguments

In Python, command-line arguments are used to provide inputs to a script at runtime from the command line. In other words, command line arguments are the arguments that are given after the name of program in the command line shell of operating system. Using Python we can deal with these type of argument in various ways. Below are the most common ways:

Example: In this example we write the program to sum up all the numbers provided in command line. Firstly we import sys module. After that we checks if there are any numbers passed as arguments. Iterates over the command-line arguments, skipping the script name i.e. “sys.argv[0]” and then converts each argument to a float and then add them. We have used try-except block to handle the “ValueError”.

Python
import sys

# Check if at least one number is provided
if len(sys.argv) < 2:
    print("Please provide numbers as arguments to sum.")
    sys.exit(1)  # Exit with an error status code

try:
    # Convert arguments to floats and sum them
    total = sum(map(float, sys.argv[1:]))
    print(f"Sum: {total}")
except ValueError:
    print("All arguments must be valid numbers.")

Output
Please provide numbers as arguments to sum.

Output: In the output we can see that the program returns the total of numbers passed as an arguments.

Screenshot-2023-10-12-123142

Taking Input from User in Python

The input() function in Python is used to take user input from the console. The program execution halts until the user provides input and presses “Enter”. The entered data is then returned as a string. We can also provide an optional prompt as an argument to guide the user on what to input.

Example: In this example, the user will see the message “Please enter your name: “. After entering their name and pressing “Enter”, they’ll receive a greeting with the name they provided.

Python
# Taking input from the user
name = input("Please enter your name: ")

# Print the input
print(f"Hello, {name}!")

Output:

Please enter your name:
Sagar
Hello, Sagar!


Similar Reads

Python - Pie Syntax (@)
A decorator, is a callable that is used to extend the functionality of other callables. In simple words, It allows you to "decorate" a function with another function. The "@" symbol in this context is sometimes referred to as Pie Syntax to a decorator. The pie syntax makes it more easy to access and extend. Since, we already had decoration with sta
2 min read
Python2 vs Python3 | Syntax and performance Comparison
Python 2.x has been the most popular version for over a decade and a half. But now more and more people are switching to Python 3.x. Python3 is a lot better than Python2 and comes with many additional features. Also, Python 2.x is becoming obsolete this year. So, it is now recommended to start using Python 3.x from now-onwards. Still in dilemma? Ev
4 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
What is Python Used For? | 7 Practical Python Applications
Python is an interpreted and object-oriented programming language commonly used for web development, data analysis, artificial intelligence, and more. It features a clean, beginner-friendly, and readable syntax. Due to its ecosystem of libraries, frameworks, and large community support, it has become a top preferred choice for developers in the ind
9 min read
Python Foreach: How to Program in Python
In many programming languages, the foreach loop is a convenient way to iterate over elements in a collection, such as an array or list. Python, however, does not have a dedicated foreach loop like some other languages (e.g., PHP or JavaScript). In this article, we will explore different ways to implement a foreach-like loop in Python, along with ex
3 min read
How to Install python-dotenv in Python
Python-dotenv is a Python package that is used to manage &amp; store environment variables. It reads key-value pairs from the “.env” file. How to install python-dotenv?To install python-dotenv using PIP, open your command prompt or terminal and type in this command. pip install python-dotenvVerifying the installationTo verify if you have successful
3 min read
Practice Tags :