Understanding Variables and Data Types
A variable in Python is a place to store values that we need to access and modify. While
naming a variable is easy, there are some guidelines to follow:
• Variable names must start with a letter or an underscore (_). They cannot begin
with a number.
• They can contain underscores and alphanumeric characters (A-Z, 0-9, and _).
• Variable names are case-sensitive.
• In Python, reserved words (keywords) cannot be used as variable names.
Examples include "for," "while," "if," "else," "import," "pass," "break," etc.
• Python supports a variety of data types, however, the following are the most
popular:
Data Description Example
Types
‘int’ Whole numbers without a decimal point. 1, 2, 10, -15
‘float’ Real numbers that can have a decimal point. 3.14, -0.01, 8.76,
5.0
‘str’ Sequences of characters enclosed in either single "Hello, Python!",
quotes (' ') or double quotes (" "). It can contain letters, 'abc123', 'Python is
numbers, spaces and punctuation. fun!'
‘bool’ Boolean values, which can be either True or False. True, False
Often used in conditional expressions.
‘list’ Ordered and mutable collection of items. Values are [1, 'a', 3.14]
between square brackets.
‘tuple’ Ordered and immutable collection of items. Values are (1, 'a', 3.14)
between parentheses.
‘dict’ An unordered collection of data in a key: value pair {'name': 'John',
form. Used to store data values like a map. 'age': 26}
‘set’ An unordered collection of unique items. Values are {1,2,3}
separated by a comma inside braces { }.
Comparison Operators
These are used to compare values. It either returns True or False according to the
condition. They include equals (==), not equals (!=), greater than (>), less than (<),
greater than or equal to (>=) and less than or equal to (<=).
Assignment Operators
These are used to give variable values. Equals (=), plus equals (+=), minus equals (-=),
multiplication equals (*=), divide equals (/=), modulus equals (%=), floor divide
equals (//=), and exponent equals (**=) are among them.
a = 10
a += 2 # equivalent to a = a + 2
print(a) # Output: 12
Logical Operators
Logical operators are and, or, not operators.
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not b) # Output: True
Bitwise Operators
Bitwise operators conduct bit-by-bit actions on bits. Bitwise AND (&), OR (|), NOT (),
XOR (), right shift (>>), and left shift () are among them
a = 10 # in binary: 1010
b = 4 # in binary: 0100
print(a & b) # Output: 0 (0000 in binary)
print(a | b) # Output: 14 (1110 in binary)
print(~a) # Output: -11 (-(1011 in binary))
print(a ^ b) # Output: 14 (1110 in binary)
print(a >> 2) # Output: 2 (0010 in binary)
print(a << 2) # Output: 40 (101000 in binary)
Lists
A list in Python is a mutable and ordered collection of items, enclosed within square
brackets [].
Creating a List:
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
Accessing List Items:
print(fruits[1]) # Output: 'banana'
Modifying List Items:
fruits[2] = "mango"
print(fruits) # Output: ['apple', 'banana', 'mango']
Tuples
In Python, a tuple is comparable to a list, but it is immutable, which means that once
constructed, the things within it cannot be modified. Within parenthesis (), tuples are
defined.
Making a Tuple:
colors = ("red", "green", "blue")
print(colors) # Output: ('red', 'green', 'blue')
Accessing Tuple Items:
print(colors[2]) # Output: 'blue'
Note: Since tuples are immutable, we can't modify their items like we can with
lists.
Prepare to take command! Today we'll look at one of the most fundamental parts of
Python (and, indeed, any programming language): conditional statements.
Conditional statements are the foundation of Python decision-making. They enable
your program to respond differently to various conditions. How do they accomplish
this? By analyzing specific conditions and running different pieces of code based on the
outcome.
To generate these conditions, we use Python's 'if', 'elif' (short for else if),
and 'else' expressions. Here's a quick rundown:
• if: The `if` statement checks if a condition is `True`. If it is, Python executes the
code block that follows.
if weather == "rain":
print("Don't forget your umbrella!")
• elif: The `elif` statement is used to check for additional conditions if the
condition(s) before it is `False`.
elif weather == "sunny":
print("You might need sunglasses.")
• else: The `else` statement catches anything which isn't caught by the preceding
conditions.
else:
print("Have a great day!")
Loops come in handy when we need to execute a chunk of code repeatedly. To
tackle such recurring activities, Python has 'for' and 'while' loops.
For Loop
The `for` loop in Python is used to iterate over a sequence (such as a list, tuple,
dictionary, set, or string) or other iterable objects.
Example:
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Here, the `fruit` variable goes through each element in the `fruits` list, printing each
one in turn.
While Loop
The `while` loop in Python is used to execute a block of statements repeatedly until a
given condition is true. When the condition becomes false, the line immediately after
the loop is executed.
Example:
# Counting up
count = 1
while count <= 5:
print(count)
count += 1
Here, as long as the `count` variable is less than or equal to 5, it gets printed, and
then 1 is added to it.