Open In App

Python Syntax

Last Updated : 01 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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.

Python
first_name = "Reddy"
last_name = "Anna"  # assign last name

# 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
'''
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)

Output
This 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.

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:
Peter
Hello, Peter!

Next Article
Practice Tags :

Similar Reads