In the last chapter, we learned how to create a simple Python program. We will now delve deeper into the fundamentals of Python by discussing variables, data types, and operators.
Variables
Variables in Python are used to store information that can be referenced and manipulated in our programs. They are created by assigning a value to a label with the =
operator.
greeting = "Hello, Python!" print(greeting)
Output:
Hello, Python!
In this example, greeting
is a variable that holds the string “Hello, Python!”.
Data Types
Python has several built-in data types that we can use to structure and manipulate our data. Here are some of the most commonly used ones:
- Integers: Whole numbers. Example:
5
- Floats: Decimal numbers. Example:
5.0
- Strings: A sequence of characters. Example:
"Hello, Python!"
- Booleans: True or false values. Example:
True
- Lists: Ordered, mutable sequences. Example:
[1, 2, 3]
- Tuples: Ordered, immutable sequences. Example:
(1, 2, 3)
- Dictionaries: Unordered key-value pairs. Example:
{"name": "Python", "year": 1991}
Operators
Operators are symbols that carry out operations on one or more operands. Python has several types of operators:
- Arithmetic Operators: Used with numeric values to perform common mathematical operations.
# Addition (+) print(5 + 2) # Output: 7 # Subtraction (-) print(5 - 2) # Output: 3 # Multiplication (*) print(5 * 2) # Output: 10 # Division (/) print(5 / 2) # Output: 2.5 # Floor Division (//) print(5 // 2) # Output: 2 # Modulus (%) print(5 % 2) # Output: 1 # Exponentiation (**) print(5 ** 2) # Output: 25
- Assignment Operators: Used to assign values to variables.
x = 5 # x is now 5 x += 3 # equivalent to x = x + 3, so x is now 8 x -= 2 # equivalent to x = x - 2, so x is now 6 # Similarly, there are *=, /=, //=, %=, **= operators
- Comparison Operators: Used to compare values. The result of a comparison is a boolean (
True
orFalse
).
print(5 > 2) # Output: True print(5 < 2) # Output: False print(5 == 2) # Output: False print(5 != 2) # Output: True print(5 >= 2) # Output: True print(5 <= 2) # Output: False
- Logical Operators: Used to combine conditional statements.
print(True and False) # Output: False print(True or False) # Output: True print(not True) # Output: False
In the next chapter, we’ll explore control structures and learn how to use these operators to influence the flow of our programs.
That’s a basic overview of variables, data types,
and operators in Python! With this knowledge, you’re well on your way to writing more complex and powerful Python programs.