How would i get this newcommands.index work? - python

What I'm trying to do is get the position of the users input so if they recall a command it will return the value but it doesn't work for some reason idk why I've tried everything I know please help.
#new file
#new untitled file
args = []
newcommands = []
import time,random,os,sys
commands = ["help","version","python"]
while True:
command = input(">")
if command not in commands:
print("That command does not exist")
if command == "help":
print(commands)
if command == "version":
print("Version = 0.0.1")
if command == "python":
print("Type exit to exit the python interperter")
os.system("python")
if command == "DM ME A COMMAND":
pass
if command == "New":
if len(newcommands) != 5:
name = input("Enter a name: ")
text= input("Enter text for the function: ")
q = newcommands.append(name)
args.append(text)
if q == newcommands.index(0):
print(args.index(0))
if q == newcommands.index(1):
print(args.index(1))
if q == newcommands.index(2):
print(args.index(2))
if q == newcommands.index(3):
print(args.index(3))
if q == newcommands.index(4):
print(args.index(4))
if q == newcommands.index(5):
print(args.index(5))

i dont know what are you trying to do but seems your logic is more than i could understand
because you try to enter New command which is not on the list it means it will never execute the if condition for the "New"
and if that's not all you also try to get command line args which will never given by the user.
so basically please give the description of you question

Related

Trouble Understanding Python Scope

I have trouble understanding Python Scope. If you can help, I'll be thankful.
This is my code:
def msgCmd(x):
if x[0] == '/':
cmd = x[1:len(x)]
print(cmd)
def Cmd(x):
if x == "hello":
print("Hi how can I help you?")
elif x == "music":
print("Let's rock!")
while 1:
inp = input()
cmd = ''
msgCmd(inp)
Cmd(cmd)
I am essentially trying to type in a command using /command and get two results. One being only the command name following slash and the other being a result of what it did. Say, I enter /music. I am expecting 'music' as the first result and 'Let's rock!' as the next. But, somehow I am failing to retrieve the second desired result, possibly due to a Python Scope problem.
Also, please explain why this code works as it should when I add global cmd at the top of the function msgCmd(x) like this:
def msgCmd(x):
global cmd
if x[0] == '/':
cmd = x[1:len(x)]
print(cmd)
And, why doesn't it run as desired when global cmd added here outside function:
global cmd
def msgCmd(x):
if x[0] == '/':
cmd = x[1:len(x)]
print(cmd)
or here within the while loop:
while 1:
inp = input()
cmd = ''
msgCmd(inp)
global cmd
Cmd(cmd)
return the value of msgCmd first:
def msgCmd(x):
if x[0] == '/':
cmd = x[1:len(x)]
return cmd # right here
then get the value of that function so you can pass that value to another function:
...
cmd_str = msgCmd(inp)
Cmd(cmd_str)

Noob with a syntax error in dictionary (python)

