Home > database >  Defining a function that will interpret whether or not an answer has been input and give out a rando
Defining a function that will interpret whether or not an answer has been input and give out a rando

Time:04-25

So here is the code in question. The error I get when I run the code is File "D:\obj\windows-release\37amd64_Release\msi_python\zip_amd64\random.py", line 259, in choice

TypeError: object of type 'type' has no len()

import random
import tkinter as tk
from tkinter import messagebox

root=tk.Tk()
root.title("Tragic 8 Ball")

def get_answer(entry, list):
    if (entry.get() != ""):
        messagebox.showwarning("Please ask question.")
    else: (entry.get() == "")
    messagebox.showwarning("Your answer", random.choice(list))
    
entry=tk.Entry(width=40)
entry.focus_set()
entry.grid()

get_answer(entry, list)

tk.Label(root, text="Ask a question:").grid(row=0)
tk.Button(root, text="Answer my question", command=get_answer(entry, list).grid(row=3), columd=0, sticky=tk.W, pady=4)

list=["It is certain.",
      "Outlook good.",
      "You may rely on it",
      "Ask again later.",
      "Concentrate and ask again.",
      "Reply hazy, try again.",
      "My reply is no.",
      "My sources say no."]

root.mainloop()
'''

CodePudding user response:

The error occurred due to this block:

def get_answer(entry, list):
    if (entry.get() != ""):
        messagebox.showwarning("Please ask question.")
    else: (entry.get() == "")
    messagebox.showwarning("Your answer", random.choice(list))

Here the name of the list is list. So when no list variable is found, on passing list it passes the type as an argument. And type type has no length. This is why naming variables same as in-built functions should be avoided.
So, you need to declare the list before

get_answer(entry, list)

CodePudding user response:

There are two related things here, one is a syntactical error and one is something that, while not an error, is at least bad coding practice.

The error is that your line get_answer(entry, list) passes an argument list to a function before that variable list has been defined. That makes the interpreter assume that list refers not to a variable but to lists as a data type in Python - and such data types have no length (which are necessary for the purposes of random functions), they're simply type objects. Solution: Have the definition of list before that variable name is first used.

The bad practice is that you named your list list. You're allowed to do that (because "list" is not a reserved word in Python), but it's not a good idea because it lends itself to all sorts of confusion (of which your problem is only one example). Better style would be to rename the list to something more descriptive, such as list_of_answers or something like that.

  • Related