Kelsey
Kelsey

Reputation: 55

Dealing with Definitions

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):

  1. Add a Stock
  2. Recommend Sale
  3. 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

Upvotes: 0

Views: 85

Answers (2)

Blckknght
Blckknght

Reputation: 104722

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)

Upvotes: 1

Vor
Vor

Reputation: 35129

for x in expected_value.key():

should be

for x in expected_value.keys():

also use raw_input

Upvotes: 1

Related Questions