Python Fundamentals
This lesson introduces the fundamental building blocks of Python programming: variables, data types, and operators. You'll learn how to store and manipulate data, perform basic calculations, and understand the different types of information Python can handle. By the end of this lesson, you'll be able to write simple Python programs that perform basic operations.
Learning Objectives
- Define and use variables to store different types of data.
- Identify and differentiate between common Python data types (integers, floats, strings, booleans).
- Utilize arithmetic, comparison, and logical operators in Python expressions.
- Write simple Python programs that perform calculations and manipulate data.
Text-to-Speech
Listen to the lesson content
Lesson Content
Variables: Your Data Containers
A variable is like a named container that holds a value. In Python, you create a variable by giving it a name and assigning a value to it using the = operator. Variable names can contain letters, numbers, and underscores, but they cannot start with a number. Python is dynamically typed, meaning you don't need to declare the data type explicitly; it's inferred from the value you assign.
Example:
age = 30 # integer variable
name = "Alice" # string variable
pi = 3.14159 # float variable
is_student = True # boolean variable
Data Types: The Kinds of Values
Python has several built-in data types. Understanding these is crucial.
- Integers (int): Whole numbers (e.g.,
10,-5,0). - Floats (float): Numbers with decimal points (e.g.,
3.14,-2.5). - Strings (str): Sequences of characters enclosed in single or double quotes (e.g.,
'hello',"Python"). - Booleans (bool): Represent truth values:
TrueorFalse.
Example:
num_apples = 5 # int
price = 2.99 # float
message = "Hello, World!" # str
is_active = True # bool
Operators: Doing the Work
Operators are special symbols that perform operations on values or variables. We'll cover:
- Arithmetic Operators:
+(addition),-(subtraction),*(multiplication),/(division),//(floor division - rounds down to the nearest whole number),%(modulo - gives the remainder),**(exponentiation). - Comparison Operators:
==(equal to),!=(not equal to),>(greater than),<(less than),>=(greater than or equal to),<=(less than or equal to). - Logical Operators:
and(returnsTrueif both operands are true),or(returnsTrueif at least one operand is true),not(inverts the boolean value).
Example:
a = 10
b = 3
print(a + b) # 13
print(a / b) # 3.3333333333333335
print(a // b) # 3 (floor division)
print(a % b) # 1 (modulo)
print(a > b and b < 5) # True
print(a == 10 or b == 1) # True
Deep Dive
Explore advanced insights, examples, and bonus exercises to deepen understanding.
Day 2: Data Scientist - Python Fundamentals (Beyond the Basics)
Welcome back! Yesterday, you laid the groundwork for your Python journey by exploring variables, data types, and operators. Today, we'll delve deeper, providing a richer understanding and equipping you to write more versatile code.
Deep Dive: Data Types and Type Conversion
Let's refine our understanding of data types. While you learned about integers, floats, strings, and booleans, Python offers more subtle variations and important considerations.
-
Type Conversion: Python allows you to convert between data types (e.g., integer to float, string to integer) using functions like
int(),float(), andstr(). Be mindful, though; conversion isn't always possible (e.g., converting the string "hello" to an integer).Example:
age_string = "30" age_integer = int(age_string) # Converts "30" (string) to 30 (integer) print(age_integer + 5) # Output: 35 - Data Type Immutability: Some data types, like strings and tuples (which you'll meet later), are immutable. This means you can't change their values after they're created. If you try to modify an immutable object, you effectively create a new one. This is different from mutable data types (e.g., lists), which can be altered in place. Understanding immutability is crucial for preventing unexpected behavior in your code.
-
Type Hints (Optional): Although Python is dynamically typed (you don't explicitly declare the type of a variable), you *can* use type hints for better code readability and maintainability, especially for larger projects. They don't affect runtime but help with static analysis (e.g., using a code editor like VS Code with a Python extension).
Example:
age: int = 30 # Explicitly tells the reader that 'age' is expected to be an integer. name: str = "Alice" is_active: bool = True
Bonus Exercises
-
Exercise 1: Age Calculator. Write a program that asks the user for their birth year (as a string) and calculates their age. Handle potential errors if the user enters non-numeric input. Print the age.
birth_year_str = input("Enter your birth year: ") try: birth_year = int(birth_year_str) age = 2024 - birth_year print(f"Your age is: {age}") except ValueError: print("Invalid input. Please enter a valid year.") -
Exercise 2: Simple Conversion. Create a program that converts temperature from Celsius to Fahrenheit. Get the Celsius value from the user (as a string), convert it to a float, apply the formula (Fahrenheit = (Celsius * 9/5) + 32), and print the result. Format the output to two decimal places.
celsius_str = input("Enter temperature in Celsius: ") try: celsius = float(celsius_str) fahrenheit = (celsius * 9/5) + 32 print(f"The temperature in Fahrenheit is: {fahrenheit:.2f}") except ValueError: print("Invalid input. Please enter a valid number.")
Real-World Connections
These fundamental concepts are the backbone of almost any data science task:
- Data Cleaning and Preprocessing: Converting data types (e.g., strings representing numbers to numerical types) is a *critical* part of data cleaning. You'll often encounter data in inconsistent formats that need to be standardized.
- Feature Engineering: Creating new features from existing ones often involves calculations (arithmetic operators) and comparing values (comparison and logical operators). For instance, calculating age from a birthdate or deriving a ratio from two columns.
- User Input Validation: In any application that takes user input, you'll need to check the data types to ensure they're valid (e.g., is the user entering a number where expected?).
Challenge Yourself
Advanced Exercise: Create a program that takes three numbers from the user and determines the largest one. Handle potential errors if the user enters non-numeric input. (Hint: Use comparison operators and if/elif/else statements, which you will learn later, but you can explore). Consider handling cases where two or more numbers are the same.
Further Learning
Explore these topics to expand your knowledge:
- More Data Types: Investigate lists, tuples, and dictionaries – these are essential for organizing and working with data.
- Error Handling (Try-Except Blocks): Learn more robust ways to handle potential errors in your code (e.g., using `try-except` blocks).
- Python Documentation: Become familiar with the official Python documentation (https://docs.python.org/3/) - it's your best friend!
Interactive Exercises
Variable Practice
Create three variables: `name` (string), `age` (integer), and `height` (float). Assign your name, age, and height to these variables. Then, print each variable to the console.
Data Type Exploration
Create variables of different data types: an integer, a float, a string, and a boolean. Use the `type()` function to check the data type of each variable. For example, `print(type(age))`.
Operator Challenge
Write a program that uses all of the arithmetic operators. Calculate the area of a rectangle (length * width) where length = 10 and width = 5. Also calculate the remainder when 17 is divided by 3.
Practical Application
Imagine you're building a simple inventory management system. You need to store the name, quantity, and price of different products. Use variables of appropriate data types to represent these product attributes. Write a Python program to calculate the total value of the inventory.
Key Takeaways
Variables store data, allowing you to reference and manipulate it later.
Python has several built-in data types (int, float, str, bool) that represent different kinds of data.
Operators enable you to perform calculations, comparisons, and logical operations.
Understanding data types and operators is fundamental for writing any Python program.
Next Steps
Prepare to learn about control flow and conditional statements (if, else, elif) to make your programs more dynamic and responsive.
Your Progress is Being Saved!
We're automatically tracking your progress. Sign up for free to keep your learning paths forever and unlock advanced features like detailed analytics and personalized recommendations.
Extended Learning Content
Extended Resources
Extended Resources
Additional learning materials and resources will be available here in future updates.