-
Notifications
You must be signed in to change notification settings - Fork 0
/
name.py
60 lines (38 loc) · 1.32 KB
/
name.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
## command-line arguments
### ex. python hello.py ___
# import sys
# print("hello, my name is", sys.argv[1]) # Note that you are starting with 1 in sys.argv. This is because '0' would be the name of the file
# ## How to address the index error to the code above
# import sys
# try:
# print("hello, my name is", sys.argv[1])
# except IndexError:
# print("Too few arguments")
# ## Or using a Conditional
# import sys
# if len(sys.argv) < 2:
# print("Too few arguments")
# elif len(sys.argv) > 2:
# print("Too many arguments")
# else:
# print("hello, my name is", sys.argv[1])
# ## Using 'sys.exit' to tidy the code above
# import sys
# if len(sys.argv) < 2:
# sys.exit("Too few arguments")
# elif len(sys.argv) > 2:
# print("Too many arguments")
# print("hello, my name is", sys.argv[1])
# ## Addressing 'too many arguments'
# ## Note that this outputs an extra list that includes the file name
# import sys
# if len(sys.argv) < 2:
# sys.exit("Too few arguments")
# for arg in sys.argv:
# print("hello, my name is", arg)
## Using 'slice' to address the "issue" above
import sys
if len(sys.argv) < 2:
sys.exit("Too few arguments")
for arg in sys.argv[1:]: # this will start at 1 instead of 0; where 0 would have inluded "hello, my name is name.py"
print("hello, my name is", arg)