Python Classroom notes 21/Dec/2024

Python Standard library

Call stack or Stack Trace

Preview

Exceptions

Random

sys

os, shutil

CLI Applications

  • CLI Application for calculator with sys
"""calc.py

This module contains functions and implementations to support
add
sub
mul
div
mod

Usage:
* python calc.py add 1 2
  3
* python calc.py sub 4 2
  2
"""

import sys


class InvalidArgs(Exception):
    pass


def main(args):

    if len(args) != 3:
        raise InvalidArgs
    operation = args[0]
    temp_args = args[1:]
    args = [int(arg) for arg in temp_args]
    if operation.lower() == "add":
        print(args[0] + args[1])
    elif operation.lower() == "sub":
        print(args[0] - args[1])
    elif operation.lower() == "mul":
        print(args[0] * args[1])
    elif operation.lower() == "div":
        print(args[0] // args[1])
    elif operation.lower() == "mod":
        print(args[0] % args[1])
    else:
        print("unsupported opearation {operation}")


if __name__ == "__main__":
    args = sys.argv[1::]
    try:
        main(args)
    except InvalidArgs:
        print("############################")
        print("Usage is as shown below")
        print("python calc.py add 1 2")
        print("Supported operations are add sub mul div mod")

  • Argparse module gives us a better way of building cli applications Refer Here for official docs and Refer Here for realpython document
  • Refer Here for simple CLI based calculator

exercise

  • Write a class called as Number which takes an integer
n1 = Number(10)
  • Now add methods
    • is_even
    • is_prime
    • is_pallendrome

list comprehensions

Published
Categorized as Uncategorized Tagged

By continuous learner

devops & cloud enthusiastic learner

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Please turn AdBlock off
Animated Social Media Icons by Acurax Responsive Web Designing Company
Visit Us On FacebookVisit Us On LinkedinVisit Us On Youtube