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.
- Evidence
- Code in 10 languages
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
ifstatement "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 testscore >= 80runs, the testscore >= 90was false already. elifandelse 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. Anelse ifthere is anelsewhose statement is anotherif. Java, C, C++ and C# work the same way.- Go. In the grammar of the Go
ifstatement, the condition is followed by aBlock, and anelseis followed by anotherifor by aBlock8. A block is a list of statements in braces, so the braces are required8. The condition is "a boolean expression"8. - Rust.
ifis 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 noreturn: 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,sixtyandfifty-nine: the scores on each side of a bound. A test written asscore > 90in place ofscore >= 90gives"B"for 90, and only a case on the bound finds the mistake.hundredandzero: the highest and the lowest score. Theelsebranch 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 >= 60comes 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)])
['D', 'D', 'D', 'F']
['A', 'B', 'D', 'F']
- The dangling else. In Java, C and C++, an
ifwithout braces can hold a secondif, and then anelsecould 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);
}
}
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.
Related tasks
- Write a switch or match: choose a branch by the value of one expression.
- FizzBuzz: an
ifchain 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.
# 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
// 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;
}
// 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);
}
}
// 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;
}
// 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));
}
}
// 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);
});
}
// 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);
});
}
// 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)
}
}
}
// 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}");
}
}
#!/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
- Conditional structures, Rosetta Code (the RosettaCodeData mirror), Task
- Compound statements, The Python Language Reference, 8.1 The if statement
- if...else, MDN Web Docs, Description
- The Java Language Specification, Java SE 25 Edition, 14.5 Statements (the dangling else problem); 14.9 The if Statement
- Selection statements, C# language reference, The if statement
- N1570, ISO/IEC 9899:201x Committee Draft (C11), 6.8.4.1 The if statement, paragraphs 1 to 3
- if statement, cppreference.com, Condition
- The Go Programming Language Specification, If statements
- Control Flow, The Rust Programming Language, if Expressions; Using if in a let Statement
- Conditional Constructs, Bash Reference Manual, if
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 220A67 Edit this page History Report an error Markdown