Can you please tell whats wrong with this - python

**Can you tell me what is wrong with this error?***************
codio#random-media:~/workspace$ python final.py
File "final.py", line 4
return f'print("{phrase}")\n'
^
SyntaxError: invalid syntax
def createOutput(lang, phrase):
if lang == "python":
return f'print("{phrase}")\n'
if lang == "c++":
return f'cout << "{phrase}\\n";\n'
if lang == "c":
return f'printf("{phrase}\\n");\n'
return ""

F strings are not supported in python2.
Use format
'print("{}")\n'.format(var)
Or use Python 3.6+ and run the code

Related

SyntaxError: Invalid syntax? Eval() [duplicate]

This question already has answers here:
Why must "exec" (and not "eval") be used for Python import statements?
(3 answers)
Closed 3 years ago.
Basically I am doing a POC against python eval security issue, but I am getting below error:
Traceback (most recent call last):
File "exploit.py", line 11, in <module>
a = paste()
File "exploit.py", line 6, in paste
if eval('%s > 1' % a):
File "<string>", line 1
import os;os.system('pwd') > 1
^
SyntaxError: invalid syntax
Code:
import datetime
def paste():
a = "import os;os.system('pwd')"
if eval('%s > 1' % a):
print a
else:
#create_brew(request.json)
return None, 201
a = paste()
print a
can anyone help me how to import libraries in-line?
eval works in expressions.
Use exec to execute a statement [import is a statement]
Also note, you cannot assign exec to a variable.
>> exec('import os;data = os.getcwd()')
>> print(data)
>> # /path/of/you/cwd
You may use the variable data to continue with your tests.
Taking the liberty to edit your code as follow:
def paste():
data = None
exec('import os;data = os.getcwd()')
if data:
return data
else:
return None, 201
a = paste()
print(a)

Import Error: no module named

Hi I'm VERY new to programming, and I am working on my first program. I've been following along in a book and I decided to stop and test a function. The function is in a file called myPythonFunctions.py. I then created a new file called untitled.py and put it in the same folder as myPythonFunctions.py.
In untitled.py I have the following code:
import myPythonFunctions as m
m.generateQuestion()
Very simple, but when I try to run it I get Import Error: no module named myPythonFunctions.
I don't understand, there is clearly a file named myPythonFunctions in the folder. What's going on?
In case you need it, here is the code for m.generateQuestion()
def generateQuestion():
operandList = [0,0,0,0,0,]
operatorList = ['', '', '', '', '']
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
for index in range(0,5):
operandList[index] = randint(1,9)
for index in range(0,4):
if index > 0 and operatorList[index-1] !='**':
operator = operatorDict[randint(1,4)]
else:
operator = operatorDict[randint(1,3)]
operatorList[index] = operator
questionString = str(operandList[0])
for index in range(1,5):
questionString = questionString + OperatorList[index-1] + str[operandList[index]
result = eval(questionString)
questionString.replace("**","^")
print('\n' + questionString)
userAnswer=input('Answer: ')
while true:
try:
if int(userAnswer) == result:
print('Correct!')
return 1
else:
print('Sorry, the correct answer is', result)
return 0
except Exception as e:
print("That wasn't a number")
userAnswer = input('Answer: ')
Edit: I'm now getting this error
Traceback (most recent call last):
File "/Users/Brad/Desktop/Python/Untitled.py", line 1, in <module>
import myPythonFunctions as m
File "/Users/Brad/Desktop/Python/myPythonFunctions.py", line 33
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
^
SyntaxError: invalid syntax
The syntaxis error you are getting, is because you are trying to define a dictionary as a list, so the interpreter is raising the error because it does not know what to do with that.
To define a dictionary you need to use { } instead of [ ]
--- EDIT 2
Your dictionary implementation is wrong, do you really copied this code from somewhere?
The
operatorDict = {1:'+', 2:'-', 3:'*', 4:'**'}
Your code was mispelled
---- EDIT
Your code on myPythonFunctions is really bad.
Python needs correct identation to works, please double check this step
I suggest you to do a check in your structure:
I did this right now
/somefolder
--this.py
--functions.py
/
The contents
--this.py
import functions as f
print f.hello()
--functions.py
def hello():
return 'It worked'
Try this structure in your environment :D
And then run:
python this.py

Add character in .txt file in python

I'm working on a python script that need from the user to add an argument on the command line to call the script. The script is
#!/usr/bin/env python
import sys
if len(sys.argv) == 1:
sys.exit("Error : argument expected.")
print("coucou")
a = ['SDK', 'DESKTOP', 'DFEM', 'COMMAND', 'TOK', 'DESKTOPONLY']
z = a.count(sys.argv[1]
if z == 0:
sys.exit("Error : argument invalid.")
print (sys.argv[1])
and the error is
File "./test.py", line 10
if z == 0:
^
SyntaxError: invalid syntax
Can anybody help me ? :) I'm just starting python, and it's driving me crazy...

Python ValueError: chr() arg not in range(256)

So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed
chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.
The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.

Why is the "else" line giving an invalid syntax error?

I'm having this error:
File "zzz.py", line 70
else:
^
SyntaxError: invalid syntax
The line which causes the problem is marked with a comment in the code:
def FileParse(self, table_file):
vars={}
tf = open(table_file, 'r')
for line in tf:
if line.startswith("#") or line.strip() == "": pass
elif line.startswith("n_states:"):
self.n_states = str(line[9:].strip())
elif line.startswith("neighborhood:"):
self.neighborhood = str(line[13:].strip())
elif line.startswith("symmetries:"):
self.symmetries = str(line[11:].strip())
elif line.startswith("var "):
line = line[4:]
ent = line.replace('=',' ').\
replace('{',' ').\
replace(',',' ').\
replace(':',' ').\
replace('}',' ').\
replace('\n','').split()
vars[ent[0]] = []
for e in ent[1:]:
if e in vars: vars[ent[0]] += vars[e]
else:
vars[ent[0].append(int(e))]
else:
rule = line.strip().split(",")
for k in vars.keys():
if k in rule:
for i in vars[k]:
change = rule.replace(k, i)
change = [int(x) for x in change]
w.rules.append(Rule(change[:5],change[5])
else: # line which causes the problem
rule = [int(x) for x in rule]
w.rules.append(Rule(rule[:5],rule[5]))
tf.close()
self.parse_status "OK"
return w.rules
w.rules is variable which is assigned to "World" class.
To be honest I have no idea why I get this. Before everything was fine and now that error shows up after adding some extra instructions in other indented blocks.
Any ideas?
Because you left out a closing brace
w.rules.append(Rule(change[:5],change[5]) )
The previous line, w.rules.append(Rule(change[:5],change[5]), is missing a close paren.
While you're at it, there is another typo. You probably want:
self.parse_status "OK"
To be:
self.parse_status = "OK"
Remove extra spaces/lines and re-indent the if/else statements. This worked for me.
(I tried the other solutions here but none worked. My braces were fine.)

Categories

Resources