Jump to content

Python 3 problem

CornOnJacob

I'm a relative beginner to Python, and I'm writing a short program in IDLE. After prompting the user for a price, I run this code:

try:    Current_price = float(Current_price)except ValueError:    print("That's not a number!")

If Current_price successfully converts to a float, I want to use it for calculations. If not (i.e. it is text) I want to throw an error. When I run this to test it and input text, I get this error:

Traceback (most recent call last):  File "C:\Users\Kids\Desktop\Stock Profit Calculator.py", line 27, in <module>    profit(D_investment, D_shares, G_investment, G_shares)  File "C:\Users\Kids\Desktop\Stock Profit Calculator.py", line 20, in profit    profit = (Current_price * shares) - investmentTypeError: unsupported operand type(s) for -: 'str' and 'float'

How can I get the program to prompt the user for a number a second time?

Thanks, 

    Jacob

[spoiler=My Current PC]AMD FX-8320 @ 4.2 Ghz | Xigmatek Dark Knight Night Hawk II | Gigabyte GA-990FXA-UD3 | 8GB Adata XPG V2 Silver 1600 Mhz RAM | Gigabyte 3X Windforce GTX 770 4GB @ 1.27 Ghz/7.25 Ghz | Rosewill Hive 550W Bronze PSU | Fractal Design Arc Midi R2 | Samsung Evo 250 GB SSD | Seagate Barracuda 1TB HDD | ASUS VS239H-P | Razer Deathadder 2013 Partlist

 

LTT Build-Off Thread: http://linustechtips.com/main/topic/35226-the-ltt-build-off-thread-no-building-required/

Link to comment
Share on other sites

Link to post
Share on other sites

Please post all your code!!

CPU: i7 4770k | GPU: Sapphire 290 Tri-X OC | RAM: Corsair Vengeance LP 2x8GB | MTB: GA-Z87X-UD5HCOOLER: Noctua NH-D14 | PSU: Corsair 760i | CASE: Corsair 550D | DISPLAY:  BenQ XL2420TE


Firestrike scores - Graphics: 10781 Physics: 9448 Combined: 4289


"Nvidia, Fuck you" - Linus Torvald

Link to comment
Share on other sites

Link to post
Share on other sites

It seems that you're trying to multiply a string ('str') by a float, which means that Current_price is being set to the user input, and then despite you trying to throw an error, you're getting a type error. Maybe try throwing a type error for your price check, or you have to exit the program/only set Current_price to the input once it has been deemed of float type.

 

I'd set the user input to a new variable, test that, and then if it is a float, set Current_price to the value of the input.

Link to comment
Share on other sites

Link to post
Share on other sites

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

×