Computer Science Introduction
💡 Introduction to Computer Science & Programming
This course, CS 50, is an introduction to the intellectual enterprises of Computer Science and the art of programming. The primary goal is to teach how to think and how to master problem-solving tools, rather than just how to program. Programming is a powerful side effect, but the core skill is computational thinking.
🤖 The Rise of Artificial Intelligence (AI)
Artificial Intelligence is rapidly changing the landscape of programming. This is an exciting development as AI tools can significantly enhance a programmer's ability to solve problems, find bugs, and add new features to software.
AI as a Co-pilot: AI can act as an assistant, helping to solve problems and debug code.
Feature Generation: Increasingly, AI can generate new features for software based on user input.
Overcoming Human Bottlenecks: Historically, human programmers have been the bottleneck in software development due to limited time and resources. AI helps overcome this by accelerating the development process.
Understanding Fundamentals: Despite AI's capabilities, a deep understanding of programming fundamentals and computational thinking remains critical. Programmers will remain "in the driver's seat," guiding the AI.
Historical Parallel: This shift is comparable to the introduction of calculators, which still required an understanding of mathematical principles.
💻 Programming Environment: Visual Studio Code (VS Code)
Visual Studio Code (VS Code) is a popular, largely open-source text editor used in industry for writing code. It's similar to basic text editors but is specialized for programming, lacking word processing features like bolding or underlining.
Terminal Window: VS Code includes a terminal window where users can type commands to interact directly with the computer.
💬 Building a Chatbot with Python and OpenAI API
This demonstration illustrates how easily one can build a basic chatbot using Python and the OpenAI API.
Import OpenAI Library: The
from openai import OpenAIcommand allows access to OpenAI's functionalities.API (Application Programming Interface): OpenAI provides an API, which is a set of functions and protocols that allows different software applications to communicate with each other. Developers can write their own programs ("clients") that use the features provided by the OpenAI API.
Client Creation: A
clientobject is created to interact with the OpenAI software.Generating Responses: The
client.chat.completions.createfunction sends a request to the OpenAI model (e.g.,GPT-5) with a specific prompt and receives aresponse.Printing Output: The
print(response.choices[0].message.content)command displays the AI's generated text.
Initial Chatbot: A basic chatbot can be created in about 10 lines of Python code, hardcoded to answer a specific question.
Dynamic Prompting: To make the chatbot interactive, the
input()function can be used to ask the user for aprompt(question). This user input is stored in a variable, which is a placeholder for a value.System Prompt: To guide the AI's behavior (e.g., "limit your answer to one sentence"), a system prompt can be provided in addition to the user's prompt. This allows for consistent AI responses without the user needing to specify the desired behavior repeatedly.
AI Personalities: By changing the system prompt (e.g., "pretend you're a cat"), the AI's output can be influenced to adopt different "personalities."
🦆 The Rubber Duck Debugging Method
The concept of rubber duck debugging is a widely recognized practice in programming.
Origin: Programmers often keep a rubber duck or similar inanimate object on their desk.
Process: When encountering a bug or problem, the programmer explains the code line-by-line to the duck.
Benefit: The act of verbalizing the problem and organizing thoughts often helps the programmer identify their own logical errors or mistakes.
CS 50 AI Duck: CS 50 provides its own virtual AI duck (
CS50.AIorCS50.dev) designed to act as a human tutor, guiding students to solutions without simply giving them the answer.Allowed AI Usage: Students are encouraged to use CS 50's AI tools but are restricted from using other general-purpose AI software like ChatGPT, Gemini, or Claude for course assignments.
📊 Computer Science: The Study of Information
Computer Science is fundamentally the study of information: how to represent it and how to process it.
Computational Thinking: The application of ideas from computer science to solve real-world problems.
Problem Solving: The core of computer science, using computers as tools and methodologies.
Input, Black Box, Output: A problem can be visualized as an input (the problem), a black box (the solution process), and an output (the desired result).
🔢 Representing Information: Binary (Zeros and Ones)
All computers ultimately understand and process information using binary digits, or bits, which are either 0 or 1.
Binary Digit (Bit): A single 0 or 1.
Physical Representation: In computers, a 0 might be represented by an electrical switch being off (no electricity), and a 1 by a switch being on (electricity flowing). This simplicity makes binary ideal for hardware.
Counting in Binary:
Unary (Base 1): Counting on fingers, where each finger represents one unit. Very limiting.
Binary (Base 2): Each finger (or bit) has a positional weight, typically powers of 2 (1, 2, 4, 8, 16, 32...).
Example: With 3 fingers/bits, one can count from 0 (all off) to 7 (all on).
000= 0001= 1010= 2011= 3100= 4101= 5110= 6111= 7
Decimal (Base 10): The number system humans typically use, with 10 digits (0-9). Each position represents a power of 10 (1, 10, 100, 1000...).
Example: 123 is 1×102+2×101+3×100.
Bytes: A common unit of measure in computing, where 1 byte = 8 bits.
With 8 bits, one can represent 28=256 different values (from 0 to 255).
Kilobytes (KB), Megabytes (MB), Gigabytes (GB), Terabytes (TB) are larger units based on bytes.
Larger Numbers: To count higher than 255, more bits are needed.
32 bits: Can represent approximately 4 billion unique values (or 2 billion if negative numbers are included).
64 bits: Increasingly common, representing a vastly larger number of permutations.
AI and Bits: The exponential increase in computing speed, memory, and available data (all stored as bits) has been a key factor in the recent advancements of AI.
🔠 Representing Text (Letters)
Computers represent letters by assigning a unique integer (number) to each character. This number is then stored in binary.
Context-Dependent Interpretation: The same pattern of zeros and ones can be interpreted differently depending on the software (e.g., as a number in a calculator, a letter in a word processor, or a color in Photoshop). The programmer dictates this interpretation.
ASCII (American Standard Code for Information Interchange): An early standard that mapped English letters, numbers, and punctuation to specific numerical values.
Capital 'A': Represented by the decimal number 65.
'B': 66, 'C': 67, and so on.
Lowercase 'a': Represented by 97.
Uppercase to Lowercase Conversion: The difference between an uppercase letter and its lowercase counterpart in ASCII is 32. A computer can change a letter's case by simply flipping a single bit (the 32's place bit) in its binary representation.
ASCII typically used 7 or 8 bits, allowing for 28=256 unique characters. This was sufficient for English but not for other languages.
Unicode: A modern superset of ASCII that uses significantly more bits (e.g., 16, 24, or 32 bits per character) to represent characters from virtually all human languages, past, present, and future.
Emojis: Emojis are technically Unicode characters, represented by patterns of zeros and ones, displayed as images. The same emoji character might appear slightly different across different platforms (Apple, Android, Telegram) because each platform has its own graphical font for rendering that character.
With 32 bits, Unicode can represent approximately 4 billion characters.
🎨 Representing Colors and Images
Colors are also represented by integers (numbers) in computers.
RGB (Red, Green, Blue): A common system where colors are created by mixing varying amounts of red, green, and blue light.
Each color component (Red, Green, Blue) is typically represented by a single byte (8 bits), allowing values from 0 to 255.
0: No amount of that color.
255: Maximum amount of that color.
Example:
0, 0, 0(no red, no green, no blue) = Black255, 255, 255(max red, max green, max blue) = White72, 73, 33(as seen in the "HI!" example) would represent a specific shade of yellow if interpreted as RGB values.
Pixels: Images are composed of individual dots or squares called pixels.
Each pixel has its own color, represented by a combination of bits.
Using RGB, each pixel requires $8 + 8 + 8 = 24 bits (3 bytes) to store its color information.
File Size: Large images or videos (GIFs, PNGs, JPEGs) require many megabytes (millions of bytes) because they contain thousands or millions of pixels, each using multiple bytes for color data.
🎬 Representing Video
A video is essentially a rapid sequence of many still images (frames) displayed per second.
Animation: The illusion of motion is created by showing 24-30 images per second, similar to a flipbook.
Videos build upon the lower-level representation of images and colors.
🎶 Representing Sound (Music)
Musical notes can be represented using numbers to describe their characteristics.
Attributes: Key attributes of a sound include:
Frequency/Pitch: The tone of the note.
Duration: How long the note is held.
Amplitude/Loudness: How loud the note is.
By standardizing these numerical representations, musical files can be shared and reproduced accurately.
⚙️ Algorithms: Step-by-Step Instructions
An algorithm is a precise, step-by-step set of instructions for solving a specific problem.
Software Implementation: All software is an implementation of one or more algorithms in a language the computer understands (e.g., C, Python).
Efficiency: Algorithms can be designed to be more or less efficient, impacting how quickly a problem is solved and how many resources (CPU, RAM, time, money) are consumed.
Problem-Solving Example: Phone Book Search
Naive Search (Linear): Starting at the beginning and checking each entry one by one.
Correctness: Always finds the entry if it exists.
Efficiency: Very slow. If there are
Npages, it takes up toNsteps. This is represented by a linear relationship (O(N)).
Skipping Pages (Linear, but faster): Checking two pages at a time.
Correctness: Potentially problematic (might skip over the target). Requires an extra step to double-check.
Efficiency: Faster than the naive search (approx. N/2 steps), but still linear.
Divide and Conquer (Binary Search): Opening to the middle, deciding which half the target is in, and discarding the other half. This process is repeated until the target is found.
Correctness: Always finds the entry if it exists.
Efficiency: Much faster. If the problem size doubles, it only requires one additional "tear" (division). This is represented by a logarithmic relationship (O(log N)).
Example: 1000 pages -> 500 -> 250 -> 125... very few steps to find the entry.
Importance of Design: Computer science emphasizes not just writing correct code, but also efficient and well-designed code.
📝 Pseudocode: Human-Like Algorithms
Pseudocode is an informal, English-like description of an algorithm. It's not a formal programming language but helps humans outline step-by-step instructions.
Example: Phone Book Search Pseudocode
Pick up phone book.
Open to middle of phone book.
Look at page.
If person is on page, call person.
Else if person is earlier in book, open to middle of left half of book. Go back to line 3.
Else if person is later in book, open to middle of right half of book. Go back to line 3.
Else (person not in book), quit.
Anticipating Corner Cases: Good algorithms (and code) must anticipate all possible situations, including negative or unexpected outcomes (e.g., the person not being in the phone book). Failure to do so can lead to software freezing or crashing.
🏗️ Fundamental Programming Constructs
Several key concepts underlie all programming languages:
Functions: Verbs or actions that perform a specific, often small, piece of work. They can take inputs (arguments/parameters) and may produce an output (return value) or a side effect (e.g., something visual on screen).
Conditionals: Forks in the road that allow a program to make decisions based on certain conditions (e.g.,
if,else if,else).Boolean Expressions: Questions that evaluate to a simple yes/no or true/false (1/0) answer. These are used within conditionals.
Loops: Mechanisms that allow a program to repeat a set of instructions multiple times (e.g.,
for,while,repeat).
📜 From Zeros and Ones to High-Level Languages
Low-Level Code: Early computers were programmed directly using zeros and ones (machine code), often via punch cards. This was tedious and error-prone.
Abstraction: The principle of abstraction in computing involves building layers of tools and languages that hide lower-level complexities.
Compilers: Programs that translate human-readable code (e.g., C) into machine code (zeros and ones).
High-Level Languages: Languages like C, Python, Scratch are progressively more abstract and user-friendly.
C: A foundational language that provides a closer understanding of how computers work.
Python: A very high-level language that simplifies many tasks, often built upon C.
Standing on the Shoulders of Giants: Modern programming is possible because previous generations solved complex low-level problems, creating tools and APIs that allow current programmers to build powerful applications more easily.
🧩 Scratch: Visual Programming
Scratch is a graphical programming language developed by MIT, designed to teach programming fundamentals using drag-and-drop puzzle pieces.
Browser-Based Environment: Accessible at
scratch.mit.edu.Components:
Blocks Palette: Contains color-coded puzzle pieces representing functions, conditionals, loops, and other constructs.
Programming Area: Where puzzle pieces are dragged and connected to form scripts (programs).
Sprites: Characters or objects in the Scratch world (e.g., the default cat). Sprites can have multiple costumes to create animation.
Stage/World: The 2D environment where sprites interact, defined by an X-Y coordinate plane.
Key Concepts in Scratch:
Events: Blocks that trigger actions (e.g.,
when green flag clicked).Looks: Blocks that control a sprite's appearance (e.g.,
say "Hello World").Sensing: Blocks that allow a sprite to interact with its environment or user input (e.g.,
ask "What's your name?" and wait).Variables: Placeholders that store values (e.g.,
answerfor user input, or custom variables likescore).Operations: Blocks for combining values or performing calculations (e.g.,
join "Hello, " [answer]).Control: Blocks for loops (
repeat,forever) and conditionals (if,if else).My Blocks: Users can create their own custom functions (blocks) to encapsulate reusable code, promoting modularity and abstraction.
Example: Interactive Cat Program
Say "Hello World":
when green flag clickedsay "Hello World"
Ask for Name and Respond:
when green flag clickedask "What's your name?" and wait(stores input inanswervariable)say join "Hello, " answer
Text-to-Speech: Using extensions like "Text to Speech" to make the cat speak and even change its voice.
Meowing Cat (Loops):
Naive approach: Duplicate
play sound meow until doneandwait 1 secondblocks multiple times. This is inefficient and poorly designed.Better approach (using a loop):
repeat 3play sound meow until donewait 1 second
Custom Block (Abstraction): Create a custom
meowblock that encapsulates theplay soundandwaitlogic. This allows for cleaner, more reusable code.Define
meow (N) times:repeat Nplay sound meow until donewait 1 second
Then, simply use
meow (3) timesin the main script.
Petting Cat (Conditionals and Loops):
when green flag clickedforeverif <touching mouse-pointer?> thenplay sound meow until done
The
foreverloop is crucial; without it, the program only checks the condition once when the green flag is clicked.
Oscar Time Game (Complex Example): A game where players drag falling trash into a trash can, demonstrating:
Sprites and Costumes: Using multiple sprites (trash can, trash items) and changing costumes for animation.
Random Movement: Trash falling from random X locations at the top of the screen.
Loops for Movement:
change y by -1in aforeverloop to simulate falling.Collision Detection:
if <touching [Oscar]?>to detect when trash hits the trash can.Teleportation: When trash is "collected," it teleports back to the top to simulate a new piece falling.
Scorekeeping: Using a
scorevariable, incremented when trash is collected.Modular Design: Creating custom blocks (functions) like
go to topto avoid repeating code.
IB's Hardest Game (Advanced Example): A game demonstrating more complex interactions:
Player Control: Using arrow keys to move the player sprite (
Harvard Crest).Wall Collision:
if <touching [left wall]?> then change x by 1(to bounce off).Autonomous Enemies:
Yale: Moves back and forth horizontally, turning 180 degrees upon hitting walls. Speed can be adjusted by changingmove (1) steps.MIT: Homing enemy thatpoint towards [Harvard logo outline]andmove (1) steps, constantly following the player. Speed adjustments can lead to visual glitches if too fast.
Game Progression: Multiple levels with increasing complexity (more enemies, different enemy behaviors).
Problem-Solving Strategy: Break down complex problems into smaller, manageable sub-problems. Start with simple functionalities and build up to the desired solution.
🍰 Conclusion
This initial exploration of computer science has covered fundamental concepts from binary representation of information to the building blocks of programming with Scratch. The journey from understanding zeros and ones to creating interactive programs highlights the power of abstraction and algorithmic thinking.

Ask anything
We've read this whole study set, so questions about it get the best answers.