Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

If statements and conditional expressions


We have already seen conditional expressions in the context of while loops. Conditional expressions can be used with if statements to allow a program to make decisions while it is running. There are numerous applications for if statements. For example, they can be used to detect invalid values and prevent errors:

input_value = 1e99
if input_value > 1e10:
    print("Warning: invalid parameter detected.")
else:
    print("--- Start of iteration ---")

The general syntax for an if statement is the following:

if conditional_expression:
    statements
else:
    statements

The else clause is optional. Python doesn't have a switch statement for choosing between multiple values. Instead, it has a special keyword called elif, which is a contraction of "else if." This can be used to emulate a switch statement. For example, we can use if with elif to choose an algorithm based on user input:

solution_type = "numerical"

if solution_type == "analytical":
    print...