You are viewing a preview of this lesson. Sign in to start learning
Back to Python Programming

Setup & Basics

Introduction to Python, installation, and environment configuration

Setting Up Your Python Environment and Basic Syntax

Master Python fundamentals with free flashcards and spaced repetition practice. This lesson covers Python installation, interactive shell usage, variable declaration, and running your first programsβ€”essential concepts for anyone starting their programming journey.

Welcome to Python Programming! 🐍

Python has become one of the world's most popular programming languages, beloved by beginners and experts alike. Whether you're building web applications, analyzing data, creating machine learning models, or automating tasks, Python provides an elegant, readable syntax that makes programming accessible and enjoyable.

In this lesson, you'll learn how to set up Python on your computer, understand the different ways to run Python code, and write your first programs. We'll explore the Python interactive shell, variables, basic data types, and the fundamental structure of Python programs.

Installing Python πŸ’»

Python comes in two main versions: Python 2 (legacy, end-of-life) and Python 3 (current). Always use Python 3.x for new projects.

Installation Steps by Operating System

Operating System Installation Method Verification Command
Windows Download installer from python.org, check "Add Python to PATH" python --version
macOS Comes pre-installed (may be old), or download from python.org / use Homebrew: brew install python3 python3 --version
Linux Usually pre-installed, or apt install python3 (Ubuntu/Debian) python3 --version

πŸ’‘ Pro Tip: After installation, open your terminal/command prompt and type python --version (Windows) or python3 --version (Mac/Linux) to verify the installation shows something like "Python 3.11.4".

Understanding the Python Command

On Windows, you typically use:

python script.py

On macOS and Linux, you often need to be explicit:

python3 script.py

This distinction exists because some systems still have Python 2 installed as python, while Python 3 is python3.

The Python Interactive Shell (REPL) πŸ”„

The REPL (Read-Eval-Print Loop) is Python's interactive shellβ€”a powerful environment where you can type Python code and see results immediately.

Starting the REPL

Simply type python or python3 in your terminal:

