Essential Python and Command Line Programming Concepts
Essential Command Line Tools
Terminal Commands
mkdir: Creates a new directory.pwdorcd(orchdir): Shows the current working directory.- Changing Directory Example: To change the current directory to the ‘SI206’ folder (if you are currently in its parent folder, ‘Fall22’), use
cd SI206.
Git Commands (Version Control)
git clone url: Copies a repository to your local computer.git status: Shows what has changed and what is staged for commit.git add file: Adds a specific file to the staging area for the next commit.git commit -m "message": Creates a local commit with a descriptive message.git push: Pushes the local commit(s) to the remote repository (the cloud).
Object-Oriented Programming (OOP) Concepts
Relationship Terms
- Instance Of: A student is an instance of a university (e.g., an object belonging to a class).
- Subclass Of (Kind Of): A dog is a kind of animal (Inheritance).
- Association (Has-A Link): Flight has an association with Airport (Composition/Aggregation).
Class Definitions and Methods
- Object Method
- A function that belongs to an instance (object) of a class. It can access and modify that object’s data.
- Class Method
- A function that belongs to the class itself, not just the instance. It is shared across all objects and typically used for factory methods or operations on the class.
- Object Attribute
- A variable that belongs to a specific object (instance). Each object can have different values. Defined in
__init__or assigned usingself(e.g.,self.name = name). - Class Attribute
- A variable that belongs to the class itself. Shared by all instances unless overridden by an object attribute. Key point: Defined directly inside the class body (outside
__init__). __init__Method- Runs automatically when you create an object; used to set up initial attributes.
__str__Method- The method that is called when an object of a class is printed (used for user-friendly string representation).
Function Definition
A function is a named group of statements that can take parameters and performs a specific task.
Control Flow Keywords
continue- Skips the rest of the current iteration of a loop and moves to the next iteration.
pass- Used as a placeholder to allow unfinished code blocks (like functions or loops) to compile without error.
break- Exits the loop immediately.
return- Hands back a result to the caller and ends the execution of the function.
Turtle Graphics Library Commands
- Movement:
forward(x),backward(x),left(angle),right(angle) - Positioning:
goto(x, y),setheading(deg) - Pen Control:
penup(),pendown(),pensize(w),color("red") - Shapes:
circle(r),stamp() - Filling:
begin_fill()…end_fill(),fillcolor("blue") - Screen Setup:
bgcolor("white"),screensize(w, h),exitonclick()
Python Code Examples and Implementations
String Slicing Example
b = "Hello, World!" # THIS CODE PRINTS "orld"
print(b[8:-1])
Function: Filtering Happy Hour Specials
This function takes a list of menu items (name, category, is_today_special, price) and returns a dictionary of specials grouped by category, provided the item is a special and costs $15 or less.
def happy_hour_specials(menu_items):
specials = {}
for name, category, is_today_special, price in menu_items:
if is_today_special and price <= 15:
if category not in specials:
specials[category] = {}
specials[category][name] = price
return specials
Function: Creating a Dictionary from Tuples
The make_dir function converts a list of two-element tuples (key, value) into a dictionary.
def make_dir(tuple_list):
d = {}
for tuple in tuple_list:
d[tuple[0]] = tuple[1]
return d
Class Implementation: Book
Constructs a class named Book with an initializer (__init__) that sets title and author attributes. Includes a __str__ method to return a string containing the title.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return "Title: " + self.title
newbook = Book("The Odyssey", "Homer")
Class Implementation and Unit Testing: Car
Defines the Car class with __init__ and set_model methods. Followed by a unittest.TestCase implementation to test the set_model functionality.
class Car:
def __init__(self, make, model, color):
self.make = make
self.model = model
self.color = color
def set_model(self, model):
self.model = model
def get_model(self):
return self.model
import unittest
class TestCar(unittest.TestCase):
def setUp(self):
self.c = Car("Ford", "Volt", "Blue")
def test_set_model(self):
self.c.set_model("Focus")
self.assertEqual(self.c.get_model(), "Focus")
Function: Summing the First Half of a List
Returns the total sum of the items in the first half of the passed list nums. Uses floor division for the halfway index. Example: total_first_half([1, 2, 3]) returns 1; total_first_half([1, 2, 3, 4]) returns 3.
def total_first_half(nums):
half = len(nums) // 2 # Floor division to get halfway index
return sum(nums[:half]) # Slice first half and sum it
# Test cases
print(total_first_half([1, 2, 3]))
print(total_first_half([1, 2, 3, 4]))
Function: Calculating Letter Grade from Percentage
The computegrade function takes a percentage (per, 0.0 to 1.0) and returns a letter grade string (A, B, C, D, F). It returns “Invalid Input” if the score is outside the 0.0 to 1.0 range.
def computegrade(per):
# Check for invalid input
if per < 0 or per > 1.0:
return "Invalid Input"
# Determine grade
if per >= 0.9:
return "A"
elif per >= 0.8:
return "B"
elif per >= 0.7:
return "C"
elif per >= 0.6:
return "D"
else:
return "F"
# Test cases
print(computegrade(.95))
print(computegrade(.5))
Turtle Function: Drawing a Filled Triangle
This function draws an equilateral triangle of a given side length using the Turtle object t and fills it with the current fill color.
def draw_triangle(side):
t.begin_fill()
for _ in range(3):
t.forward(side)
t.left(120) # 360 / 3
t.end_fill()
