Menu
CoddyTech

Conditional Value Selection

Lesson 10 of 48 in Coddy's Python for C Developers course.

Python if/elif/else expresses the same first-match priority as a C if/else-if chain. Test higher-priority cases first. Two independent if statements can both run, so the later one may overwrite a result. For a short value choice, Python writes first if condition else second instead of the C condition ? first : second form. Only the selected result expression is evaluated. Keep else at the indentation level of its matching if.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    int score = 8;
    const char *label = score >= 10 ? "high" : score >= 5 ? "mid" : "low";
    puts(label);
    return 0;
}

Python: complete example.py

score = 8
if score >= 10:
    label = "high"
elif score >= 5:
    label = "mid"
else:
    label = "low"
print(label)

Watch the difference

Do not emulate a conditional with and/or when the first result can be zero or empty. Those values would trigger the fallback even when the condition is true.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

Read a nonnegative total in cents and a membership token yes or no. Shipping costs 0 for totals at least 5000; otherwise it costs 200 for a member and 500 for a nonmember. Output the shipping number and then free for zero or paid otherwise.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

Keep the priority of the C if/else-if chain when writing Python if/elif.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C Developers

Practice on your own: Online Python compiler