Python Syntax
The syntax of Python serves as the language's grammar, comprising a collection of guidelines that dictate how code should be crafted and structured, enabling the Python interpreter to accurately comprehend and execute it. Adhering to these guidelines guarantees that the code is composed correctly, organized logically, and free from errors. As a robust, high-level programming language, Python features an uncomplicated and exceptionally readable syntax, which contributes to its widespread popularity among both novices and experienced developers.
First Program in Python
We will now examine a fundamental Python program that outputs "Hello, world!" in two distinct modes:
- Interactive Mode
- Script Mode
Python Interactive Mode
To utilize the Python interpreter via the command line, you can effortlessly initiate it by entering 'python', as demonstrated 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 syntax provided above, the symbol >>> represents the Python Command Prompt, which is the interface where we can input our commands. Now, let's create a straightforward command to display "Hello, World!" in the Python prompt and then hit Enter.
Example
>>> print("Hello, World!")
Output:
Hello, World!
Python Script Mode
An alternative approach to utilizing the Python Interpreter is through the Python Script mode. In this mode, the code is authored within a .py file and subsequently run from the command prompt. Now, let’s create a basic syntax to display "Hello, World!" using 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
In Python, variables serve the purpose of holding data values. In contrast to many other programming languages, Python does not necessitate an explicit type declaration for its variables; they are dynamically typed. This characteristic implies that the variable's type is established during runtime, depending on the value that is assigned to it.
Let's explore a straightforward example that illustrates how to declare variables in Python.
Example
# initializing variables
a = 10
print(a, '->', type(a))
b = 'Example'
print(b, '->', type(b))
Output:
10 -> <class 'int'>
C# Tutorial -> <class 'str'>
Explanation:
In the preceding example, we have established two variables that possess distinct data types. It is evident that we have not specified their data types explicitly.
For further information regarding Variables and their corresponding data types in Python, please refer to - Python Variables and Python Data Types.
Indentation in Python
Python employs indentation to delineate blocks of code, in contrast to other programming languages like C or Java that utilize curly braces {}. This use of indentation not only improves the readability of the code but also serves as an essential aspect of Python's syntax. It is imperative that every block of code—including loops, functions, and conditionals—is consistently indented to the same degree.
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 preceding example, the if statement has been utilized to assess whether 9 exceeds 5. If this condition evaluates to true, the code lines that are indented will be executed.
An IndentationError will be triggered if the indentation is not done correctly. Maintaining appropriate indentation is crucial for preserving the logical framework of the code.
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
In Python, keywords are specific reserved terms that cannot be utilized as identifiers for variables. Some examples of these keywords are: if, else, while, for, def, class, import, among others.
| 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
In Python, comments are employed to clarify code and enhance its readability. They assist other programmers in grasping the intent behind the code and act as a reference for the individual who wrote it. The Python interpreter disregards comments, which implies that they do not influence the program's execution.
Below is an illustration that demonstrates various forms of comments utilized in Python programming.
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 preceding example, any line that is preceded by the # character is recognized as a comment. Consequently, this line is disregarded by the interpreter. Additionally, comments that span multiple lines and are enclosed within triple quotes are frequently referred to as docstrings.
For additional information regarding Comments, please refer to - Python Comments
Multiline Statements in Python
Creating lengthy statements within code can lead to decreased readability, which is considered poor practice. To mitigate this issue, we can divide an extensive line of code into several lines. This can be achieved either explicitly by utilizing a backslash (\) or implicitly by employing parentheses .
In Python, the backslash character (\) serves as a unique symbol that denotes line continuation. This feature enables developers to break lengthy lines of code into several lines, enhancing readability while ensuring that the execution of the code remains unaffected.
Let us examine the subsequent example that demonstrates the functionality of the backslash (\) character 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:
Explanation:
In the preceding illustration, we employed the backslash (\) to divide an extended line of code into several lines to enhance the clarity and readability of the code.
For additional information regarding multiline statements, please refer to - Multi-Line Statements in Python.
Taking Input from User in Python
In Python, the function input is utilized to capture input from the user. Regardless of whether the user inputs a numerical value, the data is always obtained in the form of a string.
Let's examine the subsequent example that illustrates how to gather input from 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 preceding illustration, the input function has been utilized to gather input from the user.
Conclusion
The syntax of Python is straightforward, exceptionally legible, and mandates the use of indentation to organize code, which renders it accessible for novices while also being robust enough for experienced developers. Its adaptability, dynamic type system, and clean formatting contribute significantly to the effectiveness and upkeep of the code.
Python Syntax - FAQs
1. What is Python syntax?
The syntax of Python encompasses a collection of guidelines that determine the manner in which Python code is composed and organized. This includes aspects such as indentation, keywords, statements, and expressions.
2. How is indentation used in Python?
In Python, indentation—whether using spaces or tabs—is employed to delineate blocks of code, contrasting with other programming languages that utilize curly braces {}. It is essential for each block to maintain a consistent level of indentation.
if True:
print("Indented block") # Correct
3. Are semicolons required in Python?
No, Python does not necessitate the use of semicolons to terminate statements. Nevertheless, they can be utilized to combine several statements within a single line.
a = 10; b = 20; print(a + b) # Not recommended
4. Is Python Case Sensitive?
Indeed, Python is sensitive to case. This implies that the variable 'fname' and 'Fname' are regarded as two distinct identifiers.
5. What are Python variables?
Variables are used to hold values and do not need a specific type to be defined explicitly.
x = 5 # Integer
name = "John" # String