Python Syntax acts as grammar, with the set of rules defining the way of writing and organizing code so that the Python interpreter can understand and execute it properly. These rules ensure that the code is well-written, structured, and error-free. Python, being a powerful, high-level programming language has a simple and highly readable syntax, making it a popular choice for beginners and professionals alike.
First Program in Python
We will now look at the basic Python program to print “Hello, world!” in two different modes:
- Interactive Mode
- Script Mode
Python Interactive Mode
We can use Python interpreter from command line by simply typing ‘python’ as shown below:
Syntax:
C:\> python
Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
In the above syntax, >>> denotes a Python Command Prompt where we can type the commands. Let us now write a simple syntax to print “Hello, World!” in Python prompt and press Enter.
Example
>>> print("Hello, World!")
Output:
Hello, World!
Python Script Mode
Another method to use Python Interpreter is by using the Python Script mode. In script mode the code is written in a .py file and then executed from the command prompt. Let us now write a simple syntax to print “Hello, World!” using the script mode and save it as sample.py.
Example
print("Hello, World!")
- Output:
$ python sample.py
Hello, World!
Different Aspects of Python Syntax:
The following are the different aspects of Python Syntax:
- Variables
- Indentation
- Identifiers
- Keywords
- Comments
- Multiline Statements
- Input from Users
Python Variables
Variables in Python are used to store data values. Unlike other languages, Python variables do not require explicit declaration of type; they are dynamically typed. This means that the type of variable is determined at runtime based on the value assigned to it.
Let us see a simple example showing the way of defining variables in Python.
Example
# initializing variables
a = 10
print(a, '->', type(a))
b = 'Learn Python App'
print(b, '->', type(b))
Output:
10 -> <class 'int'>
Learn Python App -> <class 'str'>
Explanation:
In the above example, we have defined two variables of different data types. As we can observe, we have not declared their data types explicitly.
To learn more about Variables and their data types in Python, visit – Python Variables and Python Data Types.
Indentation in Python
Python uses indentation to define blocks of code instead of using curly braces {} as in other languages like C or Java. Indentation enhances code readability and is a crucial part of Python syntax. Every block of code (such as loops, functions, and conditionals) must be indented at the same level.
Example
if 9 > 5:
print("9 is greater than 5") # proper indentation
print("This is part of the if block")
print("This is outside the if block")
Output:
9 is greater than 5
This is part of the if block
This is outside the if block
Explanation:
In the above example, we have used the if statement to check if 9 is greater than 5. If true, it will print the indented line of codes.
In case of improper indentation, it will raise an IndentationError. Proper indentation ensures the logical structure of the code is maintained.
Python Identifiers
Identifiers are names used for variables, functions, classes, and other entities in Python. They must follow specific rules to be valid:
- It can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
- It cannot start with a digit.
- We cannot use Python keywords as identifiers.
- Case-sensitive (MyVar and myvar are different identifiers).
- It should be descriptive and follow naming conventions (e.g., using snake_case for variables and functions and CamelCase for class names).
Python Keywords
Keywords are reserved words in Python that cannot be used as variable names. Examples include if, else, while, for, def, class, import, etc.
| False | None | True | and |
| assert | as | await | async |
| break | class | continue | def |
| del | elif | else | except |
| finally | for | from | global |
| if | import | not | in |
| return | yield | while | with |
| raise | or | pass | try |
| is | lambda | nonlocal | match |
| case |
To learn more about Keywords, visit – Python Keywords
Python Comments
Comments in Python are used to explain code and make it more readable. They help other developers understand the purpose of the code and serve as a reminder for the programmer. Comments are ignored by the Python interpreter, meaning they do not affect the execution of the program.
Here is an example showing different types of comments in Python.
Example
# This is a single-line comment
"""This is a multi-line comment.
It can span multiple lines.
"""
def addition():
# This is a comment inside a function
a = 10 # This is an inline comment
'''''This is a multi-line string, often used for documentation.
It can also serve as a multi-line comment.
'''
b = 14
print("Sum of a and b is", a + b)
addition()
Output:
Sum of a and b is 24
Explanation:
In the above example, the line followed by the # symbol is treated as comments. As a result, it is ignored by the interpreter. Moreover, the multiline comments declared using the triple quotes are often considered as docstrings.
To learn more about Comments, visit – Python Comments
Multiline Statements in Python
Writing a long statement in a code is not good practice causing unreadability. To prevent this, we can break the long line of code into multiple lines. This can be done either explicitly using backslash (\) or implicitly by parentheses ().
A backslash (\) in Python is a special character used to indicate line continuation. It allows long lines of code to be split across multiple lines for better readability without affecting the code’s execution.
Let us take a look at the following example showing how backslash (\) works in Python.
Example
# showing the use of backslash (\) to break
# the long line of code into multiple lines
total_cost = 25 + 58 + 92 + \
74 + 29 + 82 + \
51 + 99 + 12
print(total_cost)
Output:
522
Explanation:
In the above example, we have used the backslash (\) to split the long line of code into multiple lines in order to increase the readability of the code.
To learn more about multiline statements, visit – Multi-Line Statements in Python
Taking Input from User in Python
In Python, we use the input() function to take user input. The input is always received as a string, even if the user enters a number.
Let us see the following example showing how to take input from the users in Python.
Example
# taking input from user
fname = input("Enter your first name: ")
lname = input("Enter your last name: ")
print("Welcome,", fname, lname)
Output:
Enter your first name: Tony
Enter your last name: Prince
Welcome, Tony Prince
Explanation:
In the above example, we have used the input() function to take input from the user.
Conclusion
Python syntax is simple, highly readable, and enforces indentation for code structure, making it beginner-friendly yet powerful for professionals. Its flexibility, dynamic typing, and clear formatting enhance code efficiency and maintainability.
Leave a Reply