Python - if Statement


In Python, the if statement is used to execute a block of code only if a specified condition is true. It's part of conditional statements that allow decision-making in code.

Syntax


 

if condition:
    # code to execute if the condition is true

Example


 

x = 10

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

Explanation

  • if: This keyword introduces the condition.
  • condition: This is a logical statement that evaluates to True or False.
  • :: A colon follows the condition.
  • Indentation: The code block that follows must be indented.

Adding else

You can add an else statement to handle cases where the condition is not true:


 

x = 3

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

Using elif for Multiple Conditions

The elif keyword allows testing multiple conditions:


 

x = 5

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")
 

Logical Conditions

You can use comparison operators (e.g., >, <, ==, etc.) and logical operators (e.g., and, or, not).

Example using and:


 

x = 7
if x > 5 and x < 10:
    print("x is between 5 and 10")

Let me know if you'd like more details on conditions or operators!


<h3>Example:</h3>

<div class="code-editor">
    <textarea id="code" name="code" rows="5">
x = 10

if x > 5:
    print("x is greater than 5")
    </textarea>
</div>
<button id="runCode" class="btn btn-primary mt-2">Run</button>

<div id="output" class="mt-3">
    <h4>Output:</h4>
    <pre id="codeOutput"></pre>
</div>

<script>
    // Initialize CodeMirror editor
    var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: true,
        mode: "python",
        theme: "default"
    });

    // Function to handle code execution
    document.getElementById("runCode").addEventListener("click", function() {
        var code = editor.getValue();
        fetch("{% url 'run_code' %}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify({ code: code })
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById("codeOutput").textContent = data.output;
        })
        .catch(error => {
            document.getElementById("codeOutput").textContent = "Error: " + error;
        });
    });
</script>
 




Enroll Now

  • Python Programming
  • Machine Learning