$ python3
Python 3.11.4 (main, Jun 20 2023, 17:23:00)
[Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> prompt means Python is waiting for your input.

Using the REPL

>>> 2 + 2
4
>>> print("Hello, World!")
Hello, World!
>>> name = "Alice"
>>> print(f"Hello, {name}")
Hello, Alice
>>> exit()

πŸ’‘ Pro Tip: The REPL is perfect for testing small code snippets, experimenting with syntax, or using Python as a calculator.

🧠 Memory Device: Think of REPL as a Really Easy Place to Learnβ€”it reads your code, evaluates it, prints the result, and loops back for more!

Your First Python Program πŸ“

While the REPL is great for quick tests, real programs are saved in .py files that you can run repeatedly.

Creating a Python File

  1. Open any text editor (VS Code, Sublime Text, Notepad++, or even Notepad)
  2. Type your Python code
  3. Save with a .py extension (e.g., hello.py)
  4. Run it from the terminal: python hello.py

Example: hello.py

print("Hello, World!")
print("Welcome to Python programming!")

Run it:

$ python3 hello.py
Hello, World!
Welcome to Python programming!

Python File Structure

Python reads your file top to bottom, executing each line in order:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Python File Execution Flow     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                 β”‚
β”‚  Line 1  ───────→  Execute     β”‚
β”‚     ↓                           β”‚
β”‚  Line 2  ───────→  Execute     β”‚
β”‚     ↓                           β”‚
β”‚  Line 3  ───────→  Execute     β”‚
β”‚     ↓                           β”‚
β”‚  Line 4  ───────→  Execute     β”‚
β”‚     ↓                           β”‚
β”‚   ...                           β”‚
β”‚                                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Variables and Basic Data Types πŸ“¦

Variables are containers that store data. Unlike some languages, Python doesn't require you to declare variable typesβ€”it figures them out automatically (dynamic typing).

Variable Assignment

# Integers (whole numbers)
age = 25
temperature = -5

# Floats (decimal numbers)
price = 19.99
pi = 3.14159

# Strings (text)
name = "Alice"
message = 'Hello, World!'

# Booleans (True/False)
is_active = True
has_permission = False

Variable Naming Rules

Rule Valid Examples Invalid Examples
Start with letter or underscore name, _value, data2 2name, $price
Only letters, numbers, underscores user_name, value1 user-name, first.name
Case-sensitive Name β‰  name β‰  NAME N/A
Not a keyword my_class, for_loop class, for, if

πŸ’‘ Convention: Use snake_case for variable names: user_name, total_count, is_valid

Checking Types

Use the type() function to see what type a variable is:

>>> type(25)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("Hello")
<class 'str'>
>>> type(True)
<class 'bool'>

Basic Input and Output πŸ”Š

The print() Function

The print() function displays output to the console:

print("Simple message")
print("Multiple", "arguments", "separated", "by", "spaces")
print("Value:", 42)

Output:

Simple message
Multiple arguments separated by spaces
Value: 42

String Formatting

Python offers multiple ways to format strings:

name = "Alice"
age = 30

# f-strings (Python 3.6+, recommended)
print(f"My name is {name} and I'm {age} years old")

# .format() method
print("My name is {} and I'm {} years old".format(name, age))

# Concatenation (less flexible)
print("My name is " + name + " and I'm " + str(age) + " years old")

All produce:

My name is Alice and I'm 30 years old

πŸ’‘ Best Practice: Use f-strings for modern Python codeβ€”they're more readable and faster.

The input() Function

The input() function reads user input from the keyboard:

name = input("What is your name? ")
print(f"Hello, {name}!")

age = input("How old are you? ")
print(f"You are {age} years old")

⚠️ Important: input() always returns a string. To get numbers, you must convert:

age_str = input("Enter your age: ")
age = int(age_str)  # Convert string to integer
print(f"Next year you'll be {age + 1}")

# Or combine it:
age = int(input("Enter your age: "))

Comments and Code Documentation πŸ“–

Comments are notes in your code that Python ignoresβ€”they explain what your code does for human readers.

# This is a single-line comment
print("Hello")  # Comments can also go at the end of lines

# Multiple single-line comments
# can be stacked to create
# multi-line explanations

"""
This is a multi-line string that's often used
as a multi-line comment. It's technically a string
that's not assigned to anything.
"""

name = "Alice"  # Store the user's name
age = 25        # Store the user's age

πŸ’‘ Good commenting practice:

  • Explain why, not what (the code shows what)
  • Use comments for complex logic
  • Keep comments up-to-date with code changes

Understanding Python Syntax Rules πŸ“

Python's syntax is notably different from languages like C, Java, or JavaScript:

Indentation is Sacred

Python uses indentation (spaces or tabs) to define code blocksβ€”not curly braces:

# Correct indentation
if age >= 18:
    print("You are an adult")  # Indented = inside the if block
    print("You can vote")

print("This always runs")  # Not indented = outside the if block

⚠️ Common Mistake: Mixing tabs and spaces causes errors. Configure your editor to use 4 spaces per indentation level (Python standard).

No Semicolons Required

Unlike many languages, Python doesn't need semicolons at the end of statements:

# Python style (correct)
name = "Alice"
age = 25
print(name)

# You can use semicolons, but it's not Pythonic
name = "Alice"; age = 25; print(name)

Case Sensitivity

Python distinguishes between uppercase and lowercase:

name = "Alice"
Name = "Bob"
NAME = "Charlie"

print(name)  # Alice
print(Name)  # Bob
print(NAME)  # Charlie

Examples in Action πŸš€

Example 1: Simple Calculator

# Get two numbers from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Perform calculations
sum_result = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2

# Display results
print(f"Sum: {sum_result}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")

Explanation: This program demonstrates input, type conversion (float()), arithmetic operations, and f-string formatting. Note that we use float() instead of int() to allow decimal numbers.

Example 2: Temperature Converter

# Convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}Β°C is equal to {fahrenheit}Β°F")

# Convert Fahrenheit to Celsius
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit}Β°F is equal to {celsius}Β°C")

Explanation: This shows how to perform mathematical formulas in Python. The order of operations follows standard mathematics (PEMDAS/BODMAS). Notice how we can reuse variable names for different values.

Example 3: Personal Greeting Generator

# Gather user information
first_name = input("What's your first name? ")
last_name = input("What's your last name? ")
age = int(input("How old are you? "))
city = input("What city do you live in? ")

# Generate personalized greeting
print(f"\nHello, {first_name} {last_name}!")
print(f"It's great to meet someone who is {age} years old.")
print(f"I hope you're enjoying life in {city}!")

# Calculate birth year (approximate)
current_year = 2024
birth_year = current_year - age
print(f"\nYou were probably born in {birth_year}.")

Explanation: This program combines multiple inputs and demonstrates string concatenation with f-strings. The \n creates a blank line for better formatting. This also shows a simple calculation using the stored age value.

