Python Functions, Scope, Objects, and Turtle Graphics
Course Announcements and Semester Schedule
Assignment 1 Submission Deadline and Policies:
- Assignment 1 is due tomorrow at 11:00 PM.
- Adequate time must be allowed to submit work prior to the deadline.
- Submitting even 1 minute late—including situations where submission was attempted but the automated system did not process it—results in a minimum penalty of a 10% deduction.
Assignment 2 Release and Cadence:
- Assignment 2 will be released tomorrow.
- Students who complete Assignment 1 early can begin Assignment 2 as soon as it opens tomorrow.
- Assignment 2 will utilize Python's Turtle module.
- Exactly 1 week is given to complete Assignment 2, making it due next Thursday.
- Standard semester schedule structure: Every Thursday an assignment is due, and every Thursday a new assignment is released.
Upcoming Class Holiday Schedule:
- There is no class on Monday due to a scheduled holiday.
- There are no office hours, support hours, or email responses during Monday's holiday.
- The next class activity following today is the scheduled lab session on Tuesday.
- Lecture resumes in person on Wednesday.
Quiz 1 Format and Preparation
Quiz Schedule and Timing:
- Quiz 1 takes place in class next Wednesday.
- The quiz is administered during the last 10 minutes of the regular lecture period.
- Class lecture will end a few minutes early to provide time for the quiz.
- The quiz is designed to take 10 minutes or less to complete.
Format and Content:
- The quiz is 1 page long.
- It contains short answer questions and multiple-choice questions.
- Questions are based directly on the material covered in Assignment 1.
- The quiz is administered entirely on paper, not on a computer. A physical writing utensil is required.
Permitted Materials and Preparation Advice:
- A reference sheet detailing common Python syntax will be provided alongside the quiz, eliminating the need for pure memorization.
- To prepare, review Assignment 1 requirements and read through written code to refresh memory on implementation details.
Submission Procedure and Quiz Cadence:
- Upon finishing the quiz, quietly gather all personal belongings, turn in the paper quiz directly to one of the Teaching Assistants (TAs) present in class, and exit the room.
- Starting next Wednesday, a quiz will occur almost every Wednesday covering the material from the preceding assignment/week.
Functions, Parameters, and Variable Scope
Review of Functions:
- A function is a named block of code that encapsulates a specific chunk of execution logic to accomplish a task.
- Functions eliminate the need to retype or copy and paste repetitive blocks of code across a program.
Choosing Between Loops and Functions for Code Repetition:
- Use a loop when code needs to repeat continuously or sequentially in one location.
- Use a function when code needs to be executed flexibly across different distinct locations within a program.
- Loops and functions can be combined, such as executing a loop that calls a function during each iteration.
Parameters and Local Scope:
- A parameter acts as a variable internal to a function definition (for example, a parameter named in a function named
double). - When a function is called, the parameter evaluates to the argument value passed into the function call (e.g., evaluating ).
- Parameters exist exclusively within the internal scope of their parent function and cannot be accessed or evaluated outside of that function.
- Attempting to access a function parameter outside its function body triggers a name error indicating the variable is not defined, as Python expects a globally or locally defined variable that does not exist in that outer context.
- A parameter acts as a variable internal to a function definition (for example, a parameter named in a function named
Definition of Scope:
- Scope refers to the specific region of a program where a variable name is valid and accessible.
Local Variables:
- A local variable is any variable defined inside a function body (for example, defining a variable
new_numberinside anadd_twofunction). - The lifetime and scope of a local variable are restricted strictly to the execution of the function in which it is declared.
- Local variables cannot be referenced, modified, or accessed outside of their defining function.
- A local variable is any variable defined inside a function body (for example, defining a variable
Global Variables and Best Practices:
- A global variable is defined outside of any function body (e.g., declaring
number = 5at the top level of a script in PyCharm). - The scope of a global variable extends everywhere throughout the script, making it accessible both inside and outside of functions.
- Style Rule: Defining global variables is strongly discouraged as bad programming style, with very few exceptions.
- Instead of relying on global variables, programs should pass values into functions explicitly using parameters.
- Local variables can be given the exact same name as variables in other scopes, but Python treats them as entirely distinct entities in memory.
- A global variable is defined outside of any function body (e.g., declaring
Objects, Data Types, and Method Invocation
Variables and Memory Model:
- When assigning a value to a variable (e.g.,
number = 12), Python creates an object storing the value in memory, and the variable namenumberstores a reference pointing to that memory object. - Different values possess distinct data types, such as integers (
int), floating-point numbers (float), or strings (string). - Standard Python functions can accept objects of multiple different data types. For example, the
str()function can be called on anintcontaining , afloat, or astringwithout error because standalone functions are not strictly bound to a single object type.
- When assigning a value to a variable (e.g.,
Methods vs. Functions:
- A method is a special category of function that is explicitly bound to a specific object or data type.
- In languages such as Java, almost all routine operations are termed methods because code is inherently tied to object classes.
- In Python, an object is defined as an entity possessing a specific data type (e.g.,
int,float,string) that has underlying class code defining valid operations for objects of that type. - Methods are invoked using dot notation in the format
object.method_name().
Method Scope and Syntax Errors:
- The
.lower()method is defined specifically for objects of typestringand returns a lowercase copy of the string (e.g.,"Hello".lower()produces"hello"). - Calling a string method on an incompatible data type—such as attempting to execute
.lower()on a numerical data type (intorfloat)—results in an error stating the object has no attribute'lower'. - Methods cannot be invoked in isolation without an attached object instance (e.g., calling
.lower()standalone is a syntax error) because Python requires an explicit object preceding the dot to determine what entity is being operated on.
- The
Python Turtle Graphics Setup and Import Rules
Overview of Python Turtle:
- Turtle is a built-in graphical module created originally by developers at MIT.
- It enables visual drawing on a window canvas by simulating a turtle crawling across a screen, leaving continuous line traces along its path.
Class Activity and Starter Code Location:
- Starter files are located on Canvas under the Class Day 4 activity page labeled "turtle in class activity".
Import Syntax and Critical File Naming Rule:
- To use Turtle graphics, scripts must import its functionality using
from turtle import *(or importing methods directly from the turtle module). - CRITICAL WARNING: Never name a custom Python file
turtle.pyor store a script namedturtlein the working directory or PyCharm project. Naming a fileturtle.pyoverrides Python's standard library module, preventing the script from finding required drawing methods.
- To use Turtle graphics, scripts must import its functionality using
Initializing Canvas and Turtle Objects:
- A display window must be initialized by creating a
Screenobject:window = Screen() - A drawing object must be initialized by creating a
Turtleobject:my_turtle = Turtle()(or any arbitrary variable identifier such asframeorAgatha).
- A display window must be initialized by creating a
Controlling Turtle Objects with Methods and Pen Commands
Screen Event Loop:
- The method
window.exitonclick()must be placed at the end of the script to keep the window canvas active until clicked by the user, after which it safely closes the screen object.
- The method
Default State and Movement Methods:
- By default, a newly created turtle object initializes in the center of the screen canvas facing to the right ( relative to the horizontal axis).
my_turtle.forward(distance): Moves the turtle forward in its current direction by a specified numeric distance (e.g.,my_turtle.forward(100)ormy_turtle.forward(200)).my_turtle.left(angle): Rotates the turtle counterclockwise by a specified angle in degrees (e.g.,my_turtle.left(45)ormy_turtle.left(100)).my_turtle.right(angle): Rotates the turtle clockwise by a specified degree angle.- Sequential forward commands without rotation continue moving the turtle along its existing heading vector.
Controlling Line Rendering with Pen Commands:
- By default, the turtle draws a continuous line wherever it travels.
my_turtle.penup(): Lifts the pen drawing tip off the canvas surface, allowing the turtle to relocate without rendering lines.my_turtle.pendown(): Places the pen tip back down onto the canvas, resuming line drawing for subsequent movement commands.
Working with Multiple Turtle Objects:
- Multiple independent turtle objects can be instantiated within a single script (e.g.,
my_turtle = Turtle()andmy_other_turtle = Turtle()). - Each turtle instance operates independently with its own position, heading, and drawing state, allowing scenarios like simultaneous multi-turtle drawings or racing animations.
- Multiple independent turtle objects can be instantiated within a single script (e.g.,
Execution Rules and Documentation:
- Turtle graphics rendering relies on active code execution; removing or deleting movement lines from a script prevents those path segments from being drawn when the script is executed again.
- Specific turtle method names do not need to be memorized; official Python Turtle documentation provides complete listings of available graphical and configuration methods.
Advanced Turtle Concepts: Modularizing with Functions
- Encapsulating Graphic Logic in Functions:
- Instead of repeatedly writing long, sequential sequences of raw turtle methods to draw complex geometry, drawing operations should be encapsulated inside custom functions.
- Defining a custom function to draw specific shapes allows complex graphical procedures to be invoked repeatedly via single function calls across the script.