I am trying to learn Python following the tutorial from Programming with Mosh.
I have created a program that starts up and greets me and then asks me to select an item on a list. Each list item is a "sub-program" that the tutorial covers. So I have two sub-programs in my program:
A chat translator that should return text and, via a dictionary, convert :) and :( to emojis
Then also a square calculator.
The problem I am facing is that my chat translator runs into a syntax error in the dictionary. This is where the error happens, at the first quotation mark in line 2 of the dictionary:
C:\Users\smelt\PycharmProjects\HelloWorld\venv\Scripts\python.exe C:/Users/smelt/PycharmProjects/HelloWorld/venv/app.py
File "C:\Users\smelt\PycharmProjects\HelloWorld\venv\app.py", line 41
":(": emoji.emojize(":frowning_face:")
^
SyntaxError: invalid syntax
Part of the code the error happens in:
def emoji_converter(message):
words = message.split(" ")
emojis = {
":)": emoji.emojize(":smiling_face:"),
":(": emoji.emojize(":frowning_face:")
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
This is my entire code:
first_name = "Henrik"
last_name = "Skaaning"
program_on = True
calculator_on = False
emoji_converter_on = False
def greet_user(first_name, last_name):
# Standard greeting to user
print(f"""Hi {first_name} {last_name}!
Welcome back!
""")
if program_on:
while program_on:
greet_user(first_name, last_name)
selection = input(f"""This is Training program for Henrik Skaaning.
please enter a number to select a program to run
1: Emoji converter
2: Square calculator
enter "quit" to quit program...
selection> """)
if selection == "1":
emoji_converter_on = True
print(f'Emoji converter on')
while emoji_converter_on:
import emoji
def emoji_converter(message):
words = message.split(" ")
emojis = {
":)": emoji.emojize(":smiling_face:"),
":(": emoji.emojize(":frowning_face:")
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
message = input("message> ")
if message != "help":
if message != "quit":
print(emoji_converter(message))
if message == "help":
print(f"""This is a simple emoji converter developed by Henrik Skaaning.
Type a text in the command line with an emoji to return the text and emoji.
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if message == "quit":
emoji_converter_on = False
print(f'Emoji converter shutting off')
if selection == "2":
calculator_on = True
print(f'Square calculator on')
while calculator_on:
def square(number):
return int(number) * int(number)
number = input("commandline> ")
if number == "quit":
program_on = False
calculator_on = False
print(f'Executing')
if number != "quit":
if number != "help":
if number.isnumeric() != True:
print(f"Sorry! That isnt a command i understand")
if number == "help":
print(f"""This is a simple square calculator developed by Henrik Skaaning.
Type a number in the command line to return the square of that number
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if number.isnumeric():
result = square(number)
print(f' The result is {result}')
if program_on == False:
print(f'Program shut down')
print(f'Done...')
While it is possible to define a function within another function, and sometimes using a closure makes things easier, this code has a really long mainline with a function defined within a while loop. This code would be better and easier to understand if it was written with the functions separated. Otherwise, as you now know, it can be hard to debug.
The actual problem is that you have confused the syntax for a Python dict and JSON. A dict requires symbol / value pairs, while JSON requires string / value pairs.
Below is a reorganized program for you. The bug was not corrected.
first_name = "Henrik"
last_name = "Skaaning"
program_on = True
calculator_on = False
emoji_converter_on = False
def emoji_converter(message):
words = message.split(" ")
emojis = {
":)": emoji.emojize(":smiling_face:"),
":(": emoji.emojize(":frowning_face:")
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
def greet_user(first_name, last_name):
# Standard greeting to user
print(f"""Hi {first_name} {last_name}!
Welcome back!
""")
if program_on:
while program_on:
greet_user(first_name, last_name)
selection = input(f"""This is Training program for Henrik Skaaning.
please enter a number to select a program to run
1: Emoji converter
2: Square calculator
enter "quit" to quit program...
selection> """)
if selection == "1":
emoji_converter_on = True
print(f'Emoji converter on')
while emoji_converter_on:
import emoji
message = input("message> ")
if message != "help":
if message != "quit":
print(emoji_converter(message))
if message == "help":
print(f"""This is a simple emoji converter developed by Henrik Skaaning.
Type a text in the command line with an emoji to return the text and emoji.
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if message == "quit":
emoji_converter_on = False
print(f'Emoji converter shutting off')
if selection == "2":
calculator_on = True
print(f'Square calculator on')
while calculator_on:
def square(number):
return int(number) * int(number)
number = input("commandline> ")
if number == "quit":
program_on = False
calculator_on = False
print(f'Executing')
if number != "quit":
if number != "help":
if number.isnumeric() != True:
print(f"Sorry! That isnt a command i understand")
if number == "help":
print(f"""This is a simple square calculator developed by Henrik Skaaning.
Type a number in the command line to return the square of that number
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if number.isnumeric():
result = square(number)
print(f' The result is {result}')
if program_on == False:
print(f'Program shut down')
print(f'Done...')
Now that you know you need a symbol instead of strings like ":)" and ":(", can you fix it yourself?
Hint: use string substitution instead of a dict. Convert all ":)" strings to ":smiling_face:", and ":(" strings to ":frowning_face:", like:
message.replace(":)", ":smiling_face:").replace(":(", ":frowning_face:")
The corrected program should be noticeably shorter.
The code you have posted is not the code you ran to generate that error message. It does not give a syntax error and the line in the error is now on line 33 not 41 as in the stacktrace.
My guess is that you missed the comma after the first dict entry
emojis = {
":)": emoji.emojize(":smiling_face:")
":(": emoji.emojize(":frowning_face:")
}
gives the error you got.

Continuous results from a single function call

I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...

Break out of double while loops? [duplicate]

This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Python - `break` out of all loops [duplicate]
(4 answers)
Closed 8 years ago.
Hello i have this login that i am trying to make and when i get to the command screen if i want to exit out of the program i type "exit", but the problem is i have it in a double while loop and don't know how to break out of both. Here is an example of the code:
a = 0
b = 0
loginatt = 0
while a == 0:
if loginatt == 4:
print "Too many tires!"
break
password = raw_input("Password: ")
if password == "test":
b = 1
while b == 1:
command = raw_input("command: ")
if command == "exit":
break
else:
loginatt += 1
print "error, login failed!"
this part of the code won't break out of the double while loop:
command = raw_input("command: ")
if command == "exit":
break
break will only leave one level of looping. You could try resetting your outer loop variable:
if command == "exit":
a = 1
break
However, it might be better to break your code up a bit:
def access_control(correct_pass="test", attempts=4):
"""Control access to the supplied function func."""
for _ in range(attempts):
password = raw_input("Password: ")
if password == correct_pass:
get_commands()
break
else:
print "Incorrect password."
else:
print "Too many tries."
def get_commands():
"""Take user input until they enter 'exit'."""
while True:
command = raw_input("Command: ")
if command == "exit":
break
You can now call access_control to enter the password; if correct, you will be passed on to get_commands:
>>> access_control()
Password: test
Command: exit
>>>
or
>>> access_control()
Password: foo
Incorrect password.
Password: bar
Incorrect password.
Password: baz
Incorrect password.
Password: python
Incorrect password.
Too many tries.
>>>
There is no keyword to break from more than one loop. You can try the following:
wantToBreak = False
while b == 1:
command = raw_input("command: ")
if command == "exit":
wantToBreak = True
break
if wantToBreak:
break
It utilizes a boolean variable which indicates whether the flow should be interrupted (break more levels).
Generally variable names like a and b aren't very explicit. Also your login functionality is independent of your command functionality, hence why not seperate both?
#! /usr/bin/python2.7
def login(maxTries = 4):
while maxTries:
password = raw_input('Password: ')
if password == 'test':
return True
maxTries -= 1
print 'Too many tries.'
return False
def runCommand():
while True:
command = raw_input('Command: ')
if command == 'exit': break
print 'processing command', command
if login(): runCommand()
Instead of breaking when finding the command exit you can also use an iterator with a sentinel:
def runCommand():
for command in iter(lambda: raw_input('Command: '), 'exit'):
print 'processing command', command

Subprocess.call & check_output Python2.7

I was reading about the subprocess module and have gotten very confused. Under my search function, I wanted to use subprocess.check_output to return a printed error message of my chosing when grep failed to find the users input in the text file. How would I go about doing this? Using Python 2.7
import subprocess
def menu():
usr = raw_input("Press 1 if you are creating a new entry, press 2 for search or 3 to exit")
if usr == '1':
collect()
if usr == '2':
search()
if usr == '3':
sys.exit()
if usr == '4':
subprocess.call(['vim', '-c', '10', 'book.txt'])
def search():
inp = raw_input("Please enter a name:")
subprocess.call(['rgrep', '-e', inp])
search()
def collect():
def do_global():
global name, ac, number
name = raw_input("Name")
ac = raw_input("Area Code")
if subprocess.call(['rgrep', '-e', inp]) != 0: # rgrep failed
print("error message of your choosing")
To find out what exit status grep may produce, see its man page

Categories

Resources