Example 4: String Manipulation Basics

# Get user input
text = input("Enter some text: ")

# Various string operations
print(f"Original: {text}")
print(f"Uppercase: {text.upper()}")
print(f"Lowercase: {text.lower()}")
print(f"Length: {len(text)} characters")
print(f"First character: {text[0]}")
print(f"Last character: {text[-1]}")

# Check for content
if "python" in text.lower():
    print("You mentioned Python!")
else:
    print("No mention of Python found.")

Explanation: This demonstrates string methods like .upper() and .lower(), the len() function for length, string indexing with [0] and [-1], and the in operator for substring checking.

Common Mistakes to Avoid ⚠️

1. Forgetting to Convert input() to Numbers

# ❌ WRONG
age = input("Enter your age: ")
next_year = age + 1  # ERROR! Can't add int to string

# βœ… CORRECT
age = int(input("Enter your age: "))
next_year = age + 1  # Works!

2. Inconsistent Indentation

# ❌ WRONG
if True:
  print("Two spaces")
    print("Four spaces")  # IndentationError!

# βœ… CORRECT
if True:
    print("Four spaces")
    print("Four spaces")

3. Using Reserved Keywords as Variable Names

# ❌ WRONG
class = "Math 101"  # SyntaxError! 'class' is a keyword
for = 5             # SyntaxError! 'for' is a keyword

# βœ… CORRECT
class_name = "Math 101"
count = 5

4. Mismatching Quote Types

# ❌ WRONG
name = "Alice'  # SyntaxError! Quotes don't match

# βœ… CORRECT
name = "Alice"  # Both double quotes
name = 'Alice'  # Both single quotes
name = "It's Alice"  # Double quotes allow single quote inside
name = 'She said "Hi"'  # Single quotes allow double quotes inside

5. Confusing = (assignment) with == (comparison)

# ❌ WRONG
if age = 18:  # SyntaxError! Can't use = in condition
    print("Exactly 18")

# βœ… CORRECT
if age == 18:  # == checks equality
    print("Exactly 18")

Key Takeaways 🎯

βœ… Python 3.x is the current versionβ€”always use it for new projects

βœ… The REPL (interactive shell) is perfect for quick experiments and testing

βœ… Python files use the .py extension and are run with python filename.py

βœ… Variables don't need type declarationsβ€”Python figures out the type automatically

βœ… Use snake_case for variable names: user_name, not userName or UserName

βœ… print() displays output; input() reads user input (always as a string)

βœ… Convert strings to numbers with int(), float(), etc.

βœ… Indentation defines code blocksβ€”use 4 spaces per level

βœ… f-strings (f"text {variable}") are the modern way to format strings

βœ… Comments start with # and help explain your code

πŸ€” Did You Know?

Python was named after Monty Python's Flying Circus, not the snake! Creator Guido van Rossum was reading the comedy group's scripts while implementing Python in the late 1980s. This is why Python documentation often includes silly references like "spam" and "eggs" instead of generic "foo" and "bar"!

πŸ”§ Try This: Your First Real Program

Create a file called about_me.py and write a program that:

  1. Asks for your name, age, and favorite hobby
  2. Calculates what year you were born
  3. Prints a nicely formatted summary
  4. Uses at least one comment explaining your code

Example output:

=== About Me ===
Name: Alice Johnson
Age: 25
Born: ~1999
Favorite Hobby: Photography
================

πŸ“‹ Quick Reference Card

Start REPLpython3 or python in terminal
Exit REPLexit() or Ctrl+D (Mac/Linux) / Ctrl+Z (Windows)
Run Python filepython3 filename.py
Print outputprint("text") or print(variable)
Get inputinput("prompt: ")
Convert to intint(value)
Convert to floatfloat(value)
Convert to stringstr(value)
Check typetype(variable)
Single-line comment# comment text
F-string formatf"text {variable} more"
String lengthlen(text)

πŸ“š Further Study

  1. Official Python Tutorial - https://docs.python.org/3/tutorial/index.html - The definitive guide from Python's creators

  2. Real Python Tutorials - https://realpython.com/python-first-steps/ - Comprehensive beginner tutorials with practical examples

  3. Python Style Guide (PEP 8) - https://pep8.org/ - Learn Python's official style conventions for writing clean, readable code

Practice Questions

Test your understanding with these questions:

Q1: Write a complete Python program that asks the user for their name and age, then prints a greeting message that includes their name and calculates their birth year (assuming the current year is 2024). Use f-strings for formatting.
A: !AI