I am trying to get the expected value, but I seem to be having trouble. I turned the input values to integers and I think that is where the error is coming from. I know the int cannot convert an empty string to the integer, but when testing this I had a value.
Error:
TypeError: 'int' object is not subscriptable
What can I do to fix this problem?
def print_menu():
print('1. Add a Stock')
print('2. Recommend Sale')
print('3. Quit')
print()
expected_value = {}
menu_choice = 0
print_menu()
while menu_choice != 3:
menu_choice = int(input("Type in a number (1-3): "))
if menu_choice == 1:
print("Add Name, Prices, Risk, Shares")
name = input("Name: ")
price = input("Buyers Price: ")
Cprice = input("Current Price: ")
srisk = input("Risk: ")
sshares = input("Shares: ")
Expected_Sale_value = ((int(Cprice) - int(price)) - int(srisk) * int(Cprice)) * int(sshares)
expected_value[name] = Expected_Sale_value
elif menu_choice == 2:
print("Expected Sale values")
for x in expected_value.keys():
print("Stock: ", x, "\tExpected value:", Expected_Sale_value[x])
print()
elif menu_choice != 3:
print_menu()
I am new to python, and I know python has its tricks! Saying that I ask if there are any tips or you see something I can improve on please give me insight.
EXAMPLE(IDLE):
Add a Stock
Recommend Sale
Quit
Type in a number (1-3): 1
Add Name, Prices, Risk, Shares
Name: Google
Buyers Price: 21
Current Price: 20
Risk: 1
Shares: 2
Type in a number (1-3): 2
Expected Sale values
Traceback (most recent call last):
File "", line 25, in
print("Stock: ", x, "\tExpected value:", Expected_Sale_value[x])
TypeError: 'int' object is not subscriptable
You have an error where you're using the wrong variable name. Here are the relevant lines:
for x in expected_value.keys():
print("Stock: ", x, "\tExpected value:", Expected_Sale_value[x])
In the print statement you are indexing into the variable Expected_Sale_value rather than expected_value. Expected_Sale_value is an integer, rather than a dictionary, so you get an exception.
A slightly more "Pythonic" way of doing the loop would be:
for key, value in expected_value.items():
print("Stock: ", key, "\tExpected value:", value)
for x in expected_value.key():
should be
for x in expected_value.keys():
also use raw_input
Related
I'm a beginner and this is my first receiving this message "IndexError: list index out of range," can someone please tell me how to fix it? and what exactly did I do wrong? Also if someone can run it and make sure it does what it's supposed to because I need another person other than me to run it(Professor's instruction)
This is the output it gave me -
Traceback (most recent call last):
File "", line 74, in
File "", line 24, in user
IndexError: list index out of range
Here's my code:
print ("Dish No. Dish Name Price ")
print (" -------- --------- ------")
print (" 1 Gang Gai $10.00")
print (" 2 Pad Thai $8.75")
print (" 3 Pad Cashew $9.50")
print (" 4 Pad Prik $10.25")
print (" 5 Peanut Curry $9.50")
print (" 6 Curry Noodles $11.25")
def user():
array = [10,8.75,9.50,10.25,9.50,11.25]
cart = []
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
xx=input("Would you like to order another item( Yes or No)?: ")
if xx.lower() == "no":
break
checkout(cart)
# if xx=='No'.lower():
# return array[x-1]
# else:
# return array[x-1]+user(array)
def seniorCitizen():
print("Are you 65 years or older(Yes or No)? ")
xsenior = input()
if xsenior.lower() == "yes":
senior = True
else:
senior = False
return senior
def checker(num):
if num > 6 or num < 1:
return "wrong number"
def checkout(cart):
senior = seniorCitizen()
titems = 0
for item in cart:
titems = titems + item
print(" Bill Information ")
print("-------------------------------")
print("Total of all items: $",titems)
if senior == True:
boomercount = titems * 0.1
boomercount = round(boomercount, 2)
print("Total senior discounts:-$", boomercount)
tax = round((titems-boomercount)*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round(((titems-boomercount)+tax), 2))
else:
tax = round(titems*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round((titems+tax), 2))
user()
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
The problem is the pass statement. It does not restart the loop -- it does nothing at all. So if the user enters a wrong number, it prints an error message but then it keeps going and tries to access array[x-1] which is out of range.
Use continue which will start the loop over, instead of pass.
I have just started learning about classes. In the examples that I'm learning I notice how everything that gets instantiated is hardcoded into the examples. I wanted to try and figure out if I could instantiate without having to do this, by means of user input.
In line 74/75 my expectation is that print(RecordID_map_PilotID[valUE].flownhours) prints me the number of hours I have chosen to log for a specific instance. Instead I'm confronted with the following pesky error:
Traceback (most recent call last):
File "oop_test.py", line 74, in <module>
RecordID_map_PilotID[valUE].recordflytime(loghours)
AttributeError: 'str' object has no attribute 'recordflytime'
Can anyone please help me understand why what I intend Python to do doesn't actually work?
Thank you!
PilotID_ClassValCalls = {}
RecordID_map_PilotID = {}
class PilotRecord:
department = "Aviation"
asset = "Employee"
assetcategory = "FTE"
flownhours = 0
def __init__(self, pilotid, name, age, licensestatus, licenseexpiration, shiptype, callsign, flownhours):
self.pilotid = pilotid
self.name = name
self.age = age
self.licensestatus = licensestatus
self.licenseexpiration = licenseexpiration
self.shiptype = shiptype
self.callsign = callsign
self.flownhours = flownhours
def __str__(self):
return f"{self.pilotid} has an {self.licensestatus} license with an expiration date of {self.licenseexpiration} with the following callsigns:\n {self.callsign} ."
def recordflytime(self, hours):
self.flownhours = self.flownhours + hours
def Adding_Pilot_Records(): #This definitions created new pilot records and instantiates a new object for each pilot rcord that is created. In addition memory values are stored in Dict
add_records_number = int(input("How many pilot records would you like to add? "))
for eachrecord in range(add_records_number):
record_store = [input("Please provide pilot ID: "), input("Please provide pilot Name: "), int(input("Please provide pilot Age: ")),
input("Please provide pilot licensestatus: "), input("Please provide pilot licenseexpiration: "), input("Please provide pilot shiptype: "), input("Please provide pilot callsign: "), 0]
PilotID_ClassValCalls.update({eachrecord + 1 : record_store[0]})
RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]})
PilotID_ClassValCalls[eachrecord+1] = PilotRecord(record_store[0], record_store[1], record_store[2], record_store[3], record_store[4], record_store[5], record_store[6], record_store[7])
while True == True:
print("Hello, Welcome to the PILOT RECORD DATABASE\n",
"What would you like to do with the Records?:\n\n",
" \t1 - \"Add\"\n",
" \t2 - \"Log\"\n",
" \t3 - \"Delete\"\n",
" \t4 - \"Quit\"\n")
userchoice = str(input().lower().strip())
try:
if userchoice == "1" or userchoice == "add":
Adding_Pilot_Records()
continue
elif userchoice == "2" or userchoice == "log":
while userchoice == "2" or userchoice == "log":
pickarecord = str(input("Which Record ID would you like to create a log for? ")).split()
pickarecord_yesno = input(f"Selected Record >>> {RecordID_map_PilotID[pickarecord[0]]}, Is this the correct record? [Y] [N] [Quit]").upper().split()
userchoice = ""
if pickarecord_yesno[0] == "Q" or pickarecord_yesno[0] == "QUIT":
break
elif pickarecord_yesno[0] == "Y" or pickarecord_yesno[0] == "YES":
userchoice = ""
loghours = int(input(f"How many hours would you like to log?"))
pickarecord = str(pickarecord[0])
for record, valUE in RecordID_map_PilotID.items():
if pickarecord in valUE:
RecordID_map_PilotID[valUE].recordflytime(loghours)
print(RecordID_map_PilotID[valUE].flownhours)
elif pickarecord_yesno[0] == "N" or pickarecord_yesno == "NO":
userchoice = "2"
continue
elif userchoice == "3" or userchoice == "delete":
continue
elif userchoice == "4" or userchoice == "quit":
break
except ValueError:
print("Sorry an Error has occurred")
This is the line causing the error:
RecordID_map_PilotID[valUE].recordflytime(loghours)
You're trying to call .recordflytime() on RecordID_map_PilotID[valUE]. But RecordID_map_PilotID is a dictionary of type str -> str, so RecordID_map_PilotID[valUE] references a string and strings don't have .recordflytime() methods.
I can tell it's a string, because this line is the only line modifying it:
RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]})
So, you're updating one dict with another, with a single key/value pair, the key being PilotID_ClassValCalls[eachrecord+1] and the value record_store[0]. PilotID_ClassValCalls is filled similarly, and its value also typically is record_store[0]. And you fill record store with the result of a call to input(), which is a string.
I would suggest you read some examples on object-oriented programming in Python - I think you're trying to do 'by hand' what is better done with the specific data structures and methods that exist for it in Python.
More generally, it's a good idea to separate the structures that hold and operate on data from the code that gets an processes input. After all, you want to manipulate these objects with direct user input now, but what if you save stuff out to a file and read it back later? Or perhaps call your code from a web page? You'd want to use the same classes, but without the direct calls to input() resulting in your code expecting input on the console.
I am trying to create a basic online store in python. But whenever I try to 'buy' an item it shows an error with my dictionary or something I am not sure.
The error: users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
TypeError: str() takes at most 3 arguments (6 given)
coun = 0
users = [{"name":"Jack","username":"ja", "cc":'12345',"email":'whwhwwhh', "code": '111', "Transactions": ""}]
def sign_in():
username = input("Enter username")
for i in range (len(users)):
for x in users[i].values():
if x == username:
pin = input("Enter pin")
if pin == users[i].get("code"):
print("Welcome", users[i].get("name"))
menu(username,users[i].get("name"))
break
else:
print("Wrong pin")
sign_in()
def menu (usern, names_f):
global coun
if coun == 0:
order = ''
total = 0
for i in range (len(categories)):
print(str(i+1)+".", categories[i])
choice = int(input("Choose a category by typing the number beside the categories name."))-1
print("Items in this list are")
print("Itemname \t Price \t Stock")
final = location[choice]
for c in range((int(len(final)/3))):
print(str(c+1)+'.',str(final[c*3]),"\t",'$'+str(final[c*3+1])), "\t", str(final[(c*3)+2])
choice = int(input("Which item (Type number on left of the item name)"))-1
while True:
quanti = int(input("How many do you want to buy"))
if quanti > final[choice*3+2]:
print("Sorry your request for", quanti, "Is more than we have at the store please try again")
continue
else:
price = str(quanti*final[choice*3+1])
final[choice*3+2] = final[choice*3+2]-quanti
print("Thank you for your purchasing",quanti,"of", final[choice*3], "Your total price of this buy is", '$'+price)
for n in range (len(users)):
if usern == users[n].get("username"):
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
order += str(quanti, 'of', final[choice*3])
price += int(price)
done = input("Do you want to check out then type '1' if you want to continue type '2'")
if done == '1':
print("Thank you")
print ("Invoice:", order, "/n total price (HKD) $"+str(price))
else:
coun += 1
menu(usern,names_f)
variable_name = users[n]["Transactions"] + str(names_f) + "bought" + str(quanti) + "of" + str(final[choice*3]) + "with a total price of $"+ str(price)
users[n]["Transactions"] = variable_name
You will maybe need to declare variable_name somewhere.
Problem is that str usage is following
str(object, encoding=encoding, errors=errors)
but whenever you pass comma it count it as another parameter.
P.S. I'm not sure if you need all those str in my solution.
str is a class, and as stated in the docs you can pass up to 3 parameters to it:
class str(object=b'', encoding='utf-8', errors='strict')
Also, it also says what it does:
Return a string version of object. If object is not provided, returns the empty string.
Meaning it is used to cast other types to string. Thus, you need to convert every int individually:
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f) + " bought " + str(quanti) + " of " + str(final[choice*3]) + " with a total price of " + str(price)
Note the spaces before and after every string. Alternatively, you can format your string:
users[n]["Transactions"] = users[n]["Transactions"] + '%s bought %s of %s with a total price of %s' % (names_f, quanti, final[choice*3], price)
As a side note, it's worth checking what happens when the first transaction is made. If the key Transactions does not yet exist, you need to add an initial value before accessing it.
I usually do it like:
if key not in dict_:
dict_[key] = 'my initial value'
dict_[key] += 'add my stuff'
another solution would be using the get method, which allows you to add a default value:
dict_.get(key, 'default')
Note that this will not add the key to the dictionary, meaning that trying to access its value later on will still result in a Key Error.
I'm resolving a basic problem consisting of make a list of products, the user choose the product and the amount of the product and the total price is printed. I get a keyerror in the line 22.
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[code] * quantify)
print("The total price is: $", totalPrice)
The error displayed is
Traceback (most recent call last):
File "main.py", line 30, in <module>
main()
File "main.py", line 22, in main
print("The price is $", relation[code])
KeyError: '5'
In this case I choose the product code "5".
When you use input it returns a string, not an integer. You can see this because the error message shows '5', not 5. The keys to your dictionary are integers, though, so the key you are providing in the statement (code) is not found.
You could instead use
print("The price is $", relation[int(code)])
A better format, at least in Python 3.6 and later, would be
print(f"The price is ${relation[int(code)]}")
for line 26, the problem is similar. Just convert to integers (or float, if there's a decimal point)
totalPrice = float(relation[int(code)] * int(quantify))
or
totalPrice = relation[int(code)] * float(quantify)
input in python receives data as a string, you need to typecast it
it is something along:
print("The price is $", relation[int(code)])
I think you should also follow the Python idiom EAFP (Easier to ask for forgiveness than permission) here when asking for user input as he could write literally everything but integers you expect:
while True:
code = input("Enter the product code: ")
try:
price = relation[int(code)]
except (ValueError, KeyError):
print("Error: Incorrect code value, try again!")
else:
break
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[int(code)] * quantify)
print("The total price is: $", totalPrice)
you need to take the input as integer because the input() take the default as a string so you can type it like quantify = int(input("Enter amount: "))
or another method is to use int() in the place where the calculations are like
totalPrice = float(relation[int(code)] * int(quantify))
i get this kind of error when i run my code but i didnt understood what does it mean i try to google for similar case but i didnt find anything .this is the error i get when i pressed the no responde
Traceback (most recent call last):
File "/home/main.py", line 27, in <module>
dataCheck(data);
File "/home/main.py", line 24, in dataCheck
values=data();
TypeError: 'tuple' object is not callable
and here is the code i wrote :
print("Welcome to the game!");
def data():
name=input("Give me your name: ");
lname=input("Give me your last name: ");
age=int(input("Give me your age: "));
return (name,lname,age);
def dataCheck(data):
name=data[0];
lname=data[1];
age=str(data[2]);
print("Your name: "+name);
print("Your Last name: "+lname);
print("Your age: "+age);
yn=input("The information are true Y/N :");
if yn.lower()=="y":
print("Welcome "+name);
elif yn.lower()=="n":
values=data();
dataCheck(values);
data=data();
dataCheck(data);
You have a namespace collision. Once you say data = data(), the function data() is gone, so when you call it with values = data(), you're trying to call the value it returned before.
Try this.
print("Welcome to the game!")
def get_data():
name = input("Give me your name: ")
lname = input("Give me your last name: ")
age = int(input("Give me your age: "))
return (name, lname, age)
def data_check(data):
name, lname, age = data
print("Your name: " + name)
print("Your Last name: " + lname)
print("Your age: " + str(age))
yn = input("The information are true Y/N :")
if yn.lower() == "y":
print("Welcome " + name)
elif yn.lower() == "n":
data_check(get_data())
data_check(get_data())
Note I also
Removed the semicolons (you don't need those in Python)
snake_cased the data_check function (that's the convention)
Used tuple unpacking instead of individual assignment in data_check(), it's handy shortcut
At one level, you made a mistake because you defined data as a function, redefined data as what the function returned and eventually tried to use data as the function that you defined at first (and Python complained that you are trying to use a tuple as a function: TypeError: 'tuple' object is not callable). Using different names for the function and the player info will suffice to solve your issue.
At another level, you named your function wrong. Functions represent actions, hence you should try to use action names for them. dataCheck is OK, (that, or check_data if you want to stress the verb), data is no good, get_data could be OK but get_player_data is even better, coupled with check_player_data as well.
As a first footnote, instead of name=data[0]; etc it's more idiomatic to unpack the whole tuple/list as in a, b, c = data.
Second one, Your dataCheck is not producing a result... were data in need of an edit you get new values but data is not going to be modified by your function.
Third and last, if you want to edit data in checkData, don't do
elif yn == 'n':
data = get_data()
because that's going to create a local assignment that is not reverberated at the level of the caller's name space.
always use some unique variable name or pay attention on function/variable name. In your case due to same name, it is considering data as tuple not the one you are trying to refer to.
please compare difference from your code and below.
print("Welcome to the game!");
def Input_data():
name=input("Give me your name: ");
lname=input("Give me your last name: ");
age=int(input("Give me your age: "));
return (name,lname,age);
def dataCheck(data):
name=data[0];
lname=data[1];
age=str(data[2]);
print("Your name: "+name);
print("Your Last name: "+lname);
print("Your age: "+age);
yn=input("The information are true Y/N :");
if yn.lower()=="y":
print("Welcome "+name);
elif yn.lower()=="n":
values=Input_data();
dataCheck(values);
data=Input_data();
dataCheck(data);
Do something like this:
def data_fn():
name=input("Give me your name: ");
lname=input("Give me your last name: ");
age=int(input("Give me your age: "));
return (name,lname,age);
def dataCheck(data):
name=data[0];
lname=data[1];
age=str(data[2]);
print("Your name: "+name);
print("Your Last name: "+lname);
print("Your age: "+age);
yn=input("The information are true Y/N :");
if yn.lower()=="y":
print("Welcome "+name);
elif yn.lower()=="n":
values=data_fn(); # instead of calling the tuple as function call the function itself
dataCheck(values);
data=data_fn();
dataCheck(data);
The issue with your code was that you were calling tuple as a function hence the error: 'tuple' object is not callable.
You should use raw_input, the raw_input will return <type 'str'>, and with input, if you want to input a string, you should use like this:
```
a = input('a:')
a: 'your input string'
```