Sign in to follow this  

Python 2.6.2 Very Beginner questions

This topic is 3042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Intro: Hey, what's up. I'm learning python (still...). I'm using 2.6.2 and running IDLE for the coding part. I've been following a very easy to follow tutorial on youtube to get me started. This is the 2nd time I've tried to start learning Python, but I feel much less confused so far and really am enjoy it. Forgive me if I use the wrong coding terms, I'm still learning! Anyway, my goal for myself this week is to produce a very simple, yet functional and useful (to me) program. Problem: I am writing a program to calculate how much a stock price must rise in order to meet your profit goal. It's pretty simple math. Basically, the program takes in the users cash they want to spend, price of stock, how much money they want to make 'profit' from the stock and any fees associated with the stock transaction (broker fees). It then tells them how much the stock must rise in price before they can sell and meet their profit goal. Here's the code so far (minus all the math stuff, which will probably be posted later when/if I have problems with it)
cash=input("How much money do you want to spend? ")
stockprice=input("What is the share price of the stock? ")
cashgoal=input("How much money do you want to make as profit? ")
stockfees=input("What is the stock transaction fee (if applicable)? ")
print ""
print "This is how much money you have to spend: $%i" % cash
print "This is how much each share costs: $%i" % stockprice
print "This is how much you want to make: $%i" % cashgoal
print "This is how much each stock transaction costs: $%i" % stockfees
The problem I'm having is working with decimal numbers. For the stock price, if I use a number such as 0.179, when 'print' the info back to the user (this is just for testing purposes now) it returns a '0' value. But, this only happens when I print the info using a %i in the string. If I just print the integer without using the %i in the string:
print stockprice
Then it will return the correct value of '0.179'. I'm missing the info on how to convert the 'stockprice' into something the %i can handle correctly. Or maybe I shouldn't be using %i for decimals...or maybe I need to take the 'stockprice' after the user has given input and convert it to something else before using the %i in the str. Anyway, help please! :) ps: what's the correct way to post formatted code? I used [ code ] and [ /code ], but I don't see what it did exactly.

Share this post


Link to post
Share on other sites
Programmer's skill #1: looking things up in the documentation

http://docs.python.org/library/stdtypes.html#string-formatting-operations

Share this post


Link to post
Share on other sites
So yeah, you want to be using %f for floating point values (numbers that we normally consider to be decimals). Binary Floating Point numbers represent a standard and efficient way for a machine to store and use decimal numbers, unfortunately the price for this efficiency is that we sacrifice precision.

Python does support decimal (as opposed to binary) floating point numbers and arithmetic, which if you're interested in learning about you can read more here. We use regular binary floating point values 99% of the time and decimals floating point values for the 1% where precision is paramount (you don't want to be losing money in your bank account everytime the bank do their account processing just because of a precision issue).

As for [ code ] tags, they make it so that:
1) Each symbol has the same width, which makes aligning text across multiple lines easy, and
2) Consecutive spaces are preserved when you post. Normally multiple spaces get collapsed into a single space.

You can also use the [ source lang="python" ] [ /source ] tags to get syntax highlighting in an embedded scrollable box.
Also, to get this inline pre-formatted text you can use < tt > < /tt > tags, they're different from code tags in that they can be used on a single line amongst regular text and they don't fulfill #2 above, so spaces are still collapsed. Incidentally code tags are really just < pre > < /pre > tags. [smile]

Share this post


Link to post
Share on other sites
You guys rock, thank you so much for the help! That's why I posted here. :)

I suspect it would make more sense for me to use the %0.2f for all my values to help show dollar and change amounts.

I'll read through the docs referenced above. I promise I DID do a lot of searching for the answer, but I think I worded my searches wrong. I was looking for integer to decimal conversions and all I got was integer to binary stuff which didn't seem applicable to my question.

Anyway, thank you all!

Share this post


Link to post
Share on other sites
As an aside, I almost never use input, this evaluates the user's input almost like a piece of python code; the user could run riot this. As an example try typing in cash as the response when it asks you about profit and see what happens. Then imagine if you had a function in your code for transacting money to and fro between bank accounts and you were to let the user get wind of this function's name.. [tears]

In place of that you can intead use either raw_input or sys.stdin.readline (if you import sys first). These return your response as a regular string with no evaluating going on whatsoever, so they're safe. If you want to get a user's input as a number rather than a string then you can cast it:

cash = float(raw_input("How much money do you want to spend? "))

(If you want an integer then use int(..) instead).

Note that in Python 3, raw_input has been renamed to input and the function previously known as input has been dropped.

Share this post


Link to post
Share on other sites
I won't fault you for using wrong terminology, but you really ought to have noticed that there's a whole separate forum for beginner questions. :) Moved.

