Understanding Variables, Loops, and Functions in Python
Understanding Variables, Loops, and Functions in Python
Python is one of the easiest programming languages to learn. If you're just starting your journey, three basic concepts to master are variables, loops, and functions. In this article, we’ll explain each of them in simple words with examples.
๐ธ What Are Variables in Python?
A variable is a name that stores data. You can think of a variable like a box that holds information.
✅ How to create a variable:
Here:
-
name
stores a string"Alice"
-
age
stores a number25
-
is_student
stores a booleanTrue
๐ Rules for variable names:
-
Must begin with a letter or underscore (
_
) -
Can include numbers, but not at the beginning
-
Cannot use Python keywords (like
if
,for
,def
, etc.)
๐ง Example:
Output:
๐ What Are Loops?
A loop is used to run the same block of code again and again.
Python has two main types of loops:
-
for
loop -
while
loop
๐น For Loop
Use a for loop when you want to repeat something a specific number of times.
Output:
The range(5)
function creates numbers from 0 to 4.
๐น While Loop
A while loop keeps running as long as the condition is True
.
Output:
⚠️ Make sure your while
loop ends eventually, or it may run forever!
๐ Looping Through Lists
You can loop through items in a list using for
.
Output:
๐งฎ What Are Functions?
A function is a block of code that you can reuse.
✅ Define a function using def
:
To run (call) the function:
๐ธ Functions with Parameters
You can pass values to functions.
Output:
๐ธ Functions that Return Values
You can return values from functions using return
.
Output:
๐ง Why Use Functions?
-
Avoid repeating code
-
Make code easy to read
-
Easy to test and debug
๐ Using Loops Inside Functions
You can mix loops and functions.
Output:
๐ก Practice Time!
Try writing a function that checks if a number is even:
๐ Final Project Example
Here’s a small program using all three:
Output:
๐ฏ Conclusion
Variables help store information. Loops help repeat tasks. Functions help organize your code. Together, they make Python powerful and easy to use.
Keep practicing, and you'll master them in no time!
Comments
Post a Comment