# 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.

## 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 on other sites
Programmer's skill #1: looking things up in the documentation

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

##### Share on other sites
%i prints an integer, you want a float %0.2f which displays a float number to the 2nd decimal place.

##### 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 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 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 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 on other sites
Quote:
 Original post by ZahlmanI 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 on other sites
Quote:
 Original post by dmatterAs 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 on other sites
I do my pyhton input like this:

some_name = int(raw_input("What is your name?")

##### Share on other sites
Quote:
 Original post by LandsharkIt 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 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 eithera 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" % cashprint "This is how much each share costs:$%0.5f" % stockpriceprint "This is how much you want to make: $%0.2f" % cashgoalprint "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 objectstockfees2 = ()#python complains about the = sign on the next line, I don't know whyif 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 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 whyif 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 on other sites
Quote:
 Original post by LandsharkI 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 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.

##### 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.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628676
• Total Posts
2984179

• 13
• 12
• 9
• 10
• 10