Introduction to Programming Class Notes
Introduction to Programming Class Notes
Input and output functions like print() and input() allow interaction. A simple "Hello World" program
would be:
print("Hello, World!")
print("Welcome,", user_name)
Common errors include syntax errors (e.g., missing colons or parentheses) and runtime errors (e.g.,
dividing by zero). Always check indentation, as Python uses whitespace to define code blocks.
Control structures direct the flow of a program. Conditional statements like if, elif, and else
execute code based on Boolean conditions. For example:
temperature = 30
else:
print("Cool weather!")
Loops repeat actions: for loops iterate over sequences (e.g., lists), while while loops run until
a condition is false. Use break to exit a loop early or continue to skip iterations. Logical
operators (and, or, not) combine conditions.
A practical exercise is building a number-guessing game:
import random
guess = 0
print("Correct!")
Functions encapsulate reusable code. Define them with def, followed by parameters:
return a + b
Parameters are variables in the function definition; arguments are the actual values passed.
Modules like math (for sqrt, sin) or random (for randint, choice) extend functionality. Import
them with import module_name.
Variable scope determines accessibility: variables inside a function are local, while those
declared outside are global. For example:
x = 10 # Global
def test():
y = 5 # Local
print(x + y)
test()
Practice by creating a calculator that uses functions for addition, subtraction, etc.