Think of variables as information the program remembers, functions as named pieces of work, and loops as a way to repeat work without writing the same instructions again and again.
Start With the Big Picture
Programming languages differ in syntax, but many of the basic ideas are shared across languages. Variables, functions, and loops are three of the most important.
Variables
Store or refer to values that a program needs to work with.
Functions
Group instructions into reusable pieces of logic that can be called when needed.
Loops
Repeat instructions for a collection of items or while a condition remains true.
These concepts often work together. A loop might pass values into a function, while the function calculates a result and stores it in another variable.
What Is a Variable?
A variable gives a name to a value so that the program can refer to that value later.
For example, instead of repeatedly writing a customer's age, you could store it using a variable.
Storing Values
name = "Sara"
age = 24
score = 87.5Here, name, age, and score are variable names. They refer to values that can be used elsewhere in the program.
Good variable names also make code easier to understand. Compare:
Meaningful Names Help
x = 1250
monthly_revenue = 1250Both variables can hold the same value, but the second name tells the reader what that value represents.
Variables Can Hold Different Types of Data
Programs work with different kinds of values. The exact type system varies between programming languages, but common data types include:
| Type | Example | Typical Purpose |
|---|---|---|
| Integer | 25 | Whole numbers |
| Float / Decimal | 19.75 | Numbers containing decimal values |
| String | "Data Analytics" | Text |
| Boolean | True / False | Logical conditions |
| Collection | [10, 20, 30] | Storing multiple values |
The number 10 and the text "10" are not necessarily interchangeable. Data type problems are a common source of programming errors.
Variable Values Can Change
In many programming languages, a variable can be assigned a value and then updated later.
Updating a Value
score = 70
score = score + 5
print(score)The first line stores 70. The second takes the current value, adds 5, and assigns the new result back to score.
The final value is 75.
This pattern is common in counters, totals, calculations, and loops.
What Is a Function?
A function is a named block of code designed to perform a particular task.
Instead of copying the same calculation into several parts of a program, you can define it once and call the function when needed.
A Simple Function
def greet():
print("Welcome!")
greet()The function is defined using the name greet. Calling greet() executes the instructions inside it.
Functions can make larger programs easier to read, test, maintain, and reuse.
Parameters and Return Values Make Functions More Useful
A function does not have to perform exactly the same operation with the same values every time. It can receive information through parameters.
Using a Parameter
def greet(name):
print("Welcome,", name)
greet("Sara")
greet("Ali")The same function can now work with different names.
Functions can also return a result to the part of the program that called them.
Returning a Value
def calculate_total(price, quantity):
total = price * quantity
return total
order_total = calculate_total(25, 4)
print(order_total)The function calculates a value and returns it. That returned value is then stored in order_total.
Printing a value and returning a value are different actions. A function can return information for later use without displaying it on screen.
What Is a Loop?
A loop repeats a block of code. This avoids manually writing the same instructions for every item or repetition.
Imagine you have 100 customer records. Writing the same calculation 100 times would be inefficient. A loop can apply the calculation to each record.
For Loop
Commonly used to work through items in a collection or sequence.
While Loop
Continues repeating while a specified condition remains true.
Understanding a For Loop
A for loop is useful when you want to perform an operation for each item in a collection.
Looping Through Scores
scores = [72, 85, 91, 68]
for score in scores:
print(score)The loop takes one value from scores at a time, temporarily refers to it as score, and executes the indented code.
Loops can do more than print values. They can calculate totals, check conditions, transform data, call functions, and build new collections.
Calculating a Total
prices = [10, 20, 15]
total = 0
for price in prices:
total = total + price
print(total)The variable total starts at zero and is updated during each iteration. The final result is 45.
Understanding a While Loop
A while loop continues running as long as its condition evaluates to true.
A Simple Counter
count = 1
while count <= 5:
print(count)
count = count + 1The loop starts with count = 1. After each iteration, the value increases until the condition is no longer true.
If the condition in a while loop never becomes false, the loop may continue indefinitely. Make sure something in the loop moves the program toward its stopping condition.
Putting Variables, Functions, and Loops Together
These concepts become more useful when they work together. Consider a small program that converts several temperatures from Celsius to Fahrenheit.
Combining the Concepts
def celsius_to_fahrenheit(celsius):
return (celsius * 9 / 5) + 32
temperatures = [0, 10, 20, 30]
for temperature in temperatures:
converted = celsius_to_fahrenheit(temperature)
print(converted)Several things are happening here:
- temperatures stores a collection of values;
- celsius_to_fahrenheit() contains the conversion logic;
- the for loop processes each temperature; and
- converted stores each returned result during the loop.
Breaking a program into these smaller ideas makes it easier to understand how the overall logic works.
Common Beginner Mistakes
1. Using unclear variable names
Names such as x and a1 may be appropriate in some contexts, but descriptive names usually make application code easier to understand.
2. Confusing strings and numbers
User input is often received as text. A value may need to be converted before numerical calculations can be performed.
3. Forgetting to return a value from a function
Displaying a result with a print statement is not the same as returning that result for use elsewhere in the program.
4. Creating an infinite while loop
If the loop condition never changes, the program may continue executing the same block indefinitely.
5. Getting indentation or block structure wrong
Programming languages use different ways to define blocks of code. In Python, indentation is part of the syntax and changes which statements belong to a function, loop, or condition.
6. Writing repeated code instead of using a function
If the same logic appears repeatedly, consider whether it can be placed in a function rather than copied throughout the program.
Check Your Understanding
Can I explain what value a variable currently contains?
Do I understand the type of data stored in that variable?
Can I explain what a function is designed to do?
Do I know what information is passed into the function?
Do I know what the function returns?
Can I identify what causes a loop to repeat?
Can I identify when the loop stops?
Can I trace how the variables, functions, and loops interact in a small program?
If you can answer those questions while reading a short piece of code, you already understand much of the logic behind basic programming.
Need Help Understanding Your Code?
Share your code, programming language, project instructions, expected output, and the part that is causing difficulty. The logic can then be worked through in the context of your actual project.
