Python value problem: SyntaxError: invalid syntax - python

I'm learning, so go easy on me.
What am I doing wrong here:
#!/usr/bin/python3.1
import urllib.request
page = urllib.request.urlopen ("http://au.finance.yahoo.com/q?s=AUDUSD=X")
text = page.read().decode("utf8")
where = text.find('Last Trade:</th><td class="yfnc_tabledata1"><big><b><span id="yfs_l10_audusd=x">')
start_of_us_price = where + 80
end_of_us_price = start_of_us_price + 6
us_price = text[start_of_us_price:end_of_us_price]
where = text.find('Trade Time:</th><td class="yfnc_tabledata1"><span id="yfs_t10_audusd=x">')
start_of_trade_time = where + 72
end_of_trade_time = start_of_trade_time + 11
trade_time = text[start_of_trade_time:end_of_trade_time]
print ('The price is $ 'us_price' as of 'trade_time'")

The last line should be:
print ('The price is $ ', us_price, ' as of ', trade_time)
Consider this to understand it better:
>>> x = 3
>>> print('The value of x is:', 3, 'Yes!')
The value of x is: 3 Yes!

Related

Python Return Statement Not Providing Expected Results

Just attempting to return values from a defined function. When calling the function first and attempting to print the return values I receive "[variable] not defined". However, if I run "print(qb_stat_filler())" it prints the results in a tuple. I need the individual variables returned to use in a separate function.
For Example
print(qb_stat_filler())
outputs: (0, 11, 24, 24.2024, 39.1143, 293.0, 1.9143000000000001, 0.2262, 97.84333355313255)
but when trying
qb_stat_filler()
print(cmp_avg)
print(att_avg)
outputs: NameError: name 'cmp_avg' is not defined
Process finished with exit code 1
I've tried establishing the variables outside of the function, then passing and returning them and that did not work either. Any thoughts?
def qb_stat_filler():
n_input = input('Player name: ')
t_input = input('Players team: ')
loc_input = input('H or #: ')
o_input = input('Opponent: ')
# convert index csv to dictionary of player values
q = pd.read_csv('Models\\QB Indexes\\QBname.csv')
q = q[['Player', 'Num']]
qb_dict = dict(q.values)
name = qb_dict.get('{}'.format(n_input))
t = pd.read_csv('Models\\QB Indexes\\Tmname.csv')
t = t[['Tm', 'Num']]
tm_dict = dict(t.values)
team = tm_dict.get('{}'.format(t_input))
loc = 0
if loc_input == '#':
loc = 0
elif loc_input == 'H':
loc = 1
z = pd.read_csv('Models\\QB Indexes\\Oppname.csv')
z = z[['Opp', 'Num']]
opp_dict = dict(z.values)
opp = opp_dict.get('{}'.format(o_input))
*there are several lines of code here that involve SQL
queries and data cleansing*
cmp_avg = (cmp_match + cmpL4) / 2
att_avg = (patt_match + pattL4) / 2
pyds_avg = (py_match + pydsL4) / 2
ptd_avg = (ptdL4 + ptd_match) / 2
int_avg = (intL4 + int_match) / 2
qbr_avg = (qbr_match + qbrL4) / 2
return name, team, opp, cmp_avg, att_avg, pyds_avg, ptd_avg,
int_avg, qbr_avg
qb_stat_filler()
You might consider:
def qb_stat_filler():
stats = {}
...
stats['name'] = name
z = z[['Opp', 'Num']]
opp_dict = dict(z.values)
stats['opp'] = opp_dict.get('{}'.format(o_input))
...
stats['cmp_avg'] = (cmp_match + cmpL4) / 2
stats['att_avg'] = (patt_match + pattL4) / 2
stats['pyds_avg'] = (py_match + pydsL4) / 2
stats['ptd_avg'] = (ptdL4 + ptd_match) / 2
stats['int_avg'] = (intL4 + int_match) / 2
stats['qbr_avg'] = (qbr_match + qbrL4) / 2
return stats
...
stats = qb_stat_filler()
print(stats['cmp_avg'])

IndexError: list index out of range error on python

This is my code:
while True:
print("Type 'done' to finish receipts")
code=input("Enter item code to add:")
items =open("items.txt")
quant=input("Quantity:")
details = items.read()
detailslist = details.split("\n")
for a in detailslist:
fire = a.split("#")
print (fire)
b = fire[0]
c = fire[1]
d = fire[2]
dictd = {}
dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d
print (dictd)
This is in items.txt:
A# Almanac2018# 18.30
B# Almanac2020# 23.80
C# Almanac2021# 16.54
D# Almanac2022# 22.25
I am getting this error:
Type 'done' to finish receipts
Enter item code to add:A
Quantity:45
['A', ' Almanac2018', ' 18.30']
{'A': ' Almanac2018 Quantity: 45 Price: 18.30'}
['B', ' Almanac2020', ' 23.80']
{'B': ' Almanac2020 Quantity: 45 Price: 23.80'}
['C', ' Almanac2021', ' 16.54']
{'C': ' Almanac2021 Quantity: 45 Price: 16.54'}
['D', ' Almanac2022', ' 22.25']
{'D': ' Almanac2022 Quantity: 45 Price: 22.25'}
['']
Traceback (most recent call last):
File "receipt.py", line 12, in <module>
c = fire[1]
IndexError: list index out of range
I am trying to make a program that makes a receipt of items so if you could provide any code that would be helpful.
Any help would be appreciated.
The problem you have in your code is with the empty strings in your items.txt file. When there's an empty string, fire would resolve to [''], which is a list of only 1 item, so you get an error when the code tries to run c = fire[1]. You can add a check to see if it's an empty line or not:
for a in detailslist:
fire = a.split("#")
if len(fire) > 1:
print (fire)
b = fire[0]
c = fire[1]
d = fire[2]
dictd = {}
dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d
print (dictd)
Give a man a fish, feed him for a day... teach a man to fish.
So this isn't a fish, but it is a fishing rod (as long as your using Python v3.7 or greater):
import pdb #Only need this if python < v3.7
while True:
print("Type 'done' to finish receipts")
code=input("Enter item code to add:")
items =open("items.txt")
quant=input("Quantity:")
details = items.read()
detailslist = details.split("\n")
for a in detailslist:
fire = a.split("#")
print (fire)
try:
b = fire[0]
c = fire[1]
d = fire[2]
dictd = {}
dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d
print (dictd)
except:
breakpoint() # if Python >= v3.7
pdb.set_trace() # if Python < v3.7
Which means you can see the exact shape and size of "fire" when the error is being caused. Should help your debugging efforts here - and in future when other problems inevitably crop up.

Loop for extracting dictionary values ends prematurely

I'm trying to use this dictionary:
student_data_dict = {'Student_1': 'bbbeaddacddcddaaadbaabdad', 'Student_2': 'acbccaddcadaaacdadbcabcad', 'Student_3': 'babcabdccadcDdbccdbaadbad', 'Student_4': 'bcbcabddcadcdabccdbaadcbd', 'Student_5': 'DCBCCADDCADBDACCDBBACBCAD', 'Student_6': 'acbeccddcadbaaccabbacdcad', 'Student_7': 'BCBCBCDABADCADCCDABAACCAD', 'Student_8': 'dcbccbddcadaabcbcacabbcad', 'Student_9': 'DDBDBBCDDCCBABCCBACADAAAC', 'Student_10': 'cbbdacdacadcbadbabaabcaTa', 'Student_11': 'BDBECADCAADCAAAAACBACACAD', 'Student_12': 'DBBCCBDCCADCDABABCBAABCAD', 'Student_13': 'BCBCBCDDCADCAAACCABACACAD', 'Student_14': 'DBBECBDACADAAACBCBAAABCBD', 'Student_15': 'acbebbddcadbaacccbcaddcad', 'Student_16': 'ACBEBCDDCADBAACCAACADBCAD', 'Student_17': 'DBBCACDDCADCAABCADBABDDAD', 'Student_18': 'dcbcdcdbbddccabbdacacccbd', 'Student_19': 'dbbccbddcadaaaccbdcaaacad', 'Student_20': 'abbdaaddcadcaaccbdcaaccbd', 'Student_21': 'DCDCABDBCADAAACDCCDAACAAD', 'Student_22': 'dabdaddabddbaacdacbaaaaad', 'Student_23': 'BCBCDDDACCDCAABDDABACACAD', 'Student_24': 'ACBDCBDBBCDAACCCCBDAADCBD', 'Student_25': 'DCBCACDAADDCADCBAABACBCAD', 'Student_26': 'dcbaabdccadcdadcccbaabdbd', 'Student_27': 'abbadbddcadacbcacccacbdad'}
and store the first letter for all students as a dictionary entry and then do the same for the next letter ect... to result in:
{'question_1': 'babbDaBdDcBDBDaADddaDdBADda', 'question_2': 'bcacCcCcDbDBCBcCBcbbCaCCCcb', 'question_3': 'bbbbBbBbBbBBBBbBBbbbDbBBBbb', 'question_4': 'ecccCeCcDdECCEeECccdCdCDCaa', 'question_5': 'acaaCcBcBaCCBCbBAdcaAaDCAad', 'question_6': 'dabbAcCbBcABCBbCCcbaBdDBCbb', 'question_7': 'ddddDdDdCdDDDDdDDdddDdDDDdd', 'question_8': 'adcdDdAdDaCCDAdDDbddBaABAcd', 'question_9': 'ccccCcBcDcACCCcCCbccCbCBAcc', 'question_10': 'daaaAaAaCaAAAAaAAdaaAdCCDaa', 'question_11': 'ddddDdDdCdDDDDdDDdddDdDDDdd', 'question_12': 'caccBbCaBcCCCAbBCcacAbCACca', 'question_13': 'daDdDaAaAbADAAaAAcaaAaAAAdc', 'question_14': 'dadaAaDbBaAAAAaAAaaaAaACDab', 'question_15': 'acbbCcCcCdABACcCBbccCcBCCdc', 'question_16': 'adccCcCbCbAACBcCCbccDdDCBca', 'question_17': 'aaccDaDcBaABCCcAAdbbCaDCAcc', 'question_18': 'ddddBbAaAbCCABbADaddCcABAcc', 'question_19': 'bbbbBbBcCaBBBAcCBcccDbBDBbc', 'question_20': 'acaaAaAaAaAAAAaAAaaaAaAAAaa', 'question_21': 'aaaaCcAbDbCACAdDBcaaAaCACac', 'question_22': 'bbddBdCbAcABABdBDcacCaADBbb', 'question_23': 'dcbcCcCcAaCCCCcCDcccAaCCCdd', 'question_24': 'aaabAaAaATAAABaAAbabAaABAba', 'question_25': 'ddddDdDdCaDDDDdDDdddDdDDDdd'}
x = 1
all_letters = ''
letter = ''
y = 1
i = 0
z = 0
for start in student_data_dict:
student = student_data_dict.get('Student_' + str(y))
letter = student[z]
all_letters = all_letters + letter
y = y + 1
i = i + 1
question_data_dict["question " + str(x)] = all_letters
if i == 27:
z = z + 1
x = x + 1
i = 0
print(question_data_dict)
data_file.close()
{'question 1': 'babbDaBdDcBDBDaADddaDdBADda'}
is what I get but I can't get the answers for the other 25 questions.
I tried changing for start in student_data_dict: into while z<26: but at the line "letter = student[z]" I get the error "'NoneType' object is not subscriptable"
num_questions = 25
answers_dict = {}
for i in range(num_questions):
answers_dict['question' + str(i)] = ''.join(c[i] for c in student_data_dict.values())
print(answers_dict)
Will give you the result you want.
Edit
Fixed code. Extracted number of questions to a variable so it can be used as index
Edit2
I created an OrderedDict from your original dictionary to maintain answer order when iterating. Now the answers_dict contains valid data.
from collections import OrderedDict
ordered_data = OrderedDict()
for i in range(len(student_data_dict.items())):
ordered_data['Student_' + str(i + 1)] = student_data_dict.get('Student_' + str(i + 1))
num_questions = 25
answers_dict = {}
for i in range(num_questions):
answers_dict['question' + str(i + 1)] = ''.join(c[i] for c in ordered_data.values())
You need to reset y when you move to the next question.
Here's an alternative a way to get what you're looking for with Pandas:
import pandas as pd
sdd = {k:[x for x in v] for k,v in student_data_dict}
df = pd.DataFrame(sdd)
df = df.reindex_axis(sorted(df.columns,
key = lambda col: int(col.split("_")[-1])), axis=1)
df.index = [f"Question {i+1}" for i in df.index]
{k:''.join(v) for k,v in zip(df.index, df.values)}

Why is y not defined?

In this code for some reason the variable y is not defined for the first if statement only. I need to know why it says that y is not defined. Also if you need code for finding WOEID here it is.
import urllib2
def make_word(words):
result = ""
for i in words:
result += i
return result
continents = ['asia', 'north%20america', 'south%20america', 'europe', 'asia', 'australia', 'antarctica']
a = raw_input('Put in a place: ')
a = a.lower()
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % a).read()
f = page.find('Ohio')
if y not in continents:
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if f == -1:
f = page.find('United States')
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if y in continents:
if f == -1:
f = page.find('')
start = page.find('woeid="', f) + 7
print page[start:]
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
You only define y in very specific circumstances:
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
So only if there is a space in a do you produce y.
Don't create a new variable here, and don't URL-encode manually. Use the urllib.quote() function instead:
from urllib import quote
y = quote(a.lower())
You appear to be mixing a and y throughout your code. Perhaps you need to use more meaningful names here:
place = raw_input('Put in a place: ')
place_quoted = quote(place.lower())
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % place_quoted).read()
if place_quoted not in continents:
if ' ' in a: #This conditions fails in your code and the y variable is not initialized/ set.
if y not in continents: # when this line executes, it has no reference for y, throws the error "undefined"
Better initialize a default value at the start of your code.
Eg : y = None (or) handle your variable properly.