Share this post


Link to post
Share on other sites
Quote:
Original post by Zahlman
I won't fault you for using wrong terminology, but you really ought to have noticed that there's a whole separate forum for beginner questions. :) Moved.


Noted. :) Thanks!

Share this post


Link to post
Share on other sites
Quote:
Original post by dmatter
As an aside, I almost never use input, this evaluates the user's input almost like a piece of python code; the user could run riot this. As an example try typing in cash as the response when it asks you about profit and see what happens. Then imagine if you had a function in your code for transacting money to and fro between bank accounts and you were to let the user get wind of this function's name.. [tears]

In place of that you can intead use either raw_input or sys.stdin.readline (if you import sys first). These return your response as a regular string with no evaluating going on whatsoever, so they're safe. If you want to get a user's input as a number rather than a string then you can cast it:

cash = float(raw_input("How much money do you want to spend? "))

(If you want an integer then use int(..) instead).

Note that in Python 3, raw_input has been renamed to input and the function previously known as input has been dropped.


Dmatter,

As far as learning goes and what I should take with me from your post: It looks like best practice, if you know the input data type before-hand, is to only ask for that type of data. Hence using cash = float(raw_input(..)) Because I know it's going to be a float then I should only ask for a float. I'll keep that in mind from now on. Thanks for your help.

Share this post


Link to post
Share on other sites
Quote:
Original post by Landshark
It looks like best practice, if you know the input data type before-hand, is to only ask for that type of data.
Yes. In fact it's rather tricky to perform any meaningful processing on data without knowing, or making some assumptions about, what sort of data it's going to be beforehand.

The input function is basically defined as: eval(raw_input(..)) anyway, and almost always you neither need nor want the eval bit, better to use raw_input directly. Unfortunately the name 'raw input' sounds sort of scary compared to just 'input' so people get the wrong impression of the two, believing that you want to use input by default and raw_input if you want to do something fancy - this isn't so. This whole thing goes against the core principle of pythonicism, hence Python 3 has remedied the situation.

Share this post


Link to post
Share on other sites
Argh, ok I don't really want to have to ask this here, but here it goes.

I am worried about what will happen if someone leaves a blank or uses a string of text to answer any of the questions in the program, although for testing purposes I'm only dealing with the stockfees object for now. If I'm looking for float values, but receive either a blank or anything other than a float then it'll cause an error.

Here's the part in question:


