Python syntax is like grammar for this programming language. Syntax refers to the set of rules that defines how to write and organize code so that the Python interpreter can understand and run it correctly. These rules ensure that your code is structured, formatted, and error-free.
Here are some basic Python syntax:
Indentation in Python
Python Indentation refers to the use of whitespace (spaces or tabs) at the beginning of code line. 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 indentation error.
Python
if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")
Python Variables
Variables in Python are essentially named references pointing to objects in memory. Unlike some other languages, you don't need to declare a variable's type explicitly in Python. Based on the value assigned, Python will dynamically determine the type.
In the below example, variable 'a' is initialize with integer value and variable 'b' with a string. Because of dynamic-types behavior, data type will be decide during runtime.
Python
a = 10
print(type(a))
b = 'GeeksforGeeks'
print(type(b))
Python Identifiers
In Python, 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.
- 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.). For instance, "for", "while", "if", and "else" are keywords and cannot be used as identifiers.
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
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.
Single line comments are preceded by the "#" symbol. Everything after this symbol on the same line is considered a comment.
Python
first_name = "Reddy"
last_name = "Anna" # assign last name
# print full name
print(first_name, last_name)
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
'''
Multi Line comment.
Code will print name.
'''
f_name = "Alen"
print(f_name)
Multiple Line Statements
Writing a long statement in a code is not feasible or readable. Breaking a long line of code into multiple lines makes is more readable.
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)
OutputThis is a very long sentence that we want to split over multiple lines for better readability.
45
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
]
print(numbers)
Explicit Continuation
You can use backslash '\' to indicate that a statement should continue on the next line.
Python
# Explicit continuation
s = "GFG is computer science portal " \
"by Geeks, used by Geeks."
print(s)
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.
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:
Peter
Hello, Peter!
Similar Reads
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
6 min read
Python vs Cpython
Python is a high-level, interpreted programming language favored for its readability and versatility. It's widely used in web development, data science, machine learning, scripting, and more. However, Cpython is the default and most widely used implementation of the Python language. It's written in
4 min read
Python Quiz
These Python quiz questions are designed to help you become more familiar with Python and test your knowledge across various topics. From Python basics to advanced concepts, these topic-specific quizzes offer a comprehensive way to practice and assess your understanding of Python concepts. These Pyt
3 min read
Python Course Syllabus
Hereâs a straight-to-the-point breakdown of what a python course covers from the basics to advanced concepts like data handling, automation and object-oriented programming. No fluff, just the essentials to get you coding fast. Getting Started with Python ProgrammingWelcome to the getting started wit
6 min read
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
7 min read
What's the Zen of Python?
Whether you come from a strong programming background or are just a beginner, you must be aware of Python programming language because of its attractive syntax, ease of reading, and simplicity; which most developers use across the globe today. A collection of aphorisms known as "The Zen of Python" e
9 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Python 101
Welcome to "Python 101," your comprehensive guide to understanding and mastering the fundamentals of Python programming. Python is a versatile and powerful high-level programming language that has gained immense popularity due to its simplicity and readability. Whether you're an aspiring programmer,
14 min read
Python Version History
Python, one of the most popular programming languages today, has a rich history of development and evolution. From its inception in the late 1980s to its current status as a versatile and powerful language, Python's version history reflects the language's adaptability and the community's dedication
5 min read
What is setup.py in Python?
Introduction In Python, setup.py is a module used to build and distribute Python packages. It typically contains information about the package, such as its name, version, and dependencies, as well as instructions for building and installing the package. This information is used by the pip tool, whic
3 min read