Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
if 5 > 2: print("Five is greater than two!")
Five is greater than two!
Python will give you an error if you skip the indentation:
# Syntax Error: if 5 > 2: print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.
You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:
# Syntax error if 5 > 2: print("Five is greater than two!") print("Five is greater than two!")
Note: You have to use either tabs or spaces to indent. You can choose which to use, but you can't mix both.
Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it, and data type is determined automatically.
x = 5 y = "John" a = b = 3 print(x) print(y) print(a) print(b)
5 John 3 3
String variables can be declared either by using single or double quotes:
x = "John" # is the same as x = 'John'
Variables do not need to be declared with any particular type and can even change type after they have been set.
x = 4 # x is of type int x = "Sally" # x is now of type str print(x)
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:
You can ask for user input by using the
username = input("Enter username:") print("Username is: " + username)