Skip to main content

Control flow in python with example

 In Python, control flow refers to the order in which statements are executed in a program. Control flow allows you to make decisions and execute certain code blocks based on conditions. There are several control flow statements in Python, including if-else statements, while loops, and for loops. Let's go through each of these with examples:

1. if-else statement:

The if-else statement allows you to execute a block of code if a certain condition is true, and another block of code if the condition is false.

```python
x = 10

if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

# Output: x is greater than 5
```

2. Nested if-else statements:

You can also use nested if-else statements to handle multiple conditions.

```python
x = 7

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

# Output: x is greater than 5
```

3. while loop:

The while loop allows you to repeatedly execute a block of code as long as a certain condition is true.

```python
count = 1

while count <= 5:
    print("Count is:", count)
    count += 1

# Output:
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
# Count is: 5
```

4. for loop:

The for loop is used to iterate over elements in a sequence, such as lists, tuples, or strings.

```python
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print("I like", fruit)

# Output:
# I like apple
# I like banana
# I like orange
```

5. break and continue statements:

- The `break` statement is used to exit a loop prematurely when a certain condition is met.

```python
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        break
    print(num)

# Output:
# 1
# 2
```

- The `continue` statement is used to skip the rest of the current iteration and move to the next iteration of the loop.

```python
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        continue
    print(num)

# Output:
# 1
# 2
# 4
# 5
```

6. else with loops:

In Python, you can use the `else` statement with loops to specify a block of code that should be executed when the loop completes normally without encountering a `break` statement.

```python
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)
else:
    print("Loop completed without encountering a break statement.")

# Output:
# 1
# 2
# 3
# 4
# 5
# Loop completed without encountering a break statement.
```

These control flow statements are essential for making decisions, iterating over data, and controlling the flow of execution in Python programs. They provide the flexibility needed to handle various scenarios and implement complex logic.

Comments

Popular posts from this blog

Web Programming: HTML, DHTML, XML, Scripting, Java, Servlets, Applets

 Web programming encompasses various technologies and concepts used to develop web applications. Let's explore each of them in detail: 1. HTML (Hypertext Markup Language): HTML is the standard markup language used to create the structure and content of web pages. It uses tags to define elements like headings, paragraphs, images, links, forms, etc. Example: ```html <!DOCTYPE html> <html> <head>     <title>My Web Page</title> </head> <body>     <h1>Hello, World!</h1>     <p>This is a paragraph.</p>     <img src="image.jpg" alt="Image">     <a href="https://www.example.com">Visit Example</a> </body> </html> ``` 2. DHTML (Dynamic HTML): DHTML is a combination of HTML, CSS, and JavaScript that allows web pages to become more dynamic and interactive. Example (DHTML with JavaScript): ```html <!DOCTYPE html> <htm...

Tokens, Identifiers, Data Types, Sequence Control, Subprogram Control, Arrays, Structures, Union, String, Pointers, Functions, File Handling, Command Line Argumaents, Preprocessors in C with example

 Let's discuss each concept briefly and provide examples for better understanding: 1. Tokens: Tokens are the smallest building blocks in C programming. They include keywords, identifiers, constants, strings, operators, and punctuators. Example: ```c #include <stdio.h> int main() {     int num = 42;  // 'int', 'main', 'return', '42', '=', ';' are tokens     printf("Hello, World!");  // 'printf', '(', ')', 'Hello, World!', ';', are tokens     return 0;  // 'return', '0', ';' are tokens } ``` 2. Identifiers: Identifiers are names used to identify variables, functions, or other user-defined entities. Example: ```c int age = 30;  // 'age' is an identifier (variable name) void displayMessage() {  // 'displayMessage' is an identifier (function name)     // function body } ``` 3. Data Types: Data types define the type of data that can be stored in ...

Place holder and control character in c language

 In the C programming language, placeholders and control characters are used to format and control the output of text in console-based programs. They are special characters or sequences of characters that have specific meanings. Here are the placeholders and control characters commonly used in C: 1. Placeholders:    - %d: Used to display signed integers.      Example: printf("The value is %d", 10);    - %u: Used to display unsigned integers.      Example: printf("The value is %u", 10);    - %f: Used to display floating-point numbers.      Example: printf("The value is %f", 3.14);    - %c: Used to display characters.      Example: printf("The character is %c", 'A');    - %s: Used to display strings (sequence of characters).      Example: printf("The string is %s", "Hello");    - %p: Used to display memory addresses (pointers)...