When I use the float() method in a program , I am getting an error. Can you please help me with that. I am using python 3.4.0a4.
This is the program:
import urllib.request
price = 99.99
while price > 4.74:
page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
Print("Buy!")
and this is the error I get:
Traceback (most recent call last):
File "F:/Python/python 8.py", line 11, in <module>
price = float(text[start_of_price:end_of_price])
ValueError: could not convert string to float: '!DOC'
It seems like you sliced the string of the web page at the wrong position, and the result of text[start_of_price:end_of_price] is !DOC.
This is not a valid number and can hence not be converted to a float.
This is the exact code given in Head first Programming. The link was broken and I got the output on correcting it. Thanks for your help..
Related
I am getting the following error on the code below :
Traceback (most recent call last):
File "D:/Personal Files/Technical Development/PycharmProjects/Call Center Headcount Model/Call Center Headcount Model.py", line 12, in
historical_start_date = work_rules.iloc(4, 2)
TypeError: call() takes from 1 to 2 positional arguments but 3 were given
I am trying to assign a cell value in excel to a variable in Python through pandas. i.e. Historical_start_date = work_rules.loc(4,2)
Any idea why this is?
Code:
work_rules = pd.read_excel(
'D:\\Personal Files\\Technical Development\\PycharmProjects\\Call Center Headcount Model\\Call Center Work Rules.xlsx',
sheet_name='Inputs')
historical_start_date = work_rules.iloc(4, 2)
print(historical_start_date)
Please refer to the Iloc documentation. You're supplying variables as if it is a method. I'm not sure what you want to do exactly but it seems to me that you need to replace the parenthesis after iloc with brackets.
I have built a code for a codewars problem. I think it is correct but it shows me an error I don't understand.
Can you tell me what am I doing wrong?
import math
def waterbombs(fire, w):
s=""
countx=0
for i in fire:
if i=="x":
countx+=1
elif i=="Y":
countx=0
return sum(math.ceil(countx/w))
waterbombs("xxYxx", 3)
This is the error:
Traceback (most recent call last):
File "D:\Curso Python Pildorasinformaticas\Ejercicios Codewars\Aerial Firefighting.py", line 16, in <module>
waterbombs("xxYxx", 3)
File "D:\Curso Python Pildorasinformaticas\Ejercicios Codewars\Aerial Firefighting.py", line 13, in waterbombs
return sum(math.ceil(countx/w))
TypeError: 'int' object is not iterable
[Finished in 0.2s]
Why are you doing sum(math.ceil(countx/w)) ?
What is the objective of the sum method here, since there is only value returned by math.ceil ?
The sum would throw that error if you pass a single value to it. You're supposed to pass a list of values of the sum method.
For eg: sum(5) would give you the same error you see above, but sum([5]) would return you 5.
I have a sample json:
I want to use the json module of python and recurse through to find the "MaxSize" in "pevcwebasg". Have the following code:
import json
param_file_handle = json.load(open("sample.json"))
print param_file_handle['Resources']['pevcwebasg']['Type']
resources = param_file_handle['Resources']
for asg in resources:
print asg["Type"]
The out put of which is :
> AWS::AutoScaling::AutoScalingGroup Traceback (most recent call last):
> File "test.py", line 8, in <module>
> print asg['Type'] TypeError: string indices must be integers
What I dont get is this line "print param_file_handle['Resources']['pevcwebasg']['Type']" works fine and gets me the output but when i recurse through and try and find asg["Type"], it fails. Any better way to do this ? I need to recurse through the tree and find the value.
Edit 1:
as I do recurse through values, I get stuck with error.
param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
for values in asg['Properties']:
print values["MaxSize"]
error :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print values["MaxSize"]
TypeError: string indices must be integers
for asg in resources:
This iterates through the keys of resources, rather than the values. Try:
for asg in resources.values():
param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
print asg["Properties"]["MaxSize"]
try this.
you broke hirerchy, missed "pevcwebasg"
resources = param_file_handle['Resources']['pevcwebasg']
for asg in resources:
print asg["Type"]
I am trying to create a script in Jython to migrate some applications from was 7 to was 8.5. After I create the Data Source I am stuck for about 2 hours with this error: TypeError: sequence subscript must be integer or slice
The problem appear at line 25 and i have no idea how to solve it. If you need more information let me know.
Please help me! Thank you very much!
My code:
if ( len(OracleDataSourceList) > 0 ):
dbuserList=AdminTask.listAuthDataEntries()
for dataSource in OracleDataSourceList:
datasourceName=dataSource[0]
dsJNDIName=dataSource[1]
compAuthAlias=dataSource[2]
providerName=dataSource[3]
dataStoreHelperClassName=dataSource[4]
description=dataSource[5]
databaseURL=dataSource[6]
databaseMaxConnections=dataSource[7]
databaseMinConnections=dataSource[8]
databaseconnTimeout=dataSource[9]
databasereapTime=dataSource[10]
databaseunusedTimeout=dataSource[11]
databaseagedTimeout=dataSource[12]
#Create Data Source
dataSourceId = AdminJDBC.createDataSourceAtScope( scope, providerName, datasourceName, dsJNDIName, dataStoreHelperClassName, databaseURL, [['componentManagedAuthenticationAlias',compAuthAlias],['containerManagedPersistence','true'],['description',description]])
#Modify connection pool
connectionPoolList = AdminConfig.list('ConnectionPool', dataSourceId)
connectionPoolList = AdminUtilities.convertToList(connectionPoolList)
connectionPoolId = connectionPoolList[0]
AdminConfig.modify(connectionPoolId, [["maxConnections", databaseMaxConnections]\
["minConnections", databaseMinConnections]\
["connTimeout", databaseconnTimeout]\
["reapTime", databasereapTime]\
["unusedTimeout", databaseunusedTimeout]\
["agedTimeout", databaseagedTimeout]\
])
print 'Saving configuration...'
AdminConfig.save()
print "Configuration saved."
Error:
WASX7017E: Exception received while running file "createDataSource.py"; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
File "<string>", line 25, in ?
TypeError: sequence subscript must be integer or slice
I solved the problem.
Replace the lines 25:31 with:
AdminConfig.modify(connectionPoolId, [["maxConnections", databaseMaxConnections], ["minConnections", databaseMinConnections], ["connectionTimeout", databaseconnTimeout], ["reapTime", databasereapTime], ["unusedTimeout", databaseunusedTimeout], ["agedTimeout", databaseagedTimeout]])
Can someone please explain to me why I keep getting this error: TypeError: get_n_nouns() takes 1 positional argument but 2 were given.
I have already had a look at where my problem may be by looking at a similar question (Link) But I have adapted my code going along with the answer and yet I end up with the above error.
Here is the error in full:
Traceback (most recent call last):
File "C:/Users/...../Downloads/Comp4.1/trialTo3.py", line 21, in <module>
app.createPhrases()
File "C:/Users/...../Downloads/Comp4.1/trialTo3.py", line 15, in createPhrases
words = self.get_n_nouns(1)
TypeError: get_n_nouns() takes 1 positional argument but 2 were given
Here is the code:
import csv
class apps():
def get_n_nouns(n):
"""
Returns the n most common nouns
"""
with open("setPhrases.txt") as in_file:
reader = csv.reader(in_file)
data = [[row[0], int(row[1])] for row in list(reader)]
return sorted(data, key=lambda x: -x[1])[:n]
def createPhrases(self):
words = self.get_n_nouns(1)
for word, count in words:
print("{}: {}".format(word, count))
app = apps()
app.createPhrases()
Can someone please explain to me where I am going wrong? Any help is much appreciated.
Ok so I found out where the error was. Kind of a rookie error.
This:
def get_n_nouns(n):
Needed to be written as this:
def get_n_nouns(self, n):
I had forgot to add the self part to it. That is why I kept getting that error message.