Categories

Chapter 1.3: Variables, Data Types, and Operators

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:

  1. Integers: Whole numbers. Example: 5
  2. Floats: Decimal numbers. Example: 5.0
  3. Strings: A sequence of characters. Example: "Hello, Python!"
  4. Booleans: True or false values. Example: True
  5. Lists: Ordered, mutable sequences. Example: [1, 2, 3]
  6. Tuples: Ordered, immutable sequences. Example: (1, 2, 3)
  7. 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:

  1. 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
  1. 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
  1. Comparison Operators: Used to compare values. The result of a comparison is a boolean (True or False).
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
  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *