Trouble Understanding Python Scope - python

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)

Related

How would i get this newcommands.index work?

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

Python try and except bug (probably)

I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.

Python script isn't working

I wrote this script for a program I'm writing ever since I changed careers but running into a lot of issues with it. Supposed to take a string and encrypt it with a key. Not sure where to begin with troubleshooting as I'm new to programming so came here for help. Maybe if you can just point me in the write direction where to begin?
This is the error I get but looks fine.
$ python temp.py -p "ThisIsATestOfMyCode" -k "testtest"
File "encrypt.py", line 37
else:
^
This is my code.
#!/usr/bin/env python
import sys, argparse
def encrypt(varAble1, varAble2):
varAble1_size = len(varAble1)/float(len(varAble2))
if str(varAble1_size).split(".")[1] == "0":
else:
while str(varAble1_size).split(".")[1] != "0":
varAble1 +== "#"
varAble1_size = len(varAble1)/float(len(varAble2))
code = []
varAble1 = list(varAble1)
varAble2 = list(varAble2))
multiply_size = int(str((varAble1_size)).spliy(".")[0]) * 8
while varAble1 != []:
p_varAble1 = varAble1[0:8]
p_varAble2 = varAble2[0:8]
temp_list = []
for i in xrange(0,8):
if type(p_varAble2[i]) == type(int):
new_ct = (ord(chr(p_varAble2[i])) ^ ord(p_varAble1[0]))
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
code.append(new_ct)
temp_list.append(new_ct)
varAble1.pop(0)
p_varAble1.pop(0)
varAble2 = temp_list
varAble2.reverse()
code.reverse()
varAble1 = code.reverse()
code_text = []
for i in code:
hex_value = hex(i)
if len(hex_value) != 4:
code_text.append("0" + hex(i)[2:])
else:
code_text.append(hex(i)[2:])
varAble2 += i
code_text = "".join(code_text).upper()
return code_text
def main():
parser = argparse.ArgumentParser(description="Encrypt things")
parser.add_argument("-p", "--var1",help="String to enc",metavar='<pt>', required=True)
parser.add_argument("-k", "--var2", help="8 length key to encrypt with", metavar='<key>', required=True)
args = parser.parse_args()
var1 = args.var1
var2 = args.var2
hash = encrypt(var1, var2)
print "[+] Encrypted using %s [+]\n%s" % (var2, hash)
if __name__ == "__main__":
main()
The block of if str(varAble1_size).split(".")[1] == "0": is empty, so you will need to add a pass statement after it. Keef Baker is also correct in spotting that the block for else: on line 37 is not properly indented.
You have to indent your code after else :
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
And as Andrew Kulpa noted, the block after
if str(varAble1_size).split(".")[1] == "0":
is empty, so you either need to do something in that block, or add a pass statement.
Python does not use brackets but indentation for control flow.
In your code, the Python interpreter sees an else but no statement for it, so it throws an error.
See more about control flow here : https://docs.python.org/3/tutorial/controlflow.html

Making two functions print their output on the same line

I'm making an interpreter, and I have a function called parse(). The parse function returns some output.
I'm making a command that prints two command's outputs on the same line instead of on separate lines.
I have the following code:
def print_command2(command):
command = command.split("_") # The underscore separates the two commands
command[0] = command[0].strip("! ") # The command is !
print(parse(command[0])), # This should print the output of the first command
print(parse(command[1])) # And this should print the second
I typed in the following command to test it:
! p Hello_p World
(p is the equivalent of Python's print command.)
But it outputs the following:
Hello
World
I want it to print this:
HelloWorld
What's wrong?
EDIT: The answer from this question prints the following:
Hello
World
So it doesn't work as wanted.
EDIT: Here's the parse function. Please don't mind the terrible code.
def parse(command):
"""Parses the commands."""
if ';' in command:
commands = command.split(";")
for i in commands:
parse(i)
if '\n' in command:
commands = command.split('\n')
for i in commands:
parse(i)
elif command.startswith("q"):
quine(command)
elif command.startswith("p "):
print_command(command)
elif command.startswith("! "):
print_command2(command)
elif command.startswith("l "):
try:
loopAmount = re.sub("\D", "", command)
lst = command.split(loopAmount)
strCommand = lst[1]
strCommand = strCommand[1:]
loop(strCommand, loopAmount)
except IndexError as error:
print("Error: Can't put numbers in loop")
elif '+' in command:
print (add(command))
elif '-' in command:
print (subtract(command))
elif '*' in command:
print (multiply(command))
elif '/' in command:
print (divide(command))
elif '%' in command:
print (modulus(command))
elif '=' in command:
lst = command.split('=')
lst[0].replace(" ", "")
lst[1].replace(" ", "")
stackNum = ''.join(lst[1])
putOnStack(stackNum, lst[0])
elif command.startswith("run "):
command = command.replace(" ", "")
command = command.split("run")
run(command[1])
elif command.startswith('#'):
pass
elif command.startswith('? '):
stackNum = command[2]
text = input("input> ")
putOnStack(text, stackNum)
elif command.startswith('# '):
stackNum = command[2]
print(''.join(stack[int(stackNum)]))
elif command.startswith("."):
time.sleep(2)
else:
print("Invalid command")
return("")
TL;DR: I'm calling two functions. I want their output to print on the same line.
the print() function has extra arguments you can pass to it. You are interested in end.
def test1():
print('hello ', end='')
def test2():
print('there', end='')
test1()
test2()
>>>
hello there
>>>
It doesn't matter how many functions this comes from

.get not working in Python

import os
name = input("Please enter your username ") or "name"
server = input("Please enter a name you wish to call this server ") or "server"
prompt = name + "#" + server
def error(choice):
print(choice + ": command not found")
commands()
def clear():
os.system("cls")
commands()
def commands():
while 1 > 0:
choice = input(prompt)
{'clear': clear}.get(choice, error(choice))()
commands()
When running this code, no matter what I enter the dictionaries .get function always returns an error. When I enter 'clear' the script should go to that function. Does anyone have an idea why this does not work correctly? Thanks.
You'll always see the error, because all arguments to a function must be evaluated before the function is called. So error(choice) will be called to get its result before it is passed as the default value to get().
Instead, leave out the default, and check it explicitly:
result = {'clear': clear}.get(choice)
if result:
result()
else:
error(choice)
You don't want to actually call error(choice).
You can partially apply parameters to a function but leave it to be called later:
>>> def error(choice):
... print(choice + ': command not found')
>>> from functools import partial
>>> func = partial(error, choice='asdf')
>>> func()
asdf: command not found
So you want:
{'clear': clear}.get(choice, partial(error, choice))()

Categories

Resources