Python 2.6.2 Very Beginner questions

Started by
14 comments, last by Esys 14 years, 8 months ago
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.
Advertisement
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.

-Landshark (Scott)

A Growing Community of Aspiring Game Developers

www.gamedev4beginners.net

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]
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".
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. :)

-Landshark (Scott)

A Growing Community of Aspiring Game Developers

www.gamedev4beginners.net

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

This topic is closed to new replies.

Advertisement