# Pavan Kumpatla
# December 26, 2021.
# I learned about the terminal and how to use it.
# I had difficulties with task 2
# %cd command_line
# Note:
#Above was the original code given by Microsoft.
# This will work the first time, but if you re-run these cells
# you may encounter errors so we changed it to...
# ************** DO NOT MODIFY OR ADD ANYTHING TO THIS CODE SEGMENT ***********
# ************** Click Edit> Clear All Outputs ***********
# ************** This code segment must be run before attempting any of the tasks or examples in this lesson ********************
# ************** This cell is a reset cell to remove (if they exist) the parent_dir and any children or leaves
# It prepares the directories and files necessary to run the examples and complete the tasks.
# This cell can be run first then all others cells in this notebook can be run, then this cell can be rerun
# This is the reset. It uses the import shutil (or shell utility) which you will learn later in the course
import os, shutil # shutil = shell utility has an important method called rmtree()
# linux does not have an equivalent command!
# Navigate to `library` directory (if not already in it)
current_path = os.getcwd()
print(current_path)
if ("content" in current_path):
#JGif ("library" in current_path):
nb_path = current_path.split("content")[0] # nb_path = the 1st item in the split list
else:
nb_path = current_path
print("Changing working dir to directory above parent_dir")
os.chdir(os.path.join(nb_path,"content"))
current_path = os.getcwd()
print("Current working directory:", current_path)
if (os.path.exists('parent_dir') == True):
shutil.rmtree('parent_dir')
os.mkdir('parent_dir')
os.chdir('parent_dir')
os.mkdir('child1_dir')
os.chdir('../')
current_path = os.getcwd()
print("Current working directory:", current_path)#
#this magic code will be used as a reset the linux directory so the notebook can be rerun
%mkdir command_line
%cd command_line
!pwd
%%writefile main_script.py
# writes new file
# Start of Python code
# Will be called from another script
def func():
# creates new function
print("Running func")
# prints
# Execute when running the script directly
def main():
# creates new function
print("Running the main function")
# prints
if __name__ == "__main__":
# if __name__ equals to "__main__"
main()
# call main()
# I don't know why it says overwriting, might be because the above code won't run
%%bash
# returns value
python3 main_script.py
# runs code
%%writefile secondary_script.py
# creates new file
# Start of Python code
import main_script
# imports main_script
# call func() from the main script
main_script.func()
# from main_script, call func()
# It says overwriting again when I rerun it.
%%bash
# returns value of code
python3 secondary_script.py
# runs
# --> I thought it was supposed to have: "!" -- at the beginning?
# [ ] The following program asks the user for a circle radius then display the area and circumference
# Modify the program so it only displays the information when executed directly
# Hint: that would include name and main in there somehwere
# The program should not display anything if it is imported as a module
def function():
# creates new function
from math import pi
# from math, import pi
def area(r):
# creates new function with parameter
return pi * (r ** 2)
# returns
def circum(r):
# creates new function with parameter
return 2 * pi * r
# returns
radius = float(input("Enter radius: "))
# stores
print("Area =", area(radius))
# prints, calls
print("Circumference =", circum(radius))
# prints, calls
if __name__ == "__main__":
# if it is equal
function()
# run the function
# I'm not sure if the code is correct.
%cd command_line
# changes directory
%%bash
# returns value - I think?
ls
# lists
%%bash
# I'm not sure what this is
ls -l
# lists with more detail
%%bash
# ?
ls -l -a
# lists with more detail AND shows hidden files
!pwd
# prints working directory
%%bash
# ?
ls -l ../parent_dir
# lists with more detail and goes back to parent_dir
# Says error
%cd command_line
# changes directory
%pwd # notice you are still in command_line
# present working directory
# It says "\work"
%%writefile command_line.py
# creates new file
import sys
# imports sys
# Number of arguments
argc = len(sys.argv)
# stores length of arguments
print(argc, "arguments and options were passed")
# prints
# List of arguments and options
print("The arguments and options passed are: ")
# prints
for i in range(argc):
# for i in range of the arguments captured
print("argv[{:d}] = {}".format(i, sys.argv[i]))
# prints, formats
%%bash
# idk what this does
python3 command_line.py arg1 arg2 -option1 -option2
# runs
%pwd # notice you are still in command_line
# We're in "/work"
%%writefile rand.py
# writes new file
import argparse
# imports
from random import randint
# from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Parse command-line arguments
args = parser.parse_args()
# Program
print(randint(0, 10))
# prints random integer between 0-10
%%bash
# idk
python3 rand.py
# runs
%%bash
# idk
python3 rand.py -i
# runs but shows error since -i is not recognized
%%bash
# idk
python3 rand.py -h
# runs with argument
%%writefile rand.py
# writes file
import argparse
# imports
from random import randint
# from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Parse command-line arguments
args = parser.parse_args()
# Program
for i in range(args.count):
# for i in range of the arguments caught
print(randint(0, 10))
# prints random integer between 0-10
%%bash
# idk
python3 rand.py
# runs with error
%%bash
# idk
python3 rand.py -h
# runs with an extra argument
%%bash
# idk
python3 rand.py 4
# runs with argument
%%writefile rand.py
# writes file
import argparse
# imports
from random import randint
# from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = 'number', nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
# Parse command-line arguments
args = parser.parse_args()
# Program
for i in range(args.count):
# for i in range of the arguments caught
print(randint(args.range[0], args.range[1]))
# prints
%%bash
# idk
python3 rand.py 4
# runs with argument
%%bash
# idk
python3 rand.py 4 -r 500 1000
# runs with more arguments specifying the range
%%bash
# idk
python3 rand.py 4 --range 500 1000
# runs with more arguments specifying the range
%%bash
# idk
python3 rand.py 10 -r 500 1000
# runs with more arguments specifying the range
%%bash
# idk
python3 rand.py
# shows error
%%bash
# idk
python3 rand.py -h
# runs with an argument
%%writefile rand.py
# writes file
import argparse
# imports
from random import randint
# from random import randint
# define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
# parse command line arguments
args = parser.parse_args()
# program
for i in range(args.count):
# for i in range of the arguments caught
print(randint(args.range[0], args.range[1]))
# prints
%%bash
# idk
python3 rand.py -h
# runs with an argument
%%writefile rand.py
# writes
import argparse
# imports
from random import randint
# from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', metavar = 'rands', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
# Parse command-line arguments
args = parser.parse_args()
# Program
for i in range(args.count): # still accessed as args.count (not args.rands)
# for i in range of arguments caught
print(randint(args.range[0], args.range[1]))
# prints
%%bash
# idk
python3 rand.py -h
# runs with argument
%%writefile rand.py
# writes file
import argparse
# imports
from random import randint
# from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Verbose mode')
# Parse command-line arguments
args = parser.parse_args()
# Program
if args.verbose:
# if the argument has v or verbose
print("Generating {:d} random integer in the range [{:d}, {:d}]".format(args.count, args.range[0], args.range[1]))
# prints, formats
for i in range(args.count):
# for i in range of the arguments caught
print(randint(args.range[0], args.range[1]))
# prints
%%bash
# idk
python3 rand.py 4 --range 500 1000 -v
# runs with more arguments
%%bash
# idk
python3 rand.py -h
# runs with argument
%%writefile rand.py
# writes file
import argparse
# imports
from random import randint
# from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', action = 'store', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
parser.add_argument('-c', '--const', action = 'store_const', const = 10, default = 0, help = 'Generate 10 additional random numbers (in addition to Count)')
parser.add_argument('-m', '--multiply', action = 'count', help = 'Multiply the number of random numbers by the number of times this flag appears')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Verbose mode')
# Parse command-line arguments
args = parser.parse_args()
# Program
# If args.const is used, add 10 to the count entered by the user
num_of_rands = (args.count + args.const)
# adds and stores
# When args.multiply is not used, its value is None
if (args.multiply != None):
# if the arguments multiplied does not equal to None
num_of_rands = num_of_rands * args.multiply
# multiply and store
if args.verbose:
# if it is verbose
print("Generating {:d} random integer in the range [{:d}, {:d}]".format(num_of_rands, args.range[0], args.range[1]))
# prints
for i in range(num_of_rands):
# for i in range of num_of_rands
print(randint(args.range[0], args.range[1]))
# prints
%%bash
# idk
python3 rand.py 4 --range 500 1000 -v -c
# runs with more arguments
%%bash
# idk
python3 rand.py 4 --range 500 1000 -v -mmm
# runs with more arguments
%%bash
# idk
python3 rand.py -h
# runs with an argument
%%writefile day_finder.py
# writes
# [ ] Write a program that reads a date (month, day, year) as command-line arguments in order
# then prints the day of the week for that date.
# If an optional flag (-c or --complete) is specified, the program should print the full date (not only the day of the week).
# The help message should look like:
'''
usage: day_finder.py [-h] [-c] month day year
positional arguments:
month Month as a number (1, 12)
day Day as a number (1, 31) depending on the month
year Year as a 4 digits number (2018)
optional arguments:
-h, --help show this help message and exit
-c, --complete Show complete formatted date
'''
# IMPORTANT - all previous cells need to have been run (in order) BEFORE writing and running this cell.
# HINT: Use a date object with strftime
from datetime import date
import argparse
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('month', action = 'store', type = int, help = 'Month as a number (1, 12)')
parser.add_argument('day', action = 'store', type = int, help = 'Day as a number (1, 31) depending on the month')
parser.add_argument('year', action = 'store', type = int, help = 'Year as a 4 digits number (2018)')
# Add optional arguments
parser.add_argument('-h', '--help', action = 'store_true', help = 'show this help message and exit')
parser.add_argument('-c', '--complete', action = 'store_true', help = 'Show complete formatted date')
# Parse command-line arguments
args = parser.parse_args()
try:
# try
d = date(month = args.month, day = args.day, year = args.year)
# stores, dates
except Exception as exception_object:
# except error as exception_object
print(exception_object)
# prints error
else:
# else
if args.complete:
# if args.complete
print(d.strftime("%A %B %d, %Y"))
# prints
else:
# else
print(d.strftime("%A"))
# prints
%%bash
python3 day_finder.py 12 31 2017 -c
%%bash
python3 day_finder.py 12 31 2017
%%writefile sort_numbers.py
# [ ] Write a program that reads an unspecified number of integers from the command line,
# then prints out the numbers in an ascending order
# The program should have an optional argument to save the sorted numbers as a file named `sorted_numbers.txt`
# The help message should look like:
'''
usage: sort_numbers.py [-h] [-s] [numbers [numbers ...]]
positional arguments:
numbers int to be sorted
optional arguments:
-h, --help show this help message and exit
-s, --save save the sorted numbers on a file (sorted_numbers.txt)
'''
# IMPORTANT - all previous cells need to have been run (in order) BEFORE writing and running this cell.
# --Complete the following--
#HINT: use nargs = '*' in an add_argument method
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('numbers', action = 'store', nargs = '*', type = int, help = 'int to be sorted')
# Add optional arguments
parser.add_argument('-h', '--help', action = 'store_true', help = 'show this help message and exit')
parser.add_argument('-c', '--complete', action = 'store_true', help = 'save the sorted numbers on a file (sorted_numbers.txt)')
# Parse command-line arguments
args = parser.parse_args()
try:
# try
except Exception as exception_object:
# except error as exception_object
print(exception_object)
# prints error
else:
# else
if args.complete:
# if args.complete
f = open("sorted_numbers.txt", "w")
# open new file
f.write(args)
# writes
f.close()
# closes
print("The numbers have been saved.")
# prints
else:
# else
s = sorted(args)
# sorts arguments
print(s)
# prints
# I genuinely have no idea if I did this right.
%%bash
# idk
python3 sort_numbers.py 23 49 5 300 43 582 58 29 62 69 320 60
# runs with arguments