Table of contents
Welcome back to our Python programming journey! In Day 1, we explored the fundamentals of Python and got a glimpse of its syntax and basic functionalities. Today, we're diving deeper into the building blocks of any programming language: variables and operators.
Variables
In Python, variables serve as a containers to store data values. In python a variable is created the moment you assign a value to it. Essentially, a Python variable is a label attached to a particular memory space.
Example of variable
#Variable assignment
var = "Hello, World"
#Printing variable and its types
print(var) #Output: Hello, World
print(type(var)) #Output: <class 'str'>
(var)
can be changed as your program runs.Variables naming in Python
Variable names cannot start with a digit.
Python is case-sensitive, so
var
andVar
are different variables.Can consist of letters, digits, and underscores.
Operators
In Python, operators are symbols that perform operations on variables. They are used to carry out arithmetic, comparison, assignment, logical, and other operations.
Types of operators in Python :
Arithmetic Operators: This includes addition (
+
), subtraction (-
), multiplication (*
), division (/
), floor division (//
), modulus (%
), exponentiation (**
).#Arithmetic operators x = 20 y = 6 print(x + y) # Output: 26 print(x - y) # Output: 14 print(x * y) # Output: 120 print(x / y) # Output: 3.3333333333333335 print(x // y) # Output: 3 print(x % y) # Output: 2 print(x ** y) # Output: 64000000
Assignment operators: They assign values to variables and include the "=" operator for simple assignments and operators like "+=", "-=", "*=", and "/=" for combined operations.
Comparison Operators: Used to compare two values that includes, Equal to (
==
), Not equal to (!=
), Greater than (>
), Less than (<
), Greater than or equal to (>=
), Less than or equal to (<=
).x = 5 y = 6 print(x == y) # Output: False print(x != y) # Output: True print(x > y) # Output: False print(x < y) # Output: True print(x >= y) # Output: False print(x <= y) # Output: True
Identity Operators:
is
: Returns True if both variables are the same object.is not
: Returns True if both variables are not the same object.
Logical Operators: They are used to perform logical operations on boolean values. Logical AND (
and
), Logical OR (or
), Logical NOT (not
).x = 5 y = 6 print(x > 0 and y < 20) # Output: True
Conclusion
We've covered a lot of ground today, delving into the complication of variables and operators in Python.
In Day 3, we'll take our Python journey further by exploring control flow statements, such as loops and conditionals, which allow us to control the flow of our programs based on certain conditions.
Stay curious! Happy coding <3