Mastering Python for Data Science & AI

7% Complete

Variables, data types, and operators

Objective

Understand how to store and manipulate data using Python's primitive data types.

2.1 Variables

A variable is a named location used to store data in memory.

# Variable assignment
course_name = "Mastering Python"
students_enrolled = 3200
rating = 5.0
is_free = True

2.2 Common Data Types

  • String (str): Textual data. Enclosed in single ('') or double ("") quotes.
  • Integer (int): Whole numbers.
  • Float (float): Numbers with a decimal point.
  • Boolean (bool): Represents truth values, True or False.

2.3 Type Casting

You can convert variables from one type to another.

# Convert float to int
rating_int = int(rating) # Becomes 5

# Convert int to string
student_count_str = str(students_enrolled) # Becomes "3200"

2.4 Operators

  • Arithmetic: +, -, *, /, % (modulo), ** (exponent)
  • Comparison: ==, !=, >, <, >=, <=
  • Logical: and, or, not

Example:

# Calculate the average rating after a new 4.0 review
new_rating = 4.0
total_ratings = 100 # assuming 100 ratings before
current_total = rating * total_ratings
new_average = (current_total + new_rating) / (total_ratings + 1)
print(f"New average rating: {new_average}")