Home > Software design >  What is the problems with my code and how to fix it?
What is the problems with my code and how to fix it?

Time:12-07

def ask_a():
    a = input("""Please enter a:
a = """)
    a = eval(a)
    if a == 0:  
        print("Please input the correct number! \n")
        ask_a()
    elif isinstance(a, str):
        print("Please input the correct number! \n")
        ask_a()
    else:
        print(a)
        return a

ask_a()

I'm making a quadratic equation solver by python 3 and that is what i write for asking for a (a is not 0 and a is not a string)

This is what the error message:

Please enter a:
a = sgafdf
Traceback (most recent call last):
  File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 15, in <module>
    ask_a()
  File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 4, in ask_a
    a = eval(a)
  File "<string>", line 1, in <module>
NameError: name 'sgafdf' is not defined
PS C:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects> & C:/Users/jbtua/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/jbtua/OneDrive/Desktop/wut is this/Personal Folder/Programming Projects/Python/blank-1.py"
Please enter a:
a = a
Please input the correct number! 

Please enter a:
a = w
Traceback (most recent call last):
  File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 15, in <module>
    ask_a()
  File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 10, in ask_a
    ask_a()
  File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 4, in ask_a
    a = eval(a)
  File "<string>", line 1, in <module>
NameError: name 'w' is not defined

What should I do to avoid this? I will appreciate all the answer.

CodePudding user response:

Problem (1.)

You're calling eval(). Don't do that. It opens too many doors to remote exploits. Specify the business problem you're trying to solve, and propose a solution that doesn't involve eval.

Problem (2.)

You never assigned a value to sgafdf, nor to w, yet you tried to evaluate them.

That won't work.

Stick to defined variables in the expressions you try to evaluate.

CodePudding user response:

You are using the eval() function which will evaluate the string that is passed to it as code. For example, if you enter the input print(9) your code will print 9:

Please enter a:
a = print(9)
9
None

When you pass it invalid code as input it will throw that exception.

CodePudding user response:

Here you are using eval which evaluates the input as integer or float while the data that you entered is string so it won't work.

  • Related