Syntax of Python
Syntax of Python involves indentation and it is highly important since it does not make use of curly braces to mark a block of code (line of statements that are executed together), variables, comments, etc.
Python uses indentation to indicate a block of code, unlike C++ and Java, which uses a set of curly braces. Indentation implies spaces at the start of a line of code. It is important to note that at least there should be 1 number of spaces in indentation and be same for the lines that make up a block of code. If no indentation is given or wrong indentation is given to a block of code, then Python raises exception for the same.
# Python program to exemplify indentations var1 = 10 var2 = 11 if var1 > var2: print(var1,"is greater than", var2) else: print(var1,"is less than", var2)
10 is less than 11
# Python program to exemplify indenatation mistakes var1 = 11 var2 = 10 #indentation is not given if var1 > var2: print(var1,"is greater than", var2) #different indentation is given if var1 > var2: print(var1,"is greater than", var2) print(var1,">", var2)
In the example provided above, errors that may arise with wrong or no indentation is shown. In the first if, there is not indentation and in the second if, statements of its block of code are not provided with equal indentations. Both of these cases are inacceptable by the Python interpreter and will raise exception.
File "main.py", line 5 print(var1,"is greater than", var2) ^ IndentationError: expected an indented block
Variables in Python do not need to be declared or provided with any type that would tell the kind of data it will store. Data type of a variable is set when a value is assigned to it. If it is an integer value, then the type of the variable is number and if it is assigned a string of characters placed inside quotes, then the type of the variable is string and so on. And value to a variable is assigned using assignment operator which is “=”.
# Python program to exemplify variables #store number in the variable 'var_number' var_number = 14 print(var_number) #store text in the variable 'var_text' var_text = 'StudyExperts!' print(var_text) #store sequence in the variable 'var_seq' var_seq = [1, 5, 3, 2] print(var_seq)
14 StudyExperts! [1, 5, 3, 2]
Comments in a program are added to ensure that it is comprehensible. It is included with the purpose of in-code documentation. They start with # and end with the end of line in Python.
Example: Python Syntax of Comments
# Python program to exemplify comments # This is a comment in Python print('StudyExperts!.')