I have the following code:
for i in range(len(str(hoursList))):
try:
g(hoursList[i])
except Exception as ex:
print(str(nameList[i]) + " " + "has more than 80 hours worked!")
When I run the code, I get an error saying "IndexError: list index out of range". I'm wondering if its because I have hoursList[i], but when I take out the [i], the loop runs too many times.
My nameList and hoursList has the following in it, respectively.
['Michael Johnson', 'Sue Jones', 'Tom Spencer', 'Mary Harris', 'Alice Tolbert', 'Joe Sweeney', 'Linda Smith', 'Ted Farmer', 'Ruth Thompson', 'Bob Bensen']
[8.75, 8.75, 8.75, 8.75, 8.75, 8.75, 11.0, 11.0, 5.25, 5.0]
What is happening when you are doing len(str(hoursList)) is you are turning the entire list into a string then going through and returning an i for each number, space, and , of the new string. For example:
len(str(["hello", "world"])) == 18
But if you do this:
len(["hello", "world"]) == 2
So when you are in the for i loop you end up going over how many entries are actually in the hoursList.
Change your loop to be:
for i in range(len(hoursList)):
try:
g(hoursList[i])
except Exception as ex:
print(str(nameList[i]) + " " + "has more than 80 hours worked!")
Related
This is my code it's the exact same code as the pdf
states = [
"Oregon":"OR",
"Florida": "FL",
"California": "CA",
"New York": "NY",
"Michigan": "MI"
]
cities = [
"CA": "San Francisco",
"MI": "Detroit",
"FL": "Jacksonville"
]
cities["NY"] = "New York"
cities["OR"] = "Portland"
print "-" * 10
print "NY state has: ", cities["NY"]
print "OR state has: ", cities["OR"]
print "-" * 10
print "Michigan's abbreviation is: ", states["Michigan"]
print "Florida's abbreviation is: ", states["Florida"]
print "-" * 10
print "Michigan has: ", cities[states["Michigan"]]
print "Florida has: ", cities[states["Florida"]]
print "-" * 10
for state, abbrev in states.items():
print "%s is abbreviated %s", % (state, abbrev)
print "-" * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
print "-" * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
print "-" * 10
state = states.get("Texas", None)
if not state:
print "Sorry, no Texas."
city = cities.get("TX", "Does Not Exist")
print "The city for the state 'TX' is: %s" % city
This is my error i put into my terminal python ex39.py and i get this.
File "ex39.py", line 3
"Oregon":"OR",
^
SyntaxError: invalid syntax
i'm running macOS 10.13.6 Beta (17G47b)
MacBook (13-inch, Mid 2010)
Processor 2.4 GHz Intel Core 2 Duo
Memory 8 GB 1067 MHz DDR3
Graphics NVIDIA GeForce 320M 256 MB
So the issue here is when you use brackets [] it makes a list, like [1,2,3,4,5].
While 1-5 in that list are all in the same list, they don't directly interact with each other.
You're looking for a dictionary, which uses curly brackets {}. It takes a array of information, but it takes them in pairs of a key and its value.
So you need this
states = {
"Oregon":"OR",
"Florida": "FL",
"California": "CA",
"New York": "NY",
"Michigan": "MI"
}
cities = {
"CA": "San Francisco",
"MI": "Detroit",
"FL": "Jacksonville"
}
The first of the pair is they key, the second is the value.
Hope this helps! Happy coding!
So basically I have to tell the user if the staff working in a phone shop has earned a bonus. If the staff sold 4 or more phones, they get a bonus.
Problem is I keep getting this error.
if list[member_number]>=4:
TypeError: 'int' object is not subscriptable
This is my code-
How_Many_Members= int(input("Enter the number of staff members:"))
list=[]
member=1
while len(list)!= How_Many_Members:
print("how many phones did the member", member,"sold?",end=" ")
Sales=int(input(""))
list.append(Sales)
member=member+1
member_number=0
for list in range(0,How_Many_Members,1):
if list[member_number]>=4:
print("member",member_number,"has earned a bonus")
member_number=member_number+1
else:
print("member",member_number,"has not earned a bonus")
member_number=member_number+1
You have two list objects. One is an array, and the other is an object in a for statement, here:
for list in range(0,How_Many_Members,1):
You are using duplicates, and that's not good and is the thing causing your program to spit the error. It is using that list instead of the array list. And since the list in the for loop is an integer object, the error is thrown. You are basically trying to use subscript on an array but it mistakes it as the integer from the for loop because it is ambiguous. Try the following:
How_Many_Members = int(input("Enter the number of staff members:"))
list = []
member = 1
while len(list) != How_Many_Members:
print("how many phones did the member", member, "sold?", end=" ")
Sales = int(input(""))
list.append(Sales)
member += 1
member_number = 0
for _ in range(0, How_Many_Members, 1):
if list[member_number] >= 4:
print("member", member_number + 1, "has earned a bonus")
member_number += 1
else:
print("member", member_number + 1, "has not earned a bonus")
member_number += 1
Something else, you misspelled member_number in a few places and I fixed that for you. I also shorted some statements and let it print member 1 instead of member 0.
Your problem is here:
for list in range(0,How_Many_Members,1):
if list[member_number]>=4:
print("member",memeber_number,"has earned a bonus")
member_number=member_number+1
else:
print("member",memeber_number,"has not earned a bonus")
member_number=member_number+1
You are saying for list in range(0, How_Many_Members), so list is taking an integer value from 0 to How_Many_Members-1. So it's not a list anymore and you can't do list[member_number].
I am using a paper trading IB-account where trades are processed just fine. I have a number of unfilled orders. The "updateAccountValue" performs as expected, while "con.register(acct_update, message.reqAllOpenOrders())" does nothing, neither does "con.reqOpenOrders()'. Neither raises an error either. The IB documentation tells me that all three methods are 'void' which I understand to mean that no value is supposed to be returned. Yet, as stated, the "updateAccountValue" method works perfectly fine, supplying the proper output.
Question 1: how do I retrieve data regarding (unfilled) open orders?
I have also noticed that the code does not always run, but it always runs properly right after (re-)starting the TWS workstation application.
Question 2: why does this code not run every time it is launched?
from ib.opt import ibConnection, message
import sys
def acct_update(msg):
print msg
con = ibConnection(clientId=100)
con.register(acct_update,
message.updateAccountValue)
con.register(acct_update,
message.reqAllOpenOrders())
con.connect()
con.reqAccountUpdates(True,'DU000000')
con.reqAllOpenOrders()
con.reqOpenOrders()
sys.exit()
I was trying to figure out how to print out all open orders. Here is what I found that may help you with your first question.
Add a print function to the original IBpy documents of Order.py and Contract.py.
In the Order.py add:
def __str__(self):
return "Action: " + self.m_action + ", Quantity: " + str(self.m_totalQuantity) + ", at price: " + str(self.m_lmtPrice)
In the Contract.py add:
def __str__(self):
return "secType: " + self.m_secType + ", symbol: " + self.m_symbol + "; expiry: " + self.m_expiry
You can modify the fields to show what you would like to view.
In your own python file:
``
from ib.opt import Connection, message
from ib.ext.Contract import Contract
from ib.ext.Order import Order
def print_open_order_messege(msg):
print ("open_order: " + str(msg.orderId) + "::" + str(msg.contract) + "::" + str(msg.order) + "::"+str(msg.orderState))
def print_order_status_messege(msg):
print ("order_status: " + str(msg.orderId) + "::" + "Status: " + msg.status + ", Filled: " + str(msg.filled) + ", Remaining: " + str(msg.remaining) + ", avgFillPrice: " + str(msg.avgFillPrice))
con.register(print_open_order_messege, message.openOrder)
con.register(print_order_status_messege, message.orderStatus)
con.reqAllOpenOrders()
It prints out my test order as below:
...
open_order: 2::secType: FUT, symbol: NQ; expiry: 20161216::action: BUY, quantity: 1, at price: 4500.0::Status: PendingCancel
order_status: 2::Status: PendingCancel Filled: 0 Remaining: 1 avgFillPrice: 0.0
Notice the difference ?
con.register(acct_update,
message.updateAccountValue)
con.register(acct_update,
message.reqAllOpenOrders())
You should use message.openOrder
Also, you're sending it to the acct_update callback but since it just prints, it's no big deal. However if you want information from the callback, here is the format it arrives in.
<openOrder orderId=123469, contract=<ib.ext.Contract.Contract object at 0x7f68daeff6a0>, order=<ib.ext.Order.Order object at 0x7f68e80d2668>, orderState=<ib.ext.OrderState.OrderState object at 0x7f68daf39240>>
You also call exit() before the program probably has a chance to finish. It's asynchronous, that means you have to wait for a reply.
So, my question is simple. I'm simply struggling with syntax here. I need to read in a set of integers, 3, 11, 2, 4, 4, 5, 6, 10, 8, -12. What I want to do with those integers is place them in a list as I'm reading them. n = n x n array in which these will be presented. so if n = 3, then i will be passed something like this 3 \n 11 2 4 \n 4 5 6 \n 10 8 -12 ( \n symbolizing a new line in input file)
n = int(raw_input().strip())
a = []
for a_i in xrange(n):
value = int(raw_input().strip())
a.append(value)
print(a)
I receive this error from the above code code:
value = int(raw_input().strip())
ValueError: invalid literal for int() with base 10: '11 2 4'
The actual challenge can be found here, https://www.hackerrank.com/challenges/diagonal-difference .
I have already completed this in Java and C++, simply trying to do in Python now but I suck at python. If someone wants to, they don't have too, seeing the proper way to read in an entire line, say " 11 2 4 ", creating a new list out that line, and adding it to an already existing list. So then all I have to do is search said index of list[ desiredInternalList[ ] ].
You can split the string at white space and convert the entries into integers.
This gives you one list:
for a_i in xrange(n):
a.extend([int(x) for x in raw_input().split()])
and this a list of lists:
for a_i in xrange(n):
a.append([int(x) for x in raw_input().split()]):
You get this error because you try to give all inputs in one line. To handle this issue you may use this code
n = int(raw_input().strip())
a = []
while len(a)< n*n:
x=raw_input().strip()
x = map(int,x.split())
a.extend(x)
print(a)
I keep getting the
"too many variables to unpack"
error. Can anybody help me get this working, and possibly give me an explanation?
wings_quantity = {
'small' : 8,
'medium' : 14,
'large' : 20,
'half bucket' : 30,
'bucket' : 65,
}
wings_price = {
'small' : 5.99,
'medium' :8.50,
'large' : 14.00,
'half bucket' :20.00,
'bucket' : 55.00
}
for number, key in wings_quantity:
print " "
print "There are "+(str(wings_quantity[number]))+ " wings in a "+(wings_quantity[key])+" size."
print " "
for number, key in wings_quantity:
ppw = wings_quantity[number] / wings_price[number]
print ('The cost per wing in a %s size is $') + ppw %wing_quantity[key]
You are close, but you forgot to put the iteritems() on the end of your for statements.
Change
for number, key in wings_quantity:
to
for number, key in wings_quantity.iteritems():
After that problem you need to rewrite your print statements as they are trying to access the dictionary twice. Since you already have the values you can just print them like so:
print "There are "+ key + " wings in a "+ str(value) +" size."
I tested this in 3.4 and it worked, but in 3.x you need to change it to
for number, key in wings_quantity.items():
This produced this output for the first loop
There are bucket wings in a 65 size.
There are small wings in a 8 size.
There are medium wings in a 14 size.
There are half bucket wings in a 30 size.
There are large wings in a 20 size.