🐍

Python Basics Overview

Jun 15, 2025

Overview

This lecture is a quick-start guide to Python basics, focusing on variables, data types, printing, logic, loops, functions, and error handling.

Setting Up Python and Tools

  • Use Python 3.8 and PyCharm editor to write and run Python code.
  • Both Python and PyCharm are free and open-source.

Variables & Naming

  • Assign a value to a variable using the equals sign (e.g., item = "banana").
  • Python is case sensitive: item and Item are different variables.
  • Use underscores for multi-word variable names (e.g., item_name = "orange").

Data Types and Printing

  • Data types: integer (e.g., 10), string (e.g., "apple"), boolean (True/False), list (e.g., ["a", "b"]).
  • Print values using the print() function.
  • Combine strings and variables using +, but convert data types as needed (str(), int()).

Type Conversion and Exceptions

  • Convert integers to strings with str() for combining with text.
  • Convert string numbers to integers with int() before doing math.
  • Type mismatches cause exceptions.

Basic Math Operations

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Exponentiation: ***

Logic Statements (If/Else)

  • Use if, elif, else to write conditional logic based on variable values.
  • Example: if age > 21: print("You are old")

Loops

  • For loop: for i in range(3): repeats three times (indexes start at 0).
  • For loops can also iterate over lists.
  • While loop: continues as long as a condition is true (e.g., while i < 5).
  • Use break to exit a loop early.

User Input

  • Get user input with input(), which returns a string.
  • Use while True for infinite loops; break on a specific input to stop.

Functions

  • Define a function with def (e.g., def say_hello(name):).
  • Functions help you reuse code by running the same logic with different inputs.
  • Use pass as a placeholder for function bodies not yet implemented.

Error Handling (Try/Except)

  • Use try and except blocks to catch and handle errors (exceptions) in your code.
  • Example: Handle invalid user input and print an error message instead of stopping the program.

Key Terms & Definitions

  • Variable — a named storage for a value.
  • String — text enclosed in quotes.
  • Integer — whole number data type.
  • Boolean — True or False value.
  • List — ordered collection of items.
  • Function — reusable block of code defined with def.
  • Exception — an error detected during code execution.

Action Items / Next Steps

  • Install Python 3.8 and PyCharm.
  • Practice writing and running basic Python scripts covering the topics above.