Python was created with to goal of making code more readable to the user. To accomplish this, most syntax that programmers are used to can be removed in favor of indentation. For example, Python does not require a semicolon after every line.
x=5
y=10
print(x+y)
Conditions
Python also removes various formatting components such as parenthesis and brackets. Here is a sample condition in Python.
if x>=0:
print("your number is positive")
else:
print("your number is negative")
Notice how all components of the condition are indented. Python will assume that all indented lines are part of the same condition statement. Since indentation is already a common practice in clean code, Python makes your code more simple and readable while keeping its functionality. However, be aware that bad indentation could put the functionality of your code at risk.
Boolean Operators
In Python, boolean values always begin with an uppercase letter (True or False). Additionally, all logical operators use the words associated with them instead of symbols.
x=True
y=False
print(x and y) #returns False. note how the word "and" is used instead of the typical "&&".
print(x or y) #returns True. Python uses "or" instead of "||".
print(x and not y) #returns True.
All comparison operators (==, !=, >, >=, etc.) remain the same.
elif... Statement
In order to shorten code, python uses the phrase "elif" instead of "else if". here is an example:
if x>0:
print("positive")
elif x=0:
print("zero")
else:
print("negative")
Match-Case Statement
Python also has a Match-Case statement, whoich is very similar to a switch statement in other programming languages. This statement evaluates a variable based on the provided "cases". Here is an example:
match x: #x is the variable being evaluated
case 1:
#this code will run if x=1
case 2:
#this code will run if x=2
case _:
#this is the default case.
#It will run if x does not meet any of the conditions above.
Loops
The range() Method
Python does not use a traditional for loop found in most languages. Instead, all for loops are in the format of a for-each loop. To get around this, python programmers use the range() method. This method has one required parameter (start) and two optional parameters (stop, step). The range method returns a list of all numbers beginning at "start" and ending before "stop". Here are some examples of how this method is used to create a loop:
for x in range(5):
#this loop has one parameter, which indicates a stop value of 5.
#since no start value is given, the loop begins at 0.
#since no step value is given, the loop will increment by 1.
for y in range (2, 6):
#this loop has two parameters, a start and a stop value.
#it will loop through all integers beginning at 2 and ending at 5.
for z in range (0, 11, 2):
#this loop will iterate through all numbers from 0 to 10 in increments of 2.