0% found this document useful (0 votes)
10 views23 pages

CS Course Lesson 1

This document provides a comprehensive introduction to Python programming, covering topics such as setting up a development environment, writing and running a basic 'Hello, World' program, and understanding functions, variables, and user input. It emphasizes the importance of using text editors over word processors, debugging syntax errors, and best practices for writing readable code. Additionally, it discusses string manipulation, data types, and practical applications like creating a basic calculator and formatting numbers.

Uploaded by

amuaru21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views23 pages

CS Course Lesson 1

This document provides a comprehensive introduction to Python programming, covering topics such as setting up a development environment, writing and running a basic 'Hello, World' program, and understanding functions, variables, and user input. It emphasizes the importance of using text editors over word processors, debugging syntax errors, and best practices for writing readable code. Additionally, it discusses string manipulation, data types, and practical applications like creating a basic calculator and formatting numbers.

Uploaded by

amuaru21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🐍 Your First Python Program

Development Environment Setup


Visual Studio Code (VS Code) is a popular program for writing code, but any text editor
works since code is just text. Python files use the .py extension to indicate they're Python
programs.

The Classic "Hello, World" Program


The most canonical first program in any programming language:

print("Hello, world")

To run this program, use the command line interface (CLI) with the command:

python [Link]

Understanding Functions and Arguments

A function is like an action or verb that lets you do something in a program.

Print is a built-in function that displays output on the screen. Functions use parentheses to
take arguments - inputs that influence their behavior.

An argument is an input to a function that somehow influences its behavior.

The text "Hello, world" passed to print() is a string - a sequence of text characters.

How Python Works


Python serves dual purposes:
1. Language: The syntax you write
2. Interpreter: A program that translates your code into binary (zeros and ones) the
computer understands
When you run python [Link], the interpreter reads your code top-to-bottom, left-to-right,
converting it into machine-readable instructions.

Side Effects in Programming


The visual output you see (like "Hello, world" appearing on screen) is called a side effect -
something that happens as a result of running the code, whether visual, audio, or otherwise.

Debugging and Syntax Errors

A bug is a mistake in a program.

Syntax errors occur when you violate the language's rules. For example, forgetting to close a
parenthesis:

