Skip to main content

Introduction to Python Programming

Python is a general-purpose programming language whose readable syntax makes it a useful first language for data work. This guide uses Python 3. Run a file with the interpreter selected for your environment:

python hello.py

On systems where python does not name Python 3, use python3 on macOS/Linux or py on Windows. Inside an activated virtual environment, python refers to that environment's interpreter.

Values, names, and types​

Python assigns objects to names; a declaration is not required. The built-in type() function reports an object's type.

course = "Python fundamentals"
lessons = 8
completion = 0.75
is_active = True

print(type(course).__name__, type(lessons).__name__)
print(completion, is_active)

Common built-in scalar types include str, int, float, bool, and NoneType. Operators follow the types of their operands: / performs true division, while // performs floor division.

print(7 / 2) # 3.5
print(7 // 2) # 3
print(7 % 2) # 1
print(2 ** 3) # 8

Blocks and indentation​

Indentation is part of Python's syntax. A colon introduces an indented suite of statements.

temperature = 21

if temperature >= 20:
message = "warm"
else:
message = "cool"

print(message)

Use four spaces per indentation level and do not mix tabs and spaces.

Input and output​

print() writes a readable representation to standard output. input() reads one line and always returns a string, so numeric input needs explicit conversion.

name = input("Your name: ")
age_text = input("Your age: ")
age = int(age_text)
print(f"Hello, {name}. Next year you will be {age + 1}.")

The example is intentionally manual because it waits for user input. Invalid integer text makes int() raise ValueError; production code should decide how to report or recover from that error.

Loops​

A for loop consumes an iterable. range(stop) produces integers from zero up to, but not including, stop.

total = 0
for number in range(1, 6):
total += number

print(total) # 15

A while loop repeats while its condition is true. Make sure its state can reach a stopping condition.

remaining = 3
while remaining > 0:
print(remaining)
remaining -= 1

Functions​

Functions give a computation a name and define its inputs and result. Reaching the end without return returns None.

def mean(values):
"""Return the arithmetic mean of a non-empty sequence."""
if not values:
raise ValueError("values must not be empty")
return sum(values) / len(values)


print(mean([2, 4, 9])) # 5.0

The explicit empty-input check makes the function's assumption visible. Continue with data structures, control flow, and functions before moving to data-science libraries.