How To use isdigit in python

Hello,
today i wanted to make a tkinter program and i made an entry about age the i only wanted the entry to get int numebrs for age but i did anything but it didnt work
i asked someone for help and she said that i need to use isdigit but she didnt say how to use it.
i just want to know how to use isdigit

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

UserData = []

# Screen Customize
Screen = Tk()
Screen.title("Panel")
Screen.iconbitmap("icon/icon.ico")
Screen.geometry("%dx%d+%d+%d" % (600, 300, 200, 200))
Screen.resizable(False, False)

# String Variable
name = StringVar()
family = StringVar()
age = StringVar()

# Funtions
def Clean(value):
    for item in value:
        item.set("")


def register(user):
    if int(user["age"]) > 18:
        if UserInList(user):
            messagebox.showerror("Error", "This User Was Registered")
            return False
        else:
            messagebox.showinfo("Done!", "Done!")
            UserData.append(user)
            return True
    else:
        return False
    


def RegisterClicked():
    NAME = name.get()
    FAMILY = family.get()
    AGE = age.get()

    if (NAME == "" or FAMILY == "" or AGE == ""):
        messagebox.showwarning("Warning!", "please enter all of your instructions")
        return
    
    if Age.get()
    us = {"name": NAME, "family": FAMILY, "age": AGE}
    result = register(us)


    
    if result:
        list = [name, family, age]
        InsertData(list)
        Clean(list)
        Name.focus_set()


def InsertData(value):
    tbl.insert('', "end", value=[value[0].get(), value[1].get(), value[2].get()])


def Select(value):
    Selection_row = tbl.selection()
    if Selection_row != ():
        name.set(tbl.item(Selection_row)["values"][0])
        family.set(tbl.item(Selection_row)["values"][1])
        age.set(tbl.item(Selection_row)["values"][2])


def Search(value):
    SecondList = []
    for item in UserData:
        if item["name"] == value or item["family"] == value or item["age"] == value:
            SecondList.append(item)
    return SecondList


def SearchClicked():
    query = SearchBox.get()
    result = Search(query)

    Clear()
    Load(result)



def Clear():
    for item in tbl.get_children():
        sel = (str(item),)
        tbl.delete(sel)


def Load(value):
     for item in value:
         tbl.insert('', "end", value=[item["name"], item["family"], item["age"]])



def UserInList(value):
    for item in UserData:
        if value["name"] == item["name"] and value["family"] == item["family"] and value["age"] == item["age"]:
            return True
        return False
        
        

        

# Label
Label(Screen, text="Name:", font="normal 20 bold").place(x=0, y=0)
Label(Screen, text="FamilyName:", font="normal 20 bold").place(x=0, y=50)
Label(Screen, text="Age:", font="normal 20 bold").place(x=0, y=100)

# Entry
Name = Entry(Screen)
Name.configure(width=20, textvariable=name)
Name.place(x=90, y=10)

Family = Entry(Screen)
Family.configure(width=20, textvariable=family)
Family.place(x=180, y=60)

Age = Entry(Screen)
Age.configure(width=20, textvariable=age)
Age.place(x=70, y=110)

SearchBox = Entry(Screen)
SearchBox.configure(width=20)
SearchBox.place(x=200, y=200)
# Buttons
Register = Button(Screen, text="Register")
Register.configure(font="normal 10 bold", bg="lime", command=RegisterClicked)
Register.place(x=0, y=160)

SearchButton = Button(Screen, text="Search", bg="gray", font="normal 10 bold", command=SearchClicked)
SearchButton.place(x=140, y=200)

DeleteButton = Button(Screen, text="Delete")
DeleteButton.configure(bg="red", font="normal 10 bold")
DeleteButton.place(x=140, y=240)
# Tabel
tbl = ttk.Treeview(Screen, columns="c1, c2, c3", show="headings")
tbl.bind("<Button-1>", Select)
tbl.column("# 1", width=50)
tbl.heading("# 1", text="Name")

tbl.column("# 2", width=90)
tbl.heading("# 2", text="FamilyName")

tbl.column("# 3", width=50)
tbl.heading("# 3", text="Age")
tbl.pack(side=RIGHT, fill=BOTH)
Screen.mainloop()

this is all of my code and if you didnt want to read all i can give you this summery
the summery is that i just want to say that when i clicked register button check the age box and then if we had an string give me an error with messagebox
i have register function that i want to use it in it.
i hope you can help me with this :slightly_smiling_face:

>>> str.isdigit("123")
True
>>> str.isdigit("xyz")
False

See str.isdigit().

Hi
if i want to use it in if statements what should i do?
and i wnat to use it on an entry

>>> def foo(s):
...     if str.isdigit(s):
...         print("only digits!")
...     else:
...         print("boo!")
...         
>>> foo("123")
only digits!
>>> foo("abc")
boo!

BTW, if you haven’t looked yet on the Python Tutorial, I think it’s good idea to read one.

3 Likes

It’s an instance method, so it’s more usual to use it directly on the object:

>>> "123".isdigit()
True
>>> "xyz".isdigit()
False
2 Likes

no i meant that i have an entry textbox called age box and i want to say if there is anything else there except number give me an error in messagebox.

thanks i read your instructions about it and it worked :pray: :pray: :pray:

Just a remark that this:

 def foo(s):
     if str.isdigit(s):

is better written:

 def foo(s):
     if s.isdigit():

Strings are objects, and str objects all have an isdigit() method.

That was mentioned above. But… Sometimes not, e.g.:

>>> x = object()
>>> x.isdigit()  # not nice exception from foo() function, isn't?
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    x.isdigit()
    ^^^^^^^^^
AttributeError: 'object' object has no attribute 'isdigit'
>>> str.isdigit(x)  # this better!
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    str.isdigit(x)
    ~~~~~~~~~~~^^^
TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'object' object

object != str. All strings (str) are objects but not all objects are strings.

Sorry, perhaps I should quote objected statement. It was “this […] is better”. Here is why it might be not:

>>> def spam(s):
...     return s.isdigit()
...     
>>> spam("123")
True
>>> spam("xyz")
False
>>> spam(123)  # oops
Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    spam(123)  # oops
    ~~~~^^^^^
  File "<python-input-0>", line 2, in spam
    return s.isdigit()
           ^^^^^^^^^
AttributeError: 'int' object has no attribute 'isdigit'
>>> import sys; sys.tracebacklimit=0  # lets confuse-a-cat^Wuser!
>>> spam(123)
AttributeError: 'int' object has no attribute 'isdigit'
>>> def spamspam(s):
...     return str.isdigit(s)
...     
>>> spamspam(123)  # more helpful: something is wrong with type of my argument
TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object

Of course, you could do isinstance(s, str) check an raise an appropriate error by hand.

try:
    s.isdigit()
except AttributeError:
   # Insert appropriate error message here

is a better way to handle it than checking to see if s is an str.

thanks for your help

If you want to convert user input into int then you must know that not all strings that pass str.isdigit are actually convertible to int:

>>> digit = '1²'
>>> digit.isdigit()
True
>>> int(digit)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1²'

If the objective is to convert into int then maybe EAFP-style is more suitable:

from_user = print("Please enter age: ")
try:
    age = int(from_user)
except ValueError:
    print(f"Expected integer but {from_user!r} was entered")
2 Likes