Python Syntax – Get yourself familiar with Python
Understanding the syntax is the first and most crucial step in learning any programming language. Python stands out for its simplicity and straightforward syntax, making it one of the most beginner-friendly languages. This article is designed to guide you through the essential syntactical structures of Python. Whether you’re just starting or looking to refresh your knowledge, this article will provide the foundation you need to write clean and efficient Python code.
TechVidvan’s Python Syntax article will help you in identifying and debugging the syntax of Python.
What is Syntax?
In every programming language, you will come along the word syntax. A programming syntax refers to a set of rules.
When we run a Python program, first it is read by a parser. The parser will only understand the Python code if it is according to the predefined rules of Python programming otherwise it will give you syntax errors. That is why it is important to understand the syntax of the language.
Example of Python Syntax
In this Python Tutorial, before learning the syntax of Python, let’s see an example of how a basic Python program looks like.
Code:
#Simple Python Program that compares two numbers. print("Enter first integer value") first_value = int(input()) print("Enter second integer value") second_value = int(input()) if(first_value > second_value): print(“First value is greater than second”) else: print(“Second value is greater than first”)
The above program takes two values from the user and then we compare which of them is bigger.
Don’t worry if you don’t understand the code yet, with this example, you can get a clue about how Python code is written.
Types of Syntax Structures in Python
Now, let’s go through the various syntax structures of Python programming.
1. Python Line Structure
A Python program is divided into logical lines where each line comprises one or more physical lines of code. The Python interpreter ignores the blank lines, which are the lines that only contain white spaces.
Code:
Msg = “Hi! Welcome to the python syntax article” print(Msg)
Output:
2. Multiline Statements
If you have studied another language like C/C++ or Java then you are used to writing semicolons after every statement.
In Python, we don’t use semicolons instead of them we use newlines for separating statements. Sometimes when you want to write a long code in a single line we can break the statement into multiple lines using the backslash character(\).
Code:
print(“Hi! \ How are you today? \ What are you planning this Sunday? \ ”)
Output:
3. Multiple Statements in One Line
Python also allows you to write multiple statements in a single line. For this purpose, we use semicolons to separate statements within the same line. This can reduce the readability of code so only use this if it is appropriate in the situation.
Code:
num1 = 10 ; num2 = 20 ; print(“Sum of numbers = ”, num1+num2)
Output:
4. Comments in Python
Writing comments for our code is useful for programmers to add notes or explanations of the code. Comments are just for reading and Python interpreter ignores whatever we write in comments. Comments can be either single-line or multiline comments.
a. Single-Line Comments
The symbol (#) indicates the starting of the comment and everything written after the # is considered as comment.
Code:
#Interpreter will ignore this print(“TechVidvan”) print(“TechVidvan”) #comments can be added after code
Output:
TechVidvan
b. Multiline Comments
When the comment is large, we can use the triple-double quotes to write comments in multiple lines.
Code:
“”” This is a multiline Comment Used for explaining functions, Codes, etc “”” print(“Multiline comment example”)
Output:
5. Python Indentation
The indentation is quite unique syntax of Python. Other languages like C/C++, Java and JavaScript use curly braces ‘{}’ to indicate block of codes.
Python uses white spaces (space or tabs) to define the block of functions, flow control and codes of class. It is mandatory to use a consistent amount of spaces for blocks throughout the code.
Let’s see this with an example:
Code:
name = “TechVidvan” if name == “TechVidvan”: print(“We know this person”) else: print(“We don’t know this person”)
Note: Here, the amount of space should be consistent otherwise you will get an error.
Code:
name = “TechVidvan” if name == “TechVidvan”: print(“We know this person”) print(“Unequal spaces in indentation”) else: print(“We don’t know this person”)
Output:
6. Python Quotations
The Python string literals can be enclosed in two ways.
We can write strings between single quotes(’) or double quotes (“) and they can be used interchangeably.
Code:
message1 = “Hey” message2 = ‘Hey’ print( message1) print( message2)
Output:
Hey
When we want to use quotes inside the string then we can combine them.
Code:
print(“ Hey ‘Anna’ ”) print(‘ Hey “Anna” ’)
Output:
Hey “Anna”
7. Python Identifier
A program contains variables, functions, classes, modules, packages etc. Identifier is the name given to these programming elements. There are some rules which we have to keep in mind for creating an identifier.
Let’s see them one by one.
- Identifier can only begin with characters starting from A-Z (Uppercase letters), a-z (lowercase letters) or _ (underscore).
- They can be then followed by any number of letters, digits or underscores.
- Python is case sensitive language so the identifiers ‘count’ and ‘Count’ are two different identifiers.
- Python Reserved keywords like for, global, continue, break, etc. cannot be used as identifiers.
Examples of Valid Identifiers:
- name
- _3name6
- get_all_names
- YES
Examples of Invalid Identifiers:
- 1name
- name$
- get-score
8. Getting Users Input
To get the input from the user, Python has input() function in the Python’s core library. It reads the input given by the user as a string and we can store the input in a variable.
Code:
Msg = input() print(Msg)
When the interpreter reaches the input() function, it will wait for an input from the user.
The user can give input, for example, here we can type “Hello” and then after pressing enter, the code will execute in which we store the input in Msg variable and print it afterwards.
Output:
‘Hello’
One important thing to note is that even when you give a number as input, Python will treat it as a string. So, when we want to work with numbers, we can use type conversion methods with input() function to convert strings into numbers.
Code:
num = int( input()) num = num + 10 print(num)
Output:
15
9. Python String-Formatters
String-formatters are very useful for displaying strings in the format we want. Let’s see the different ways of formatting string:
a. % operator
With the % operator, we can format a string to contain both text and values of identifiers. We use %s where we want our value to appear.
After the string, we put the % symbol and then mention the identifiers in parameters.
Code:
rollNo= 1 subject= “Maths” print(“ The roll no. %s studies %s subject” % (rollNo, subject) )
Output:
b. format Method
The format method is similar to the above method but instead of %s we put 0,1,2… values or identifiers in curly braces and then use format method on the string.
Code:
rollNo= 1 ; subject= “Maths” print(“ The roll no. {0} studies {1} subject”. format(rollNo, subject) ) print((“ The roll no. {rollNo} studies {subject} subject”.format(rollNo=10, subject=”Science”))
Output:
The roll no. 10 studies Science subject
c. f-strings
F-strings are easier to work with. You just need to put ‘f’ as a prefix before string and then you can put the identifier in curly braces within the string.
Code:
rollNo= 5 ; subject= “Biology” print( f“The roll no. {rollNo} studies {subject} subject” )
Output:
Summary
In this article, we saw all the Python syntax structures in detail. This will give a good idea about how programming in Python is done.
We learned the Python line structure, comments, Python indentation, identifiers, taking input from users and formatting strings.
Now you can start your journey in Python programming.
I hope you like this Python syntax tutorial and feel free to ask your queries in the comment section.