How to convert this C++ code to python code?

I have a C++ code here which inputs some attributes for n objects of a class named stock.

1
2
3
4
5
6
7
8
9
10
11
    int counter=0;
    Stock* stock = new Stock[n]; //creating n stocks
    while (n--) {
		cout << "Enter ticker> " << flush;
		cin >> stock[counter].ticker;
		cout << "Enter current price> " << flush;
		cin >> stock[counter].currentPrice;
		cout << "Enter target price> " << flush;
		cin >> stock[counter].targetPrice;
		counter++;
	}

I'm trying to convert the same code to python but I can't figure it out. Here's my python code (which contains a lot of errors of course)

1
2
3
4
5
6
7
8
    counter=0
    stock= []
    while (n!=0):
        stock[counter].ticker=(input("Enter ticker> "))
        stock[counter].currentPrice= float(input("Enter current price> " ))
        stock[counter].targetPrice=float(input( "Enter target price> " ))
        counter+=1
        n-=1


Any suggestions/ corrections are appreciated!
Last edited on
The C++ version is scary. Raw. Standard Library containers are more convenient.
1
2
3
4
5
6
    std::vector<Stock> stock;
    stock.reserve( n );
    Stock entry;
    while ( n-- && std::cout >> entry ) {
        stock.push_back( entry );
    }

Then again, while convenient for syntax the std::istream& operator>> ( std::istream&, Stock& ); might not be optimal place to spit to cout.

Nevertheless, the point is to create an entry and test success of input first, and then append to collection.

I don't use Python, but Google bets that one appends to lists.
dict, list, set, tuple are the basic py containers.
you want list, I believe. ***list is actually vector in c++ terms*** its an array surrogate.


https://www.geeksforgeeks.org/python-list/
https://docs.python.org/3/library/stdtypes.html#list

Last edited on
Not very good on object-oriented python, but you could try
class Stock:
   def __init__( self ):
       self.ticker = input( "Enter ticker: " )
       self.currentPrice = float( input( "Enter current price: " ) )
       self.targetPrice  = float( input( "Enter target price: "  ) )
       print()

n = 3
stock = []
while n:
   stock.append( Stock() )
   n -= 1

for s in stock:
   print( s.ticker, s.currentPrice, s.targetPrice )
Topic archived. No new replies allowed.