I made a program that can modify a list using commands that the user enters.
The commands that are supported are (used from actual program):
/add [value1] [value2] [valueN]...
- Add a value to the list/rvalue [value]
- Removes a value from the list/rindex [index]
- Removes the value at the specified index from the list/print
- Prints the list/help
- Lists every available command
Here is the code:
#Program to modify lists
value_list = []
def cmd_help():
print("/add [value1] [value2] [valueN]... - Add a value to the list")
print("/rvalue [value] - Removes a value from the list")
print("/rindex [index] - Removes the value at the specified index from the list")
print("/print - Prints the list")
print("/help - Lists every available command")
def get_command_params():
commands = {
"/add": lambda *value : value_list.extend(list(value)),
"/rvalue": lambda value : value_list.remove(value),
"/rindex": lambda value : value_list.pop(int(value)),
"/print": lambda : print(value_list),
"/help": cmd_help
}
while True:
input_cmd = input("Enter a command: ")
#Separate arguments
command = ""
current_args_index = -1
args = []
last_char = ""
for char in input_cmd:
#Update separator
if char == "/" or char == " ":
last_char = char
if last_char == "/":
command += char
elif last_char == "append":
args[current_args_index] += char
elif last_char == " ":
args.append("")
#To append individual characters to same index
last_char = "append"
++current_args_index
cmd = commands.get(command)
if cmd == None:
print("Invalid command!")
continue
return cmd, args
def main():
cmd_help()
#Wait for command
while True:
command, args = get_command_params()
#Execute command with arguments
try:
command(*args)
#Don't print success if command is print/help
if args != []:
print("Success!")
except IndexError:
print("Index out of range!")
except ValueError:
print("Element not found!")
except TypeError:
print("Invalid arguments! Type /help for help")
if __name__ == "__main__":
main()