Python reads closer to plain English than most languages, which is exactly why it is a common first language - but it still has real rules underneath that simplicity.
Variables need no type declaration
Unlike Java, Python figures out a variable's type automatically from the value you assign:
name = "Riya" # a string
age = 21 # an integer
price = 19.99 # a float
is_student = True # a boolean
Indentation is not optional
Python uses indentation (not curly braces) to define blocks of code. Get the indentation wrong and your program will not run - this trips up almost everyone in their first week:
if age >= 18:
print("You can vote") # this line must be indented
print("Welcome!") # so must this one
else:
print("Not yet")
if / elif / else
marks = 78
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
else:
print("Grade C or below")
Loops
# for: loop over a known range or collection
for i in range(5):
print("Count:", i)
# while: loop until a condition changes
attempts = 0
while attempts < 3:
print("Attempt", attempts)
attempts += 1
Python has no i++ shorthand - use i += 1 instead. This is a small but common trip-up if you are coming from another language.