Practice: Python Scripts

« Read the chapter

Q1. Main guard message

BeginnerCoding

Write a program with a function main() that prints Script running, and call it only when the file is run directly.

Goal: Use the main guard.

Q2. Add two arguments

BeginnerCoding

Given the list args = ["4", "6"] (like sys.argv[1:]), convert both to int and print their sum.

Goal: Convert argument strings to numbers.

Q3. Parse a name option

IntermediateCoding

Using argparse, create a parser with an option --name (default World). Parse the list ["--name", "Ravi"] and print Hello, Ravi!

Goal: Use argparse options.

Q4. Flag with store_true

IntermediateCoding

Using argparse, add a flag --loud. Parse ["--loud"] and print HELLO if the flag is set, otherwise hello.

Goal: Use boolean flags.

Q5. Return an exit status

IntermediateCoding

Write main(numbers) that returns 0 and prints the largest number if the list is not empty, otherwise prints empty and returns 1. Call it with [3, 9, 4] and print the returned status.

Goal: Return exit codes from main.

Q6. Count lines from stdin text

IntermediateCoding

Use io.StringIO to simulate standard input containing three lines (a, b, c). Print how many lines you read.

Goal: Read input line by line.

Q7. Print to the error stream

BeginnerCoding

Write code that prints OK to standard output and WARNING to standard error. Only the standard output text appears in the expected output.

Goal: Separate stdout and stderr.

Q8. What does __name__ hold?

BeginnerOutput

What does this program print when it is run directly?

Code
print(__name__)

Goal: Know the value of __name__.

Q9. Slice of argv

BeginnerOutput

What does this print?

Code
argv = ["tool.py", "a", "b", "c"]
print(argv[1:])

Goal: Understand sys.argv layout.

Q10. Types from argv

BeginnerOutput

What does this print?

Code
args = ["2", "3"]
print(args[0] + args[1])

Goal: Remember arguments are text.

Q11. Guard blocks code

IntermediateOutput

What does this print when run directly?

Code
def hello():
    print("hello")

if __name__ == "__main__":
    print("main")
else:
    hello()

Goal: Trace the main guard.

Q12. argparse default

IntermediateOutput

What does this print?

Code
import argparse

p = argparse.ArgumentParser()
p.add_argument("--n", type=int, default=5)
args = p.parse_args([])
print(args.n * 2)

Goal: Use argparse defaults.

Q13. Positional and option

IntermediateOutput

What does this print?

Code
import argparse

p = argparse.ArgumentParser()
p.add_argument("word")
p.add_argument("-n", type=int, default=1)
a = p.parse_args(["ab", "-n", "3"])
print(a.word * a.n)

Goal: Combine positional and optional arguments.

Q14. Exit code from main

AdvancedOutput

What does this print?

Code
def main():
    data = []
    if not data:
        return 2
    return 0

status = main()
print("failed" if status else "ok")

Goal: Interpret exit statuses.

Q15. Fix the missing guard

BeginnerDebugging

This script is meant to run main() only when started directly, but it also runs when imported. Fix it.

Code
def main():
    print("work")

main()

Goal: Fix a missing main guard.

Q16. Fix the argument type

IntermediateDebugging

The script should print the double of the first argument 4, but it prints 44. Fix it.

Code
args = ["4"]
print(args[0] * 2)

Goal: Convert argument types.

Q17. Fix the error message stream

IntermediateDebugging

The error message below is written to standard output. Change it so that it goes to standard error and only OK remains on standard output.

Code
import sys

print("OK")
print("error: missing file")

Goal: Send errors to stderr.

Q18. Why not parse sys.argv by hand?

IntermediateConceptual

Give two reasons why argparse is better than reading sys.argv directly for larger scripts.

Goal: Compare sys.argv and argparse.

Q19. Meaning of exit code zero

BeginnerConceptual

What does an exit code of 0 mean and why do other tools care?

Goal: Understand exit statuses.

Q20. Design a cleanup script

AdvancedApplication

You must write a script that removes blank lines from a text file given on the command line. Describe the main parts of the script.

Goal: Design a small script.