Control Flow ,Functions and Loops
Pythons Tutorials
Control Flow:
Control flow structures allow you to control the flow of execution in your program. They include conditional statements like if
, else if
, and else
, as well as loops like for
and while
.
Example 1: Conditional Statements
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
- In Example 1, we use an
if
statement to check the value of thehour
variable. Depending on the condition, different messages will be logged.
Functions:
Functions allow you to group code into reusable blocks. They can take input, perform operations, and return a result.
Example 2: Creating a Function
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("John");
- Example 2 defines a function
greet
that takes aname
parameter and logs a greeting message to the console. - We then call the function with the argument
"John"
.
Loops: Repeating Actions
Loops allow you to repeat a block of code multiple times. We’ll cover for
and while
loops.
Example 3: Using a for
Loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i+1}`);
}
- Example 3 demonstrates a
for
loop that iterates five times, logging messages to the console.
Combining Control Flow and Functions
You can use control flow structures and functions together to create more complex behaviour.
Example 4: Function with Conditional Logic
function getDiscount(price, isPremiumMember) {
if (isPremiumMember) {
return price * 0.8; // 20% discount for premium members
} else {
return price;
}
}
let totalPrice = getDiscount(100, true);
console.log(`Total price: $${totalPrice}`);
- In Example 4, we define a
getDiscount
function that calculates the final price based on whether the customer is a premium member. - The function returns the discounted price.