Python allows a user to perform interactive mode programming which involves executing a program by writing directly in the command line. To start interactive programming, call the python interpreter without passing a script file as mentioned below:
After this, a program can be directly written and executed in the command line. In the below example, print "Hello World!." program is written and executed directly in the command line.
In Python, a user can also do script mode programming which involves writing and saving a program as a python script and running it in the command line. The file extension of a python script is .py. In the below example, print "Hello World!." program is saved as test.py and executed in the command line by calling it.
This will produce the result as shown below:
Unlike C++ and Java which uses { } to indicate a block of code, Python uses indentation. Indentation means spaces at the start of a line of code. In the below example, if block of code has used two spaces as indentation.
a = 100 b = 10 if a > b: print(a,"is greater than", b) else: print(a,"is less than", b)
100 is greater than 10
The number of spaces in indentation should be at least one and it should be fixed inside a block of code. In the below example, first if block of code has used two spaces as indentation and second if block of code has used four spaces as indentation.
a = 100 b = 10 if a > b: print(a,"is greater than", b) if a > b: print(a,">", b)
100 is greater than 10 100 > 10
Python raises exception if the indentation is not given or different indentation is given to a block of code. In the below example, first if block of code has not used any indentation and second if block of code has used different indentation (two spaces and four spaces).
a = 100 b = 10 #indentation is not given if a > b: print(a,"is greater than", b) #different indentation is given if a > b: print(a,"is greater than", b) print(a,">", b)
IndentationError: expected an indented block IndentationError: unexpected indent
Unlike other programming languages, Python does not require to declare a variable or its data type. The data type of a variable is set when a value is assigned to it. To assign a value(s) to the variable, = operator is used.
#store number in the variable 'x' x = 15 print(x) #store text in the variable 'y' y = 'Hello' print(y) #store sequence in the variable 'z' z = [1, 2, 3] print(z)
15 Hello [1, 2, 3]
The Comments are added in programming code with the purpose of in-code documentation. It makes the code more readable and hence easier to update the code later. It starts with # and ends with the end of that line. Anything after # to the end of the line is a single line comment and will be ignored by the compiler.
The below example shows how to use comments in the Python. Comments are ignored by the compiler while running the code.
# first line comment print('Hello World!.') # second line comment
Hello World!.