Comparison Operators
These operators can be used during a comparison e.g. when implementing selection.
Operator |
Meaning |
== |
Equal |
!= |
Not Equal |
> |
More Than |
< |
Less Than |
>= |
More Than Or Equal |
<= |
Less Than Or Equal |
1
2
|
# This is a comment on a whole line
a = "Hi" # This is a comment at the end of a line
|
Variables
Variables allow a value to be stored in memory. Python does not require a specific type to be defined during declaration.
1
2
|
a = "I am a string!"
count = 4
|
Output
Displaying a message in the terminal can be handled via the “print” method.
1
2
3
4
5
6
7
8
9
10
11
|
# Output by passing by value
print("Hello World!")
# Output by passing a single argument
message = "Hi"
print(message)
# Output by passing multiple arguments
a = "Hello"
b = "World!"
print(a, b)
|
Input from the user can be captured via the “input” method.
1
2
3
4
5
|
# Ask for user input with a message
name = input("Enter Your Name: ")
# Ask for user input with no message
name = input()
|
Selection
Selection is handled in Python using “if statements”.
- Only the first expression that is TRUE will execute
- There must be at least an “if” statement to include “elif” or “else”
- “elif” statements can allow for multiple selections
- “else” does not require a expression, it will only run when all other expressions are FALSE
- “elif” expressions can only be after an “if”
- An “else” statement can only be added at the end
1
2
3
4
5
6
|
if <comparision>:
...
elif <comparision>:
...
else:
...
|
Example Program:
1
2
3
4
5
6
7
8
|
name = "Steve"
if name == "Leo":
...
elif len(name) == 3:
...
else:
...
|
Iteration
For
A for loop allows to iterate over a sequence of values.
1
2
3
4
5
6
7
8
9
|
message = "Welcome"
# Iterate using range
for i in range(len(message)):
print(i)
# Iterate over items
for character in message:
print(character)
|
While
A while loop allows for a condition to be checked before each iteration.
1
2
3
4
5
6
|
message = "Welcome"
i = 0
while i != len(message):
print(i)
i = i + 1
|