codescracker
python

Python Basic Syntax



Basic syntax of a Python program means rules to define the correct structure of statements and expressions used in that program. Therefore, under this section, we look up the basic structure of a Python program. Or how a Python program can be written to produce effective output.

Unlike most other programming languages like C, C++, Java etc. Python provides little simple syntax to work on. That is, to print Hello World in Python, we need to write only this single statement:

print("Hello World")

Note - Even semicolon does not require to put at last of the statement. This is the very simple structure of Python.

Since I've written above program in PyCharm IDE. Therefore after executing the above program, here is the output produced:

python basic syntax

Whatever the IDE you use, the output will be Hello World.

While learning about the basic syntax of Python or the basic structure of a Python program, the main thing to look up is the indentation of program. So let's talk about it.

Indentation is Most Important

Now the question is, what is indentation ?
The answer is, indentation refers to the spaces available/given at beginning of a statement in Python program. Before going deep into it, let's take a look at the program given below:

val = 10
if val>0:
    print("Positive")
elif val<0:
    print("Negative")

The above program can also be written as:

val = 10
if val>0:
 print("Positive")
elif val<0:
 print("Negative")

Both the program produces same output, that is:

python basic syntax example

Note - The number of space(s) to give before the statement, is up to you/programmer, but the statement needs to be in its same block of code.

The program given below produces error:

val = 10
if val>0:
    print("Positive")
elif val<0:
print("Negative")

The error produces by above Python program is only due to its indentation as shown in the snapshot given below:

python read user input

The following program also produces indentation error:

val = 10
if val>10:
    print("Positive")
        print("The value is", val)

The above program should be structured in this way:

val = 10
if val>0:
    print("Positive")
    print("The value is", val)

The output produced by above program is:

structure of python program basic syntax

Note - Whatever the space you provide, the space must be same for the same block of code.

You can refer to get user input from user in Python to get every required things on receiving any user inputs at run-time of the program with step by step description.

More Examples

Python Online Test


« Previous Tutorial Next Tutorial »



© Copyright 2021. All Rights Reserved.

CodesCracker