I wrote some code but I can't get why the pyscripter is telling a syntax error in the if statement:
#search for 9 elements
file_writer = open('C:\\PythonProject2\\commands_NUM.txt','w')
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag = True:###ERROR
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##Here is the syntax error
file_writer.close()
def search_object(pixel,frame,min_val,max_val):
(obj_y,obj_x) = pixel
y_center = pixel[0]+1
x_center = pixel[1]+1
if(obj_y<=597 and obj_x<=797 ):
for y in range(0,3):
for x in range(0,3):
if((frame[obj_y+y][obj_x+x])<=min_val or(frame[obj_y+y] [obj_x+x])>=max_val ):
return False
return True
if statement is indented inwards in for loop. And also = means assignment use == instead
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag == True: #here indent this if one step back
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##He
there should be == in if statement
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag == True:
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n')
1) Put your search_object function above - declare it before using it.
2) Fix if flag = True: to if flag:
3) Fix file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') line indentation.
4) return True inside the function search_object is with wrong indentation too. Fix it.
I would recommend you to look at PEP 8.
Related
anytime I run python I get the following error:
Screenshot of when I run Python
Python typically works fine despite the error. However, I when I run a script with this function:
def selectFromDict(options, name):
index = 0
indexValidList = []
print('Select a ' + name + ':')
for optionName in options:
index = index + 1
indexValidList.extend([options[optionName]])
print(str(index) + ') ' + optionName)
inputValid = False
while not inputValid:
inputRaw = input(name + ': ')
inputNo = int(inputRaw) - 1
if inputNo > -1 and inputNo < len(indexValidList):
selected = indexValidList[inputNo]
print('Selected ' + name + ': ' + selected)
inputValid = True
break
else:
print('Please select a valid ' + name + ' number')
return selected
This is the result:
Screenshot of Error with I use selectFromDict()
How can I fix the error when I run Python?
I am trying to make a function that automatically generated a response to a selection of an action in a text adventure game. My problem is that I have to replace every second '_' with ' '. However I have tried everything I have though of and whenever I google the question the only solution I get is to use .replace(). However .replace() replaces every instance of that character. Here is my code, could you please fix this for me and explain how you fixed it.
example_actions = ['[1] Search desk', '[2] Search Cupboard', '[3] Search yard'
def response(avaliable_actions):
for i in avaliable_actions:
print(i, end=' ')
x = avaliable_actions.index(i)
avaliable_actions[x] = avaliable_actions[x][4:]
avaliable_actions = ' '.join(avaliable_actions)
avaliable_actions = avaliable_actions.lower()
avaliable_actions = avaliable_actions.replace(' ', '_')
avaliable_actions = list(avaliable_actions)
count = 0
for i in avaliable_actions:
if count == 2:
count = 0
index = avaliable_actions.index(i)
avaliable_actions[index] = ' '
elif i == '_':
count += 1
avaliable_actions = ' '.join(avaliable_actions)
print('\n\n' + str(avaliable_actions)) #error checking
Here's one approach:
s = 'here_is_an_example_of_a_sentence'
tokens = s.split('_')
result = ' '.join('_'.join(tokens[i:i+2]) for i in range(0,len(tokens),2))
print(result)
The result:
here_is an_example of_a sentence
Did I understand you correct, that you wanna produce something like this?
this_is_a_test -> this is_a test or this_is a_test?
If so, adapt the following for your needs:
s = "this_is_just_a_test"
def replace_every_nth_char(string, char, replace, n):
parts = string.split(char)
result = ""
for i, part in enumerate(parts):
result += part
if i % n == 0:
result += replace
else:
result += char
return ''.join(result)
res = replace_every_nth_char(s, "_", " ", 2)
print(s, "->", res)
# "this_is_just_a_test" -> "this is_just a_test"
After F5 in Idle the input prompt appears, I enter a number the file is generated - everything works.
If I try to execute the script directly from the file a console is opened and closed with no result.
If I move the f = open("galaxies.txt","w+") before the outer most FOR loop the script doesn't work at all.
Any suggestions for a fix and reasons why it behaves like this?
import string, random
f = open("galaxies.txt","w+")
def inputNumber(message):
while True:
try:
howmany = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return howmany
break
string.ascii_letters
type_galaxy = ['elliptical','spiral','irregular']
howmany = inputNumber('How many galaxies to generate? ')
for i in range(howmany):
planet_names = []
pos_0 = 'g' + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + '-' + random.choice(string.ascii_letters).upper() + str(random.randint(1, 9999))
gal_type = type_galaxy[random.randint(0,2)]
num_of_planets = random.randint(1,43)
for k in range(num_of_planets):
pos_1 = 'p' + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + '-' + random.choice(string.ascii_letters).upper() + str(random.randint(1, 99))
planet_names.append(pos_1)
if i < 1:
f.write('-----Galaxy '+pos_0+'----- \n')
else:
f.write('\n-----Galaxy '+pos_0+'----- \n')
f.write('Type: '+gal_type + ' \n')
f.write('There are '+str(num_of_planets)+' planets in the galaxy. Their names are: \n')
for x in planet_names:
f.write (x + ' and it has ' + str(random.randint(0,56)) + 'moons \n')
f.write('-----Thats all from Galaxy '+pos_0+'----- \n')
f.close()
I have a function in which I need to inject a character before every odd index of a string.
def inject(s, i):
sent = str(s)
new = []
for w in sent:
if w == ' ':
new.append(w)
elif (sent.index(w) % 2 == 1):
new.append(str(i) + w)
else:
new.append(w)
return ''.join(new)
The function works for:
inject(1339, 3)
output: '1333339'
and works for
inject('This is a test', 'x')
output: 'Txhixs ixs a txexst'
but won't work for:
inject('Hello World', 'x')
output: 'Hxello World'
I know it has something to do with it breaking on the 'll' but can't figure out how to fix it.
Thanks!
I think you meant to do this:
def inject(s, i):
sent = str(s)
new = []
for idx,w in enumerate(sent):
if w == ' ':
new.append(w)
elif idx % 2 == 1:
new.append(str(i) + w)
else:
new.append(w)
return ''.join(new)
for t in [1339, 'This is a test', 'Hello World']:
print(t, inject(t,'x'))
When using the enumerate() you get the index of each character without having to search for it.
The sent.index(w) call just doesn't do what you want it to even though it might seem like it does when there are no repeated characters in a string.
I am trying to make this code alternate between setting i as 56 and i as 0 I cant seem to get the second if statement to trigger. The first one works.
while True:
print 'is55 before if logic is' + str(is56)
if is56 == True:
i = 0
is56 = False
#print 'true statement' + str(i)
print 'True is56 statement boolean is ' + str(is56)
if is56 == False:
i = 56
is56 = True
print 'i is ' + str(i)
You have two separate if, so you enter the first one, set is56 to False, and then immediately enter the second one and set it back to True. Instead, you could use an else clause:
while True:
print 'is55 before if logic is' + str(is56)
if is56:
i = 0
is56 = False
else: # Here!
i = 56
is56 = True
print 'i is ' + str(i)
any objections ?
while True:
print 'is55 before if logic is' + str(is56)
i = is56 = 0 if is56 else 56
print 'i is ' + str(i)
The changes in the first if block are immediately reversed by the next one.
You want to replace the separate if blocks with a single if/else block.
On another note, you could simply use an itertools.cycle object to implement this:
from itertools import cycle
c = cycle([0, 56])
while True:
i = next(c)
print 'i is ' + str(i)
# some code
Without an elif, the original code, if working, would execute both blocks. Why not:
def print_i(i):
print 'i is ' + str(i)
while True:
print_i(56)
print_i(0)