Skip to content

Commit 975ff65

Browse files
committed
Refactoring the code
1 parent f1b0550 commit 975ff65

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

implement-cowsay/cow.py

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,28 @@
11
import cowsay
22
import argparse #helps you collect the words typed in command line
33

4-
parser = argparse.ArgumentParser(prog="cowsay", description ="Make Animals say things")
5-
parser.add_argument(
6-
"--animal",
7-
choices = (cowsay.char_names),
8-
help = "The animal chosen to be saying things",
9-
default = "cow"
4+
def main():
5+
# Set up command-line parser
6+
parser = argparse.ArgumentParser(
7+
prog="cowsay",
8+
description="Make animals say things"
109
)
11-
parser.add_argument(
12-
"message",
13-
nargs="+", #tells argparse that this argument can accept one or more values and collect them into a list.
14-
help="The message to say."
15-
)
16-
args = parser.parse_args()
17-
18-
getattr(cowsay, args.animal)(" ".join(args.message)) #Python built‑in func that get an attribute from an object by name = cowsay module in our case.
19-
10+
parser.add_argument(
11+
"--animal",
12+
choices=cowsay.char_names, # fetch supported animals directly from cowsay
13+
default="cow",
14+
help="The animal chosen to be saying things"
15+
)
16+
parser.add_argument(
17+
"message",
18+
nargs="+", # accept one or more words as message
19+
help="The message to say"
20+
)
21+
args = parser.parse_args()
2022

23+
# Dynamically call the correct cowsay function
24+
say = getattr(cowsay, args.animal)
25+
say(" ".join(args.message))
2126

22-
#we now need to fetch animals from cowsay.char_names
23-
print(cowsay.char_names)
27+
if __name__ == "__main__":
28+
main()

0 commit comments

Comments
 (0)