cash = float(raw_input("How much money do you want to spend? "))
stockprice = float(raw_input("What is the share price of the stock? "))
cashgoal = float(raw_input("How much money do you want to make as profit? "))
stockfees = str(raw_input("What is the stock transaction fee (if applicable)? ") #Here I'm asking for a str and not a float

""" I need to put something here to convert the stockfees str into either
a float(0) (if the user inputs anything other than an int/float)
or to convert the str into a float using stockfees = float(stockfees)
"""

print""

print "This is how much money you have to spend: $%0.2f" % cash
print "This is how much each share costs: $%0.5f" % stockprice
print "This is how much you want to make: $%0.2f" % cashgoal
print "This is how much each stock transaction costs: $%0.2f" % stockfees









I know you can simply convert a str to float using stockfees = float(stockfees), but this doesn't help me if the stockfees str is the word 'zero' or simply a blank.

I thought about using an if/then statement (I don't like these statements)


#first I define my compare/test object
stockfees2 = ()

#python complains about the = sign on the next line, I don't know why
if stockfees = stockfees2: #if stockfees was left blank
stockfees = float(0) #convert stockfees to a float(0)
else:
stockfees=float(stockfees) #assume stockfees was typed as an int and convert to float







Ok, but what if someone typed a string into the stockfees prompt?

I suppose the best solution would be to not accept strings in any of the inputs and simply inform the user to type int/numbers only (I'll have to learn how to do that). I still am not quite sure how to properly get the rest of the above code to work. I don't know why the if/then statement won't accept my = sign on the 'if' line.

I've been reading for the past couple of hours on how to properly use if/then statements in python, but I haven't found a code examples using the '=' sign, only the '=='. I thought the '==' meant not equal to? Python accepts the '=' sign everywhere else, but not on the 'if' line of the if/then statement from what I can tell. I wasn't able to find any docs anywhere explaining that to me.

Share this post


Link to post
Share on other sites
Quote:
I am worried about what will happen if someone leaves a blank or uses a string of text to answer any of the questions in the program, although for testing purposes I'm only dealing with the stockfees object for now. If I'm looking for float values, but receive either a blank or anything other than a float then it'll cause an error.

It will raise a ValueError exception, which you can handle by using apropriate try and catch blocks.

Quote:
#python complains about the = sign on the next line, I don't know why
if stockfees = stockfees2: #if stockfees was left blank
stockfees = float(0) #convert stockfees to a float(0)

...
I suppose the best solution would be to not accept strings in any of the inputs and simply inform the user to type int/numbers only (I'll have to learn how to do that). I still am not quite sure how to properly get the rest of the above code to work. I don't know why the if/then statement won't accept my = sign on the 'if' line.

I've been reading for the past couple of hours on how to properly use if/then statements in python, but I haven't found a code examples using the '=' sign, only the '=='. I thought the '==' meant not equal to? Python accepts the '=' sign everywhere else, but not on the 'if' line of the if/then statement from what I can tell. I wasn't able to find any docs anywhere explaining that to me.
That's because you're trying to assign to a variable inside an if statement, and Python won't allow you to do that. You use '=' when you want to assign something to a variable, and '==' to test for equality. In that case, you wanted to test for equality, then use '=='. But there is also another mistake in there: if you want to test for an empty string, you'd use
if stockfees == "":
...
In your code, you're trying to test a string against a tuple, they're different types, and will ever evaluate to false.

[Edited by - fcoelho on August 14, 2009 3:27:34 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Landshark
I thought the '==' meant not equal to? Python accepts the '=' sign everywhere else, but not on the 'if' line of the if/then statement from what I can tell. I wasn't able to find any docs anywhere explaining that to me.
In python '=' is the assignment operator and '==' is the equality operator. The former is used to assign a value to a variable whilst the latter is used to compare two values for equality. The assignment operator is illegal within an if-statement in Python, the reason being is that there are other languages which allow it (for no real benefit) and as a consequence it's an endless source of subtle bugs (accidentally typing '=' instead of '==') for programmers to contend with; by making it illegal Python eliminates those bugs. The inequality operator is '!=', i.e. "not equal to".

Share this post


Link to post
Share on other sites
Ok, Here's what I've got so far. I made a ton of progress (at least I feel like I have) thanks to everyone's help! My program works, finally.


while True:
while True:
try:
cash = float(raw_input("How much money do you want to spend? "))
break
except ValueError:
print "Oops! Please type in a number or 0 for none..."

while True:
try:
stockprice = float(raw_input("What is the share price of the stock? "))
break
except ValueError:
print "Oops! Please type in a number greater than 0..."

while True:
try:
cashgoal = float(raw_input("How much money do you want to make as profit? "))
break
except ValueError:
print "Oops! Please type in a number or 0 for none..."

while True:
try:
stockfees = float(raw_input("What is the fee per stock transaction (if applicable)? "))
break
except ValueError:
print "Opps! Please type in a number or 0 for none..."

print ""

#The next 4 lines can be commented out on the final product
"""
print "This is how much money you have to spend: $%0.2f" % cash
print "This is how much each share costs: $%0.5f" % stockprice
print "This is how much you want to make: $%0.2f" % cashgoal
print "This is how much each stock transaction costs: $%0.2f" % stockfees
"""


#This next section is the math behind the code

totalcashgoal = cash + cashgoal #cash on hand + desired profit
cash = cash - stockfees * 2 #cash on hand - all stock transaction fees
boughtshares = int(cash/stockprice) #how many shares user can afford to buy after all fees
targetstockprice = float(totalcashgoal / boughtshares) #price stock needs to be at to sell for desired profit

print ""

print "You need to buy %i shares of stock." % boughtshares
print "When the stock price reaches $%0.4f you should sell for a profit of $%0.0f, leaving you with a total of $%0.0f." %(targetstockprice, cashgoal, totalcashgoal)
print ""

endprogram = raw_input("Do you want to exit? Type 'Yes' to exit or 'No' to restart the program: ")
if endprogram == 'yes':
break




Aside from anything obvious that might be wrong with that code that I have overlooked, the only remaining issue is handling 0's and numbers with decimals greater than 4 or 5 places. The code can't handle certain float numbers when it's computing the math section of the code and I think this is mainly for the 'stockprice' object. In a real world a stock price would never be 0, but I don't like leaving open ends like this. I think it's pretty much just for 0's and lengthy decimal numbers though. I'd like to figure out how to fix that (although I may just deal with it in exception handling, which has been fun to learn and mess with so far).

This is officially the very first program I've ever written on my own. And although it's nothing monumental, I'm very proud of it. :)

Share this post


Link to post
Share on other sites
Another way you can do string interpolation so it's easier to read would be:

print "When the stock price reaches $%(targetstockprice)0.4f you should sell for a profit of $%(cashgoal)0.0f, leaving you with a total of $%(totalcashgoal)0.0f." % vars()

Share this post


Link to post
Share on other sites

This topic is 3042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this