print("Hello, world" # Missing closing parenthesis

This produces an error message indicating the open parenthesis was never closed. Computers
take code literally - even small typos can prevent execution.
The dollar sign ($) in the terminal indicates the prompt where you enter commands.

📝 Text Editors vs. Word Processors for Coding


Microsoft Word and similar word processors are not suitable for writing code. While code is
fundamentally text, word processors add formatting (bold, underlining, paragraphs) that
interferes with programming.

Text editors like VS Code are purpose-built for editing plain text without formatting

VS Code features:
Syntax highlighting (colors for different code elements)
Built-in terminal window
Debugging tools
Free cloud usage available
Many alternative text editors exist
🖥️ Terminal vs. GUI Interfaces
Programs can be run through:
Command Line Interface (CLI) - via terminal window
Graphical User Interface (GUI) - for end users
CLI is preferred for learning programming as it provides more control, while GUI is better for
shipping software to users.

🔤 Getting User Input with Python


The input() function prompts users for text input:
Displays a blinking cursor
Waits for user to type and press Enter
Can accept a prompt string as an argument
Example evolution:
1. Initial attempt: print("What's your name?") then input()
2. Better approach: input("What's your name? ")

📦 Variables and the Assignment Operator


Variables are containers that store values in computer memory. Unlike math variables (x, y, z),
programming variables can have descriptive names.

The assignment operator (=) copies values from right to left

Syntax: variable_name = value


Key points:
Assignment flows right to left
Stores the return value of functions
Allows reuse of stored data

🖨️ Printing Variables vs. Strings


Common mistake: Using quotes around variable names
"name" prints the literal text "name"
name prints the variable's stored value
Correct approach: Pass variables to print() without quotes to display their contents

Comments in Python 💬
What Are Comments?

Comments are notes to yourself in your code that the computer ignores during execution

Written using the hash symbol (#) in Python


Used to explain code functionality to yourself, teachers, or colleagues
VS Code grays out comments to distinguish them from executable code

Best Practices
Comment every few lines to explain noteworthy code chunks
Use human language (not necessarily English)
Helpful for:
Understanding your code after time away
Debugging by comparing intentions with actual code
Sharing code with others

Multi-line Comments
Single method: Prefix each line with #
Alternative method: Use three double quotes (""") or three single quotes (''') for
multi-line comments (have special meaning in Python)

Pseudocode 📝
Pseudocode is using human language to express thoughts succinctly and algorithmically -
it's not a formal language

Benefits
Outline programs before writing actual code
Breaks big programs into bite-size tasks
Serves as a to-do list when you're unsure how to implement
Allows you to express what you want to do before figuring out how
String Concatenation 🔗
The Problem
Initial program printed "Hello" and name on separate lines - not grammatically elegant

Solution 1: Plus Operator


Use + to concatenate (join) strings
Example: "Hello, " + name
Note: Must manually add spaces for proper formatting

Solution 2: Multiple Arguments


print() function accepts multiple arguments separated by commas
Example: print("Hello,", name)
Important: Print automatically inserts a space between arguments
Remove manual spaces to avoid double spacing

Key Difference
Plus operator: Creates one concatenated string before passing to print
Comma method: Passes multiple separate arguments to print function

Function Arguments 📌
Input Function
input() expects a string argument
The string serves as the prompt displayed to user
Only works with text/string data type

Print Function Flexibility


Can take one or multiple arguments
When using multiple arguments, separates them with automatic spaces
Arguments can be strings, variables, or combinations

🔄 Functions and String Manipulation in Python


Function Reusability
Functions can be used multiple times to solve problems. When you find yourself solving the
same type of problem repeatedly, you can create custom functions instead of relying only on
built-in language functions.

String Basics

A string is a technical term in programming that refers to a sequence of text - this can be a
single character, a word, or an entire paragraph.

In Python, strings are technically referred to as str (short for string), which represents the data
type for text sequences.

String Concatenation
The plus operator (+) serves two purposes in Python:
Mathematical addition for numbers
String concatenation for combining text
You can chain multiple strings together using multiple plus signs:

"Hello" + " " + "David" + "!"

However, this approach becomes visually messy with long lines of code.

Print Function Parameters


Parameters vs Arguments
Parameters: What a function can accept (from the function's perspective)
Arguments: What you actually pass to the function (from the user's perspective)
These terms describe the same concept but from different perspectives.
Key Print Function Parameters
Parameter Default Value Purpose
end '\n' (newline) Determines what appears
after the printed content
sep ' ' (space) Determines how multiple
arguments are separated

Overriding Default Behavior


End Parameter: By default, print() adds a newline after output. You can override this:

print("Hello, ", end="")


print("David")
# Output: Hello, David

Sep Parameter: By default, multiple arguments are separated by spaces. You can customize
this:

print("Hello", "David", sep="???")


# Output: Hello???David

Documentation Reading
Python's official documentation is available at [Link]. The documentation uses
single quotes while many programmers prefer double quotes - both work in Python, but
consistency is important.
The documentation format might appear cryptic initially, but learning to read it is essential as it
contains all answers to questions about Python functions.

🖨️ Print Function Parameters


Positional vs Named Parameters
Positional parameters are values passed to print() in order:
First argument gets printed first
Second argument gets printed second
And so forth...
Named parameters are optional parameters you can specify by name:
sep - controls separator between arguments
end - controls what ends the line
Named parameters can be passed at the end of print statements and called by name

🎯 Handling Quotation Marks in Strings


The Quote Problem
When you need to include quotation marks within a string, you can't simply nest them:

print("hello "friend"")

This creates invalid syntax.

Solutions:
1. Single/Double Quote Alternation
Use single quotes outside, double quotes inside:

print('hello "friend"')

2. Escape Characters
Use backslash \ before inner quotes:

print("hello \"friend\"")

The backslash is an escape character that tells Python the following character
should be treated literally

🔤 Format Strings (f-strings)


Basic Syntax
f-strings allow variable interpolation directly in strings:
Prefix string with f
Wrap variables in curly braces {}
name = "David"
print(f"hello, {name}")

f-strings are a relatively new Python feature that formats strings in a special way

🧹 String Cleaning Methods


Common User Input Problems
Accidental spaces before/after input
Inconsistent capitalization
Sloppy formatting

Built-in String Methods


Method Purpose Example
.strip() Removes whitespace from " david ".strip() → "david"
left and right
.capitalize() Capitalizes first letter "david".capitalize() → "David"

Method Syntax
String methods use dot notation:

variable_name.method_name()

Methods are functions that belong to specific data types. You access them using a period
after the variable name

Updating Variables
You can reassign the result back to the original variable:

name = [Link]()
name = [Link]()

The equals sign means assignment (right to left), not mathematical equality
String Methods in Python 📝
Basic String Manipulation
String methods are functions built into string types that allow you to manipulate text data.
Common methods include:
.strip() - removes whitespace from both ends of a string
.title() - capitalizes the first letter of each word
.lstrip() - removes whitespace from the left side only
.rstrip() - removes whitespace from the right side only

Method chaining allows you to combine multiple string methods in a single line of code.
The operations are executed from left to right.

Practical String Processing


When processing user input, you can chain methods together:

name = input("What's your name? ").strip().title()

This single line:


1. Gets user input
2. Removes leading/trailing whitespace
3. Capitalizes each word

Code Style Considerations


There are two valid approaches to string processing:
Compact approach (single line):
Fewer lines of code
Fewer opportunities for mistakes
Can become unreadable if too long
Expanded approach (multiple lines):
More explicit about each step
Easier to debug
Better for complex operations
Best practice: Choose the approach that maximizes readability and maintainability for your
specific use case.

String Splitting
The .split() method divides a string into a list of substrings based on a delimiter:

first, last = [Link](" ")

This creates two variables from a single string, splitting on the space character.

Integer Data Types 🔢


Integer Basics
Integers (type int in Python) are whole numbers without decimal points:
Negative infinity to positive infinity
Examples:

Integer Operations
Python supports standard mathematical operations on integers:
Addition ()
Subtraction ()
Multiplication ()
Division ()

Unlike strings which use for concatenation, integers use these operators for actual
mathematical calculations.

Python Operators and Interactive Mode 🧮


The Modulo Operator
The percent sign (%) in Python is not used for percentages - it's the modulo operator. This
operator gives you the remainder after dividing one number by another.

Interactive Mode 🔄
Python supports an interactive mode where you can:
Execute code line by line immediately
See results instantly without saving files
Access this mode by typing python in the terminal
You'll see the triple bracket prompt (>>>) indicating interactive mode
In this mode, Python acts like a fancy calculator:
Type mathematical expressions like 1 + 1 and get immediate results
Use print() function to display text output
Code executes the moment you press Enter

Creating a Basic Calculator


Initial Calculator Program
A simple calculator can be created using:
Variables to store numbers (x, y, z)
Addition operation with the + operator
Print function to display results
Making It Interactive
To create a user-interactive calculator:
Use the input() function to get user data
Store user responses in variables
Example: x = input("What's x? ")
The String Concatenation Bug 🐛
When using input(), all user input is treated as strings (text), even if it looks like numbers. This
causes:
The + operator to concatenate strings instead of adding numbers
Example: Inputting 1 and 2 results in "12" instead of 3
Type Conversion Solution
To fix this issue, use the int() function to convert strings to integers:
int() converts string numbers to actual numbers
Apply it to both inputs: int(input("What's x? "))
Now mathematical operations work correctly
Function Nesting
Python allows nesting functions (putting functions inside other functions):
The innermost function executes first
Its result becomes the input to the outer function
Example: int(input("What's x? ")) - input() runs first, then int()
Variable Optimization
Consider whether you need intermediate variables:
If you create a variable and use it only once, you might not need it
Instead of: z = x + y then print(z)
Use: print(x + y) directly

Terminal Shortcuts
When working in the terminal:
Use Tab for autocomplete - type first few letters of a filename and press Tab
Use up/down arrows to navigate through command history

Code Readability vs. Complexity 📝


Trade-offs in Code Design
Readability is prioritized over cleverness
Simplicity reduces probability of mistakes
Cluttered code increases logical errors

Key Principle: Making code readable for others is essential - including your future self who
won't remember what you wrote

Variable Usage Debate


Newer approach (direct usage):
Immediately shows x and y variables as integers
More intuitive print arguments
Avoids clutter in code
Shorter line lengths
Older approach (intermediate variable z):
Easier debugging when user inputs unexpected values
More explicit variable passing
Better for error handling (though not covered in current lesson)

Over-Compacting Code
Problematic one-liner example:

print(int(input("x: ")) + int(input("y: ")))

Issues with compact code:


Nested functions require tracking multiple parentheses
Multiple operations in single line reduce readability
Increased cognitive load wastes time
Higher probability of tactical mistakes

Data Types in Python 🔢


Three Fundamental Types
Type Description Examples
string Sequence of text "hello", "123"
int Integer numbers -1, 0, 1
float Numbers with decimal points 1.2, 3.4, -0.5

Float definition: A real number with a decimal point - mathematically called a "floating
point value"

Converting Between Types


int() converts to integer
float() converts to floating point
str() converts to string

Working with Floats 🌊


Basic Float Operations
x = float(input("x: "))
y = float(input("y: "))
print(x + y)

Result: Supports decimal arithmetic like 1.2 + 3.4 = 4.6

Rounding Numbers
round() function syntax:

round(number[, ndigits]) - Square brackets indicate optional parameter

Parameters:
number: Required positional parameter (the value to round)
ndigits: Optional - number of decimal places
Usage examples:
round(4.6) → 5 (nearest integer)
round(4.6, 1) → 4.6 (tenths place)
round(4.6, 2) → 4.60 (hundredths place)

Practical Rounding Implementation

x = float(input("x: "))
y = float(input("y: "))
z = round(x + y)
print(z)

Example: Input 1.2 and 3.4 → Output 5 (rounded from 4.6)

Number Formatting 🎯
Large Number Display
US formatting convention: Commas separate every three digits
1000 → 1,000
1000000 → 1,000,000
International note: Other countries use periods and commas differently based on system
settings

F-strings for Formatting


Purpose: Automatically insert comma separators for readability Benefit: Distinguishes 1,000
from 100 or 1,000,000 from smaller numbers
Implementation: Uses f-string syntax to format numbers with commas

F-Strings and String Formatting 📝


Basic F-String Syntax
F-strings allow you to embed expressions inside string literals using curly braces. To create an
f-string, prefix the string with the letter f and wrap variables in curly braces.

F-string: A formatted string literal that lets you embed expressions inside string literals
using variablesyntax. < /p >< /blockquote >< h3xmlns = "http :
//[Link]/1999/xhtml"style = "text − align : lef t; line − height : 1.5; " ><

strong > N umberF ormattingwithF − Strings < /strong >< /h3 >< pxmlns =

"http : //[Link]/1999/xhtml"style = "text − align : lef t; line − height :

1.5; " > F −

stringssupportautomaticnumberf ormattingusingcolonsandf ormatspecif iers :<

/p >< ulxmlns = "http : //[Link]/1999/xhtml" >< li >< pstyle =

"line − height : normal; " > {z:,} - Adds comma separators for thousands (e.g., 1,000)

z : .2f − F ormatsto2decimalplaces(e.g., 0.67) < /p >< /li >< /ul ><

pxmlns = "http : //[Link]/1999/xhtml"style = "text − align :

lef t; line − height : 1.5; " > T hesyntax {variable:format_spec} is used where
format_spec can be:
.2f for 2 decimal places
, for comma separators
Other locale-specific formatting options

Float Precision and Limitations 🔢


Float Representation Limits
Floats cannot represent numbers infinitely precisely due to finite computer memory. At
some point, computers must round numbers.
Key differences between data types:
Data Type Precision Limit Size Limit
Float Limited decimal precision No upper bound
Int No precision limit No upper bound in Python

Division and Rounding


When performing division like , the result shows finite digits (0.666666) due to float
limitations.
Two ways to round to specific decimal places:
1. Using round() function:
round(x/y, 2) rounds to 2 decimal places
2. Using f-string formatting:
f"{x/y:.2f}" formats to 2 decimal places
Both methods produce equivalent results - the choice depends on whether you need to
pass the rounded value as an argument or just display it.

Creating Custom Functions 🛠️


Function Definition Syntax
Use the def keyword to define custom functions:

def function_name():
# function body (indented)

Function Components
def: Keyword to define a function (short for "define")
function_name: Your chosen name for the function
(): Parentheses for parameters (empty if no parameters)
:: Colon indicates the start of the function body
Indentation: All function code must be indented (typically 4 spaces)
Function Usage
Once defined, functions can be called like built-in Python functions:

hello() # Calls the custom hello function

Error Handling
Attempting to call an undefined function results in a NameError: "name 'function_name' is
not defined"

🎯 Function Parameters and Arguments


Parameterizing Functions
Functions can be customized to accept parameters - variables that act as placeholders for
values that will be passed to the function when it's called.

A parameter is a variable in the function definition that receives a value when the
function is called.

Creating a Parameterized Hello Function


The instructor demonstrates creating a function that takes a person's name as input:

def hello(to):
print("hello,", to)

The parameter is named to because it represents "who do you want to say hello
to?"
The function uses the parameter value in the print statement

Passing Arguments to Functions


When calling a function, you pass arguments (actual values) that get assigned to the
parameters:
name = input("What's your name? ")
hello(name)

The variable name is passed as an argument to the hello function


Inside the function, this value is accessible through the parameter to

🌍 Default Parameter Values


Setting Default Values
Functions can have default parameter values that are used when no argument is
provided:

def hello(to="world"):
print("hello,", to)

If hello() is called without arguments, it defaults to "world"


If hello("David") is called, it uses "David" instead

Using Functions with and without Arguments


The same function can be used in multiple ways:
hello() → prints "hello, world"
hello("Alice") → prints "hello, Alice"

📋 Function Organization and Order


Function Definition Order
Python requires functions to be defined before they are used. The interpreter reads code
top-to-bottom and must know about a function before calling it.

The Main Function Pattern


A common convention is to create a main() function that contains the primary program
logic:
def main():
name = input("What's your name? ")
hello(name)

def hello(to):
print("hello,", to)

main()

main() is defined first but not executed until called


hello() is defined after main() but before it's called
The actual execution starts with main() at the bottom

🔒 Variable Scope
Understanding Scope
Scope refers to where a variable exists and can be accessed in your code.

Scope determines the visibility and lifetime of variables in different parts of your
program.

Local vs. Global Scope


Variables defined inside a function (like name in main()) are local to that
function
These variables cannot be accessed from other functions
Attempting to use a local variable outside its scope results in a NameError

Scope Example and Error


This code will fail:

def main():
name = input("What's your name? ")
hello()

def hello():
print("hello,", name) # Error: name is not defined

name exists only in the main() function


hello() cannot access it because it's outside name's scope
The solution is to pass name as a parameter to hello()

🎯 Function Scope and Variable Passing


Understanding Scope Limitations
When a variable is defined inside a function, it only exists within that function's scope.
This means:

Scope refers to the region of code where a variable is accessible and can be used.

If you try to use a variable from one function inside another function without properly
passing it, you'll get a NameError because the variable doesn't exist in that scope.

Passing Variables Between Functions


To make a variable available to another function, you must pass it as an argument:

def main():
x = 5
hello(x) # Passing x to hello function

def hello(n): # n receives the value of x


print(n)

Each function can name its parameters whatever it wants


The parameter name in the receiving function doesn't need to match the original
variable name
The value is what gets passed, not the variable name itself

🔁 Functions with Return Values


The Return Keyword
Functions can return values using the return keyword, similar to built-in functions like
input(), int(), and float():
Return sends a value back to the caller, allowing the function's result to be used in
expressions or passed to other functions.

Creating a Square Function


Here's how to implement a function that returns a value:

def square(n):
return n * n

def main():
x = int(input("What's x? "))
print(f"x squared is {square(x)}")

Multiple Ways to Square a Number


Python provides several methods to calculate exponents:
1. Multiplication: n * n
2. Exponentiation operator: n ** 2
3. Power function: pow(n, 2)
All three methods produce the same result, demonstrating that there are often multiple
solutions to the same programming problem.

🏗️ Function Design Principles


Side Effects vs Return Values
Side effects: Functions that perform actions (like printing) but don't return
values
Return values: Functions that calculate and return a result without side effects

Function Structure
When creating your own functions:
1. Define the function with def and a descriptive name
2. Specify parameters in parentheses
3. Implement the logic
4. Use return to send back a value (if needed)
5. Call the function and use its return value
The return value can be used directly in expressions, passed to other functions, or stored
in variables for later use.

You might also like