1
import math
pi = 3.1415

r = float(input("Enter the radius: "))
angle = float(input("Enter the angle: "))
x = r * math.cos(angle)
y = r * math.sin(angle)

print ('x =', x, 'y =', y)

When I enter pi, or anything with pi, as answer for angle prompt, I get this error:

ValueError: could not convert string to float: 'pi'

Any suggestions what to do?

Levon
  • 138,105
  • 33
  • 200
  • 191

2 Answers2

3

You get the error because "pi" is not a number. If you want it to recognize that string you need to do it manually before trying to convert it to a float.

def get_number(what):
    # Get value from user; remove any leading/trailing whitespace
    val = input('Enter the {}:'.format(what)).strip()
    if val.lower() == 'pi': # case insensitive check for "pi"
        return math.pi
    try: # try converting it to a float
        return float(val)
    except ValueError: # the user entered some crap that can't be converted
        return 0

Then, in your main code, simply use this:

r = get_number('radius')
angle = get_number('angle')

And please get rid of pi = 3.1415 - when you need pi, you use math.pi which is much more exact and the way to go.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • That's pretty easy code. Try to understand each line of it and lookup anything you don't understand. – ThiefMaster Sep 01 '12 at 12:40
  • While this would solve the immediate problem, I don't see it being terribly useful since it won't handle things like "2*pi". – Mu Mind Sep 12 '12 at 08:27
0

This code works fine in python 2, but the input function was changed between python 2 and python 3 in compliance with PEP 3111:

  • What was raw_input in python 2 is now called just input in python 3.
  • What was input(x) in python 2 is equivalent to eval(input(x)) in python 3.

This is how it always should have been, as calling eval on user input is unsafe and unintuitive, certainly shouldn't be the default for user input, and is still easy to do if that's what you really want.

Taking your code example as a toy example, you can make it work by replacing

r = float(input("Enter the radius: "))
angle = float(input("Enter the angle: "))

with

r = float(eval(input("Enter the radius: ")))
angle = float(eval(input("Enter the angle: ")))

but you DO NOT want to do that in real-world code. Instead, you would want to use one of the solutions suggested in this question: Equation parsing in Python.

Community
  • 1
  • 1
Mu Mind
  • 10,935
  • 4
  • 38
  • 69