how to calculate 24?

I wrote a python script trying to solve the 'calculate 24' problem, which originated from a game, drawing 4 cards from a deck of cards and try to get the value 24 using +,-, *, and /.
The code is working, only that it have many duplications, for example, I input 2, 3, 4, 5 to get the value of 24, it will find and print that 2*(3 + 4 + 5) is 24, but it will also print 2*(5 + 4 + 3), 2*(5 + 3 + 4), etc., while it will find 4*(3 + 5 - 2), it will also print 4*(5 + 3 - 2). Could anyone please give me some hints on how to remove duplicated answers?
The code is as follows:
def calc(oprands, result) :
ret=[]
if len(oprands)==1 :
if oprands[0]!=result :
return ret
else :
ret.append(str(oprands[0]))
return ret
for idx, x in enumerate(oprands) :
if x in oprands[0:idx] :
continue
remaining=oprands[0:idx]+oprands[idx+1:]
temp = calc(remaining, result-x) # try addition
for s in temp :
ret.append(str(x) + ' + ' + s)
if(result%x == 0) : # try multiplication
temp = calc(remaining, result/x)
for s in temp :
ret.append(str(x) + ' * (' + s + ')')
temp = calc(remaining, result+x) # try subtraction
for s in temp :
ret.append(s + ' - ' + str(x))
temp = calc(remaining, x-result)
for s in temp :
ret.append(str(x) + ' - (' + s + ')')
temp = calc(remaining, result*x) # try division
for s in temp :
ret.append('(' + s + ') / ' + str(x))
if result!=0 and x%result==0 and x/result!=0 :
temp = calc(remaining, x/result)
for s in temp :
ret.append(str(x) + ' / ' + '(' +s +')')
return ret
if __name__ == '__main__' :
nums = raw_input("Please input numbers seperated by space: ")
rslt = int(raw_input("Please input result: "))
oprds = map(int, nums.split(' '))
rr = calc(oprds, rslt)
for s in rr :
print s
print 'calculate {0} from {1}, there are altogether {2} solutions.'.format(rslt, oprds, len(rr))
Calculate 24 is an interesting and challenging game. As other users pointed out in the comments, it's difficult to create a solution that doesn't present any flaw.
You could study the Rosetta Code (spoiler alert) implementation and compare it to your solution.

Categories

Resources