Programming Search⌘K

Taskintro

Write a conditional

Also called if else, if elif else, else if chain, if statement, choose between branches, letter grade from a score, Conditional structures.

Map a score to a letter grade with one if, else if and else chain, and put the tests in the right order so that each score takes exactly one branch.

Task

Choose one of several branches with a chain of if, else if and else. The function grade(score) takes a score from 0 to 100 and returns a letter grade:

  • "A" for a score of 90 or more,
  • "B" for a score from 80 to 89,
  • "C" for a score from 70 to 79,
  • "D" for a score from 60 to 69,
  • "F" for a score under 60.

For example, grade(85) is "B" and grade(60) is "D".

The Rosetta Code task asks for a list of the "conditional structures" of a language, and it names if-then-else and switch as the common ones1. This task uses the first of the two. Write a switch or match uses the second.

Solutions

Language The middle branches The last branch The condition
Python elif score >= 80: else: any value; Python tests its truth value2
JavaScript, TypeScript else if (score >= 80) { ... } else { ... } any value that is truthy or falsy3
Java else if (score >= 80) { ... } else { ... } boolean or Boolean4
C# else if (score >= 80) { ... } else { ... } a Boolean expression5
C else if (score >= 80) { ... } else { ... } a scalar value; zero is false6
C++ else if (score >= 80) { ... } else { ... } a value that converts to bool7
Go } else if score >= 80 { } else { a boolean expression; the braces are required8
Rust } else if score >= 80 { } else { a bool9
Bash elif ((score >= 80)); then else ... fi the exit status of a command10
  • One chain, one branch. The Python if statement "selects exactly one of the suites by evaluating the expressions one by one until one is found to be true"2. MDN describes the same rule for JavaScript: "The conditions are evaluated in order until one evaluates to true"3. So each test can use only the lower bound. When the test score >= 80 runs, the test score >= 90 was false already.
  • elif and else if. In Python, "The keyword ‘elif ’ is short for ‘else if’, and is useful to avoid excessive indentation"11. JavaScript has no special keyword: "Note that there is no elseif (in one word) keyword in JavaScript"3. An else if there is an else whose statement is another if. Java, C, C++ and C# work the same way.
  • Go. In the grammar of the Go if statement, the condition is followed by a Block, and an else is followed by another if or by a Block8. A block is a list of statements in braces, so the braces are required8. The condition is "a boolean expression"8.
  • Rust. if is an expression. "Because if is an expression, we can use it on the right side of a let statement to assign the outcome to a variable"9. The Rust solution has no return: the value of the chain is the value of the function.
  • Bash. In an if, "The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed"10. The test ((score >= 90)) is an arithmetic command, and its status is zero when the comparison is true. The function prints the grade.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • ninety, eighty-nine, sixty and fifty-nine: the scores on each side of a bound. A test written as score > 90 in place of score >= 90 gives "B" for 90, and only a case on the bound finds the mistake.
  • hundred and zero: the highest and the lowest score. The else branch takes 0 and each other score under 60.

Pitfalls

  • A wide test before a narrow test. The first true test wins, so the tests must go from the highest bound down. If the test score >= 60 comes first, it is true for 95 too, and the chain never reaches the test for "A"2:
def wrong(score):
    if score >= 60:
        return "D"
    elif score >= 70:
        return "C"
    elif score >= 80:
        return "B"
    elif score >= 90:
        return "A"
    else:
        return "F"


def right(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"


print([wrong(s) for s in (95, 85, 65, 40)])
print([right(s) for s in (95, 85, 65, 40)])
Output
['D', 'D', 'D', 'F']
['A', 'B', 'D', 'F']
  • The dangling else. In Java, C and C++, an if without braces can hold a second if, and then an else could belong to either of them. The JLS states that Java, "like C and C++ and many programming languages before them, arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong"4. The indentation does not change this:
public class Main {
    static void report(int score) {
        if (score >= 60)
            if (score >= 90)
                System.out.println(score + ": excellent");
        else
            System.out.println(score + ": failed");
    }

    public static void main(String[] args) {
        report(95);
        report(75);
        report(40);
    }
}
Output
95: excellent
75: failed

The else belongs to if (score >= 90), so 75 prints 75: failed and 40 prints nothing. C has the same rule: "An else is associated with the lexically nearest preceding if that is allowed by the syntax"6. Braces on each branch remove the doubt. The branches of a Go if are blocks, so Go does not have this problem8.

  • A condition that is not a boolean. Python and JavaScript test the truth value of any value. In JavaScript, the condition is "An expression that is considered to be either truthy or falsy"3. In C, "the first substatement is executed if the expression compares unequal to 0"6. Rust does not convert: "Unlike languages such as Ruby and JavaScript, Rust will not automatically try to convert non-Boolean types to a Boolean"9. Java also requires a boolean: the expression "must have type boolean or Boolean , or a compile-time error occurs"4.

This code does not compile, on purpose.

fn main() {
    let score = 75;
    if score {
        println!("the score is not zero");
    }
}

The fix is an explicit comparison, such as if score != 0.

  • Write a switch or match: choose a branch by the value of one expression.
  • FizzBuzz: an if chain inside a loop, where the order of the tests matters too.
  • Conditional: the concept of a conditional in each language.

Code

The build runs the native tests of each language in a pinned toolchain.

grade.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-conditional/.

def grade(score: int) -> str:
    """Return the letter grade for a score from 0 to 100."""
    # The tests go from the highest bound down, so each test needs only one bound.
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"
test_grade.py 26 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-conditional/.

import pytest

from grade import grade

CASES = {
    "ninety-five": (95, "A"),
    "eighty-five": (85, "B"),
    "seventy-five": (75, "C"),
    "sixty-five": (65, "D"),
    "forty": (40, "F"),
    "hundred": (100, "A"),
    "zero": (0, "F"),
    "ninety": (90, "A"),
    "eighty-nine": (89, "B"),
    "sixty": (60, "D"),
    "fifty-nine": (59, "F"),
}


@pytest.mark.parametrize("name", CASES)
def test_grade(name):
    score, want = CASES[name]
    assert grade(score) == want
grade.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

#include "grade.hpp"

std::string grade(int score) {
    if (score >= 90) {
        return "A";
    } else if (score >= 80) {
        return "B";
    } else if (score >= 70) {
        return "C";
    } else if (score >= 60) {
        return "D";
    } else {
        return "F";
    }
}
grade.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

#pragma once

#include <string>

// grade returns the letter grade for a score from 0 to 100.
std::string grade(int score);
test_grade.cpp 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

#include "grade.hpp"

#include <iostream>
#include <string_view>

static int failures = 0;

static void check(std::string_view name, int score, std::string_view want) {
    if (grade(score) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("ninety-five", 95, "A");
    check("eighty-five", 85, "B");
    check("seventy-five", 75, "C");
    check("sixty-five", 65, "D");
    check("forty", 40, "F");
    check("hundred", 100, "A");
    check("zero", 0, "F");
    check("ninety", 90, "A");
    check("eighty-nine", 89, "B");
    check("sixty", 60, "D");
    check("fifty-nine", 59, "F");
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Grade.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

final class Grade {
  private Grade() {}

  /** Returns the letter grade for a score from 0 to 100. */
  static String grade(int score) {
    if (score >= 90) {
      return "A";
    } else if (score >= 80) {
      return "B";
    } else if (score >= 70) {
      return "C";
    } else if (score >= 60) {
      return "D";
    } else {
      return "F";
    }
  }
}
GradeTest.java 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class GradeTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("ninety-five", 95, "A"),
        Arguments.of("eighty-five", 85, "B"),
        Arguments.of("seventy-five", 75, "C"),
        Arguments.of("sixty-five", 65, "D"),
        Arguments.of("forty", 40, "F"),
        Arguments.of("hundred", 100, "A"),
        Arguments.of("zero", 0, "F"),
        Arguments.of("ninety", 90, "A"),
        Arguments.of("eighty-nine", 89, "B"),
        Arguments.of("sixty", 60, "D"),
        Arguments.of("fifty-nine", 59, "F"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void grade(String name, int score, String want) {
    assertEquals(want, Grade.grade(score), name);
  }
}
grade.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

#include "grade.h"

const char *grade(int score) {
    if (score >= 90) {
        return "A";
    } else if (score >= 80) {
        return "B";
    } else if (score >= 70) {
        return "C";
    } else if (score >= 60) {
        return "D";
    } else {
        return "F";
    }
}
grade.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

#ifndef GRADE_H
#define GRADE_H

// grade returns the letter grade for a score from 0 to 100, as a string
// literal. The caller must not free it.
const char *grade(int score);

#endif
test_grade.c 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

#include "grade.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, int score, const char *want) {
    if (strcmp(grade(score), want) != 0) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
}

int main(void) {
    check("ninety-five", 95, "A");
    check("eighty-five", 85, "B");
    check("seventy-five", 75, "C");
    check("sixty-five", 65, "D");
    check("forty", 40, "F");
    check("hundred", 100, "A");
    check("zero", 0, "F");
    check("ninety", 90, "A");
    check("eighty-nine", 89, "B");
    check("sixty", 60, "D");
    check("fifty-nine", 59, "F");
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Grade.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

public static class Grade
{
    // Returns the letter grade for a score from 0 to 100.
    public static string Of(int score)
    {
        if (score >= 90)
        {
            return "A";
        }
        else if (score >= 80)
        {
            return "B";
        }
        else if (score >= 70)
        {
            return "C";
        }
        else if (score >= 60)
        {
            return "D";
        }
        else
        {
            return "F";
        }
    }
}
GradeTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

using Xunit;

public sealed class GradeTests
{
    public static TheoryData<string, int, string> Cases => new()
    {
        { "ninety-five", 95, "A" },
        { "eighty-five", 85, "B" },
        { "seventy-five", 75, "C" },
        { "sixty-five", 65, "D" },
        { "forty", 40, "F" },
        { "hundred", 100, "A" },
        { "zero", 0, "F" },
        { "ninety", 90, "A" },
        { "eighty-nine", 89, "B" },
        { "sixty", 60, "D" },
        { "fifty-nine", 59, "F" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int score, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Grade.Of(score));
    }
}
grade.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

/**
 * Returns the letter grade for a score from 0 to 100.
 * @param {number} score
 * @returns {string}
 */
export function grade(score) {
  if (score >= 90) {
    return "A";
  } else if (score >= 80) {
    return "B";
  } else if (score >= 70) {
    return "C";
  } else if (score >= 60) {
    return "D";
  } else {
    return "F";
  }
}
grade.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { grade } from "./grade.js";

const cases = [
  ["ninety-five", 95, "A"],
  ["eighty-five", 85, "B"],
  ["seventy-five", 75, "C"],
  ["sixty-five", 65, "D"],
  ["forty", 40, "F"],
  ["hundred", 100, "A"],
  ["zero", 0, "F"],
  ["ninety", 90, "A"],
  ["eighty-nine", 89, "B"],
  ["sixty", 60, "D"],
  ["fifty-nine", 59, "F"],
];

for (const [name, score, want] of cases) {
  test(name, () => {
    assert.equal(grade(score), want);
  });
}
grade.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

export type Grade = "A" | "B" | "C" | "D" | "F";

export function grade(score: number): Grade {
  if (score >= 90) {
    return "A";
  } else if (score >= 80) {
    return "B";
  } else if (score >= 70) {
    return "C";
  } else if (score >= 60) {
    return "D";
  } else {
    return "F";
  }
}
grade.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { grade } from "./grade.ts";

const cases: [string, number, string][] = [
  ["ninety-five", 95, "A"],
  ["eighty-five", 85, "B"],
  ["seventy-five", 75, "C"],
  ["sixty-five", 65, "D"],
  ["forty", 40, "F"],
  ["hundred", 100, "A"],
  ["zero", 0, "F"],
  ["ninety", 90, "A"],
  ["eighty-nine", 89, "B"],
  ["sixty", 60, "D"],
  ["fifty-nine", 59, "F"],
];

for (const [name, score, want] of cases) {
  test(name, () => {
    assert.equal(grade(score), want);
  });
}
grade.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

// Package grade maps a score to a letter grade.
package grade

// Grade returns the letter grade for a score from 0 to 100.
func Grade(score int) string {
	if score >= 90 {
		return "A"
	} else if score >= 80 {
		return "B"
	} else if score >= 70 {
		return "C"
	} else if score >= 60 {
		return "D"
	} else {
		return "F"
	}
}
grade_test.go 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

package grade

import "testing"

var cases = []struct {
	name  string
	score int
	want  string
}{
	{"ninety-five", 95, "A"},
	{"eighty-five", 85, "B"},
	{"seventy-five", 75, "C"},
	{"sixty-five", 65, "D"},
	{"forty", 40, "F"},
	{"hundred", 100, "A"},
	{"zero", 0, "F"},
	{"ninety", 90, "A"},
	{"eighty-nine", 89, "B"},
	{"sixty", 60, "D"},
	{"fifty-nine", 59, "F"},
}

func TestGrade(t *testing.T) {
	for _, c := range cases {
		if got := Grade(c.score); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}
grade.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

/// Returns the letter grade for a score from 0 to 100.
pub fn grade(score: i32) -> &'static str {
    // if is an expression, so the chain is the value of the function.
    if score >= 90 {
        "A"
    } else if score >= 80 {
        "B"
    } else if score >= 70 {
        "C"
    } else if score >= 60 {
        "D"
    } else {
        "F"
    }
}
tests/grade_test.rs 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-conditional/.

use algo_write_a_conditional::grade;

#[test]
fn cases() {
    let cases: &[(&str, i32, &str)] = &[
        ("ninety-five", 95, "A"),
        ("eighty-five", 85, "B"),
        ("seventy-five", 75, "C"),
        ("sixty-five", 65, "D"),
        ("forty", 40, "F"),
        ("hundred", 100, "A"),
        ("zero", 0, "F"),
        ("ninety", 90, "A"),
        ("eighty-nine", 89, "B"),
        ("sixty", 60, "D"),
        ("fifty-nine", 59, "F"),
    ];
    for &(name, score, want) in cases {
        assert_eq!(grade(score), want, "{name}");
    }
}
grade.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-conditional/.

# grade SCORE
# Prints the letter grade for a score from 0 to 100.
grade() {
  local score=$1
  if ((score >= 90)); then
    printf '%s\n' A
  elif ((score >= 80)); then
    printf '%s\n' B
  elif ((score >= 70)); then
    printf '%s\n' C
  elif ((score >= 60)); then
    printf '%s\n' D
  else
    printf '%s\n' F
  fi
}
test_grade.bats 25 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-conditional/.

setup() {
  source "$BATS_TEST_DIRNAME/grade.sh"
}

check() { # check SCORE WANT
  local got
  got=$(grade "$1")
  [ "$got" = "$2" ] || { printf 'got:  %s\nwant: %s\n' "$got" "$2"; return 1; }
}

@test "ninety-five" { check 95 A; }
@test "eighty-five" { check 85 B; }
@test "seventy-five" { check 75 C; }
@test "sixty-five" { check 65 D; }
@test "forty" { check 40 F; }
@test "hundred" { check 100 A; }
@test "zero" { check 0 F; }
@test "ninety" { check 90 A; }
@test "eighty-nine" { check 89 B; }
@test "sixty" { check 60 D; }
@test "fifty-nine" { check 59 F; }

References

  1. Conditional structures, Rosetta Code (the RosettaCodeData mirror), Task
  2. Compound statements, The Python Language Reference, 8.1 The if statement
  3. if...else, MDN Web Docs, Description
  4. The Java Language Specification, Java SE 25 Edition, 14.5 Statements (the dangling else problem); 14.9 The if Statement
  5. Selection statements, C# language reference, The if statement
  6. N1570, ISO/IEC 9899:201x Committee Draft (C11), 6.8.4.1 The if statement, paragraphs 1 to 3
  7. if statement, cppreference.com, Condition
  8. The Go Programming Language Specification, If statements
  9. Control Flow, The Rust Programming Language, if Expressions; Using if in a let Statement
  10. Conditional Constructs, Bash Reference Manual, if
  11. More Control Flow Tools, The Python Tutorial, 4.1 if Statements

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source