Machine Learning Fundamentals with Python
Python Basics
A New Syntax
If you're coming from Java or Kotlin, the first thing you'll notice about Python is its clean, readable syntax. It's designed to be uncluttered. Instead of using curly braces {} to define blocks of code, Python uses indentation. This isn't just for style, it's a strict rule the interpreter enforces.
Similarly, you can forget about ending every line with a semicolon ;. Python knows a statement is over when you start a new line. This might feel strange at first, but it leads to code that's often easier to read at a glance.
In Python, whitespace matters. Consistent indentation (usually four spaces) is crucial for your code to run correctly.
# This is a simple Python program
# No class or main method needed for a simple script
print("Hello, World!")
Compare that to the boilerplate often required in Java just to print a single line. Python lets you get straight to the point.
Variables and Data Types
Python handles variables and data types differently than statically-typed languages like Java. It uses dynamic typing, which means you don't need to declare a variable's type beforehand. The type is inferred at runtime based on the value you assign.
This makes declaring variables quick and flexible. A variable can hold an integer, and later, it can be reassigned to hold a string.
# Variable assignment in Python
# Integer
count = 10
# Float
price = 19.99
# String
name = "Alice"
# Boolean
is_active = True
# The type can change
count = "ten" # This is perfectly valid
Python's main built-in data types include integers (int), floating-point numbers (float), strings (str), and booleans (bool). While you don't declare types, you can explicitly convert, or cast, a value from one type to another using functions like int(), str(), or float().
Controlling the Flow
Control structures in Python use the same colon-and-indentation pattern. Conditional logic is handled with if, elif (Python's version of else if), and else.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or lower")
# Output: Grade: B
Loops are also straightforward. The for loop in Python is particularly powerful. It iterates over any sequence, like a list, a string, or a range of numbers. This is different from the C-style for loop common in Java.
# Loop from 0 up to (but not including) 5
for i in range(5):
print(i)
# Loop over the characters in a string
for char in "Python":
print(char)
while loops function much as you'd expect, executing a block of code as long as a condition is true.
counter = 0
while counter < 3:
print(f"Counter is {counter}")
counter += 1
Functions and Modules
You define functions using the def keyword. Like everything else, the function's body is defined by indentation. You can specify parameters and use the return keyword to send a value back.
def greet(name):
return f"Hello, {name}!"
message = greet("Bob")
print(message) # Output: Hello, Bob!
Python's power is extended through modules, which are simply files containing Python definitions and statements. They're like packages in Java. You can bring their functionality into your code using the import statement.
# Import the entire math module
import math
# Use a function from the module
square_root = math.sqrt(16)
print(square_root) # Output: 4.0
# You can also import specific functions
from random import randint
random_number = randint(1, 10)
print(f"A random number: {random_number}")
Handling Errors
For error handling, Python uses try...except blocks, which are the equivalent of Java's try...catch. When an error, or exception, occurs in the try block, the code jumps to the matching except block.
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
# Output: You can't divide by zero!
You can also add an else clause, which runs only if no exception was raised in the try block, and a finally clause, which runs no matter what, whether an exception occurred or not. This structure provides a robust way to manage potential errors and ensure cleanup code is always executed.
try:
num = int("25")
except ValueError:
print("That wasn't a valid number.")
else:
print("Conversion successful!")
finally:
print("Execution finished.")
Now, let's review the core concepts we've covered.
Ready to test your knowledge? Let's try a few questions.
How does Python define the scope of a code block, such as the body of a loop or function?
In Python, you do not need to explicitly declare a variable's type before assigning a value to it. This feature is known as:
That covers the essential syntax and structures you'll need to start writing Python. By building on your existing programming knowledge, you can quickly get up to speed with this flexible language.