Question

I have this dictionary:

stocks = {'FB': 255, 'AAPL': 431, 'TSLA': 1700}

and this script:

shares = input('How many shares? ')
stock = input('What\'s the stock? ')

for name in stocks.keys():
    ticker = (stocks[name])
    if name == stock:
        print('The price for', stock, 'is', ticker)
    
amount = int(ticker) * int(shares)
print(amount)

I wanted to access the value of the key when it is selected in the "stock" input and multiply the ticker chosen in the input, but it always multiplies 'TSLA' value 1700 by the number of shares selected, even if I choose FB as stock input.

The right output should be:

How many shares? 10

What's the stock? FB

2550

Instead I get 17000

I'd like to understand why.. thank you!

Was it helpful?

Solution

The reason is that ticker = (stocks[name]) is outside the if-statement. Since the loop does not stop when name == stock it continues to loop until the end of stocks and name will always be assigned to the last key in the dict.

One of multiple solutions is to move it within the if-statement:

shares = input('How many shares? ')
stock = input('What\'s the stock? ')

for name in stocks.keys():
    if name == stock:
        ticker = (stocks[name])
        print('The price for', stock, 'is', ticker)

amount = int(ticker) * int(shares)

print(amount)   

This gives:

How many shares? 10
What's the stock? FB
The price for FB is 255
2550

And you get the same output even without a loop:

shares = input('How many shares? ')
stock = input('What\'s the stock? ')

ticker = (stocks[stock])
print('The price for', stock, 'is', ticker)

amount = int(ticker) * int(shares)

print(amount) 

This gives:

How many shares? 10
What's the stock? FB
The price for FB is 255
2550

OTHER TIPS

You can try this (add the amount in if-block) :

import pandas as pd

stocks = {'FB': 255, 'AAPL': 431, 'TSLA': 1700}

shares = input('How many shares? ')
stock = input('What\'s the stock? ')

for name in stocks.keys():
    ticker = (stocks[name])
    if name == stock:
        print('The price for', stock, 'is', ticker)
        amount = int(ticker) * int(shares)

print(amount)
Licensed under: CC-BY-SA with attribution
Not affiliated with datascience.stackexchange
scroll top