0

Develop a Python function which either returns the float square of its parameter x if the parameter is a number, or prints the string "Sorry Dave, I'm afraid I can't do that" if the parameter is a string, and then returns 0.0.

What am I doing wrong? I'm a first year CS student and I have no previous programming background.

I created a function that takes user input, evaluates what type of input it is and print different out puts for number and strings.

For that I used eval(var) func. I also the type(var) == type to verify the type and a if-else loop.

def findt():
    userin = input("Input: ")       # Takes user input
    inpeval = eval(userin)          # Evaluates input type    

    if type(inpeval) == int:        # If input is an int
        userfloat = float(inpeval)  # Modifies into a float
        print(userfloat ** 2)       # Prints the square of the value
    elif type(inpeval) == float:    # If input is a float
        print(inpreval ** 2)        # Prints the square of the value
    elif type(userin) == str:       # If input is a string
        print("Sorry Dave, I'm afraid I can't do that")   # Print a string
        return 0.0                  # Return 0.0
    else:
        print("Invalid Input")    
findt()

When I run my code it works well when input is an int, a float or a char. But if I write more than one char it returns me an error:

NameError: name 'whateverinput' is not defined.
J. Murray
  • 1,460
  • 11
  • 19
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Ofer Sadan Oct 23 '19 at 20:38
  • 2
    Be _very_ careful of using [`eval`](https://stackoverflow.com/a/1832957/4739755) - there's almost always a better way to do whatever you're using `eval` to do. You should also look into the python string methods, specifically [`string.isnumeric`](https://docs.python.org/3/library/stdtypes.html#str.isnumeric). The return of `input` will always be a string initially. – b_c Oct 23 '19 at 20:46
  • To be honest I don't really understand the use of `eval`. It was a suggestion of a class mate. My understanding of python is still very limited. I learned only a bit about basic operations, functions, data types, while and for loops. I never heard about `string.isnumeric` which looks like can solve my problem. I just want to solve the problem with the my limited knowledge on the subject – RicardoGoncalves Oct 23 '19 at 20:55
  • Use the **isinstance()** built-in function to test data types. It takes two parameters, your variable and the expected type. Very simple. – S3DEV Oct 23 '19 at 21:08

3 Answers3

0

You're trying to eval input before you know it's needed. Get rid of it entirely:

def findt():
    userin = input("Input: ")       # Takes user input

    if type(userin) == int:        # If input is an int
        userfloat = float(userin)  # Modifies into a float
...

The root problem is that you can't evaluate an undefined name. If your input is a string that is not the name of an object in your program, it will fail. eval requires everything you feed it to be defined.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • The problem then is that every input will be identified as a string as by default `input()` stores the value as a string. So how can I test if the user input was a number or a string? – RicardoGoncalves Oct 23 '19 at 21:11
0

Here is a better way to achieve your goal by using the string method isnumeric() to test if the input is numeric or not.

def findt():
    userin = input("Input: ")

    if userin.isnumeric():
        # userin is numeric
        result = float(userin) ** 2
        print(result)

    else:
        try:
            # userin is a float
            result = float(userin) ** 2
            print(result)
        except ValueError:
            # userin is a string
            print("Sorry Dave, I'm afraid I can't do that")
            return 0.0

findt()

Update: a concise version:

def findt():
    userin = input("Input: ")

    try:
        # userin is an int or float
        result = float(userin) ** 2
        print(result)
    except ValueError:
        # userin is a string
        print("Sorry Dave, I'm afraid I can't do that")
        return 0.0

findt()
codrelphi
  • 1,075
  • 1
  • 7
  • 13
0

I found the solution for my problem. The way I did it I take the input from the user and i try to convert it to a float. If it is a number it will convert and print a float that is the square of the input. If the input is a string it cannot be converted to a float and will give me an error so I use an except ValueError: to print the string I want and return 0.0.

def whattype():
    user_input = input(">>> ")
    try:                                                
            user_input = float(user_input)                      
            print(user_input ** 2)
    except ValueError:
            print("Sorry Dave, I'm afraid I can't do that")
            return 0.0

whattype()

Thank you all for the suggestions and help