Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to pass boolean command line arguments to a Python program

Command-line argument parsing is a crucial aspect of building robust and user-friendly Python applications. The argparse module in Python's standard library provides a powerful and convenient way to parse command-line arguments.

However, when it comes to passing boolean values as command-line arguments, we encounter difficulties because there is no native boolean data type in Python so we must implement our own logic to do so.

Boolean values are fundamental in programming, representing two states: True and False. For a situation where you will need boolean values consider a program that takes two boolean arguments - one representing whether it is raining and another representing whether you have an umbrella and deciding whether you can go out. If it is raining you need an umbrella to go out. If it is not raining, it doesn’t matter whether you have an umbrella or not. We would like to implement this logic in the program given the values in the command line arguments.

Passing boolean command line arguments to your Python program

For this purpose we will create two flags (“--raining” and “--umbrella”) to use in our program. If it is raining (--raining=True), you need an umbrella (--umbrella=True) to go out. If it is not raining (--raining=False), it doesn't matter whether you have an umbrella (--umbrella=True or --umbrella=False). In this scenario, --raining and --umbrella are the two boolean arguments that the program should accept from the command line. The goal is to create a user-friendly Python program that handles boolean arguments appropriately and communicates the decision about going out to the user.

import argparse as a

def create_parser():
    parser = a.ArgumentParser()
    parser.add_argument('--raining', action='store_true')
    parser.add_argument('--umbrella', action='store_true')
    return parser

def can_go_out(raining, umbrella):
    if raining:
        if umbrella:
            return True
        else:
            return False
    else:
        return True

def main():
    parser = create_parser()
    args = parser.parse_args()

    raining = args.raining
    umbrella = args.umbrella

    result = can_go_out(raining, umbrella)

    if result:
        print("You can go out!")
    else:
        print("It is better to stay indoors.")

if __name__ == "__main__":
    main()

In the above code, a.ArgumentParser() creates the argument parser. The two arguments, --raining and --umbrella, are defined using parser.add_argument(). We use the action='store_true' argument to specify that these are boolean arguments. When these arguments are provided on the command line, argparse will automatically set their values to True.

The can_go_out function implements the logic we desire. We first check whether it is raining (raining). If it is raining, we then check whether the user has an umbrella (umbrella). If both conditions are true, we return True, indicating that the user can go out. If it is raining, but the user doesn't have an umbrella, we return False, indicating that the user should not go out. If it is not raining, we simply return True, indicating that the user can go out regardless of whether they have an umbrella or not.

In the main() function, we first create the argument parser using create_parser(). Then, we call parser.parse_args() to parse the command-line arguments. The parsed values for --raining and --umbrella are stored in args.raining and args.umbrella, respectively. We then call the can_go_out() function with the parsed boolean arguments raining and umbrella and store the result in the result variable. Finally, based on the result, we display a message to the user indicating whether they can go out or not.

Here are some sample runs:

>python main.py --raining
It is better to stay indoors.

>python main.py --raining --umbrella
You can go out!

>python main.py --umbrella
You can go out!

You can also set default values using the “default=False” option.

To make your program more user-friendly you can write more helpful messages at each step of argument parsing, like so (only the create_parser function is modified):

def create_parser():
  parser = a.ArgumentParser(description="Determine whether you can go out
            based on the weather conditions.")
  parser.add_argument('--raining', action='store_true', 
          help='Specify whether it is raining (True or False)')
  parser.add_argument('--umbrella', action='store_true', 
          help='Specify whether you have an umbrella (True or False)')
  return parser

If you run your code with the “-h” option you will get a helpful message like so:

python main.py -h
usage: main.py [-h] [--raining] [--umbrella]

Determine whether you can go out based on the
weather conditions.

options:
  -h, --help  show this help message and exit
  --raining   Specify whether it is raining (True
              or False)
  --umbrella  Specify whether you have an
              umbrella (True or False)

Finally, you will notice that the program will function in the absence of any flags. If you do not want to use default values (as mentioned earlier), you will need to account for that usecase. Below is the complete program that does not use default values and will complain if at least one value is not provided.

import argparse as a
import sys


def create_parser():
    parser = a.ArgumentParser(description=
          "Determine whether you can go out 
            based on the weather conditions.")
    parser.add_argument('--raining', action='store_true', 
        help='Specify whether it is raining (True or False)')
    parser.add_argument('--umbrella', action='store_true', 
        help='Specify whether you have an umbrella (True or False)')
    return parser


def can_go_out(raining, umbrella):
    if raining:
        if umbrella:
            return True
        else:
            return False
    else:
        return True


def main():
    parser = create_parser()
    args = parser.parse_args()

    if not any(vars(args).values()):
        print("No arguments provided. 
              Please use --raining and/or --umbrella.")
        sys.exit(1)

    raining = args.raining
    umbrella = args.umbrella

    result = can_go_out(raining, umbrella)

    if result:
        print("You can go out!")
    else:
        print("It is better to stay indoors.")


if __name__ == "__main__":
    main()

If we run it without any arguments like so:

>python main.py

we will get the error message:

No arguments provided. Please use --raining and/or --umbrella.

In summary it is easy to pass boolean arguments from the command line into your Python program with the use of flag arguments and parsing them using the argparse module in Python.

If you liked this blogpost, checkout our post on handling a list of command line arguments in your Python program.

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.