简体   繁体   中英

checking if a variable is an integer or not on python

I am making a maths test using tkinter. I have 4 entries to allow the user to input the answers of questions. the answers must be in integer format if not it will give a long error. I wanted my program to check if the inputted value is an integer or not.and then if it is not an integer open up a message box telling the user to check the answers.

here is my code: (it's a long code because I didn't know how to shorten it, I'm not a programmer)

from tkinter import*
from tkinter import messagebox
from random import*




n1= randint(1,6)
n2= randint(1,9)
ques1 = n1, "x", n2, "="
c1= n1*n2

n1= randint(8,15)
n2= randint(1,7)
ques2 = n1, "-", n2, "="
c2= n1-n2

n1= randint(1,10)
n2= randint(5,15)
ques3 = n1, "+", n2, "="
c3= n1+n2

n1= randint(5,12)
n2= randint(1,10)
ques4 = n1, "x", n2, "="
c4= n1*n2

#window
window = Tk()
window.geometry("280x450")
window.title("quiz")
window.configure(background='yellow')

def checkthrough():
    if ans1.get() == '':
        messagebox.showinfo("error", "check again ")
    elif ans2.get() == '':
        messagebox.showinfo("error", "check again ")
    elif ans3.get() == '':
        messagebox.showinfo("error", "check again ")
    elif ans4.get() == '':
        messagebox.showinfo("error", "check again ")
    else:
        save()
    #this is where i tried to check if it's an integer or not
    try:
        ans1 == int()
    except:
        messagebox.showinfo("error", "check again ")


def save():
    score = 0
    if c1==int(ans1.get()): 
        score= score + 1
    if c2==int(ans2.get()):
        score = score+1
    if c3==int(ans3.get()):
        score = score+1
    if c4==int(ans4.get()):
        score = score+1
    fscore.set(score)



def savetofile():
    result = result ="\n "+ namestudent.get() + "            " + fscore.get()+"/4"
    messagebox.showinfo("results", "your results been saved successfuly")
    if int(year.get())==1:
        f = open('results C1.txt', 'a')
        f.write(result)
        f.close()
    if int(year.get())==2:
        f = open('results C2.txt', 'a')
        f.write(result)
        f.close()
    if int(year.get())==3:
        f = open('results C3.txt', 'a')
        f.write(result)
        f.close()


#frame
frame = Frame(window)
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)


#variables
namestudent = StringVar()
ans1 = StringVar()
ans2 = StringVar()
ans3 = StringVar()
ans4 = StringVar()
fscore = StringVar()
year = StringVar()

#labels
name = Label(window, text = "type your name:")
name.grid(row= 6, column = 0)

yr = Label(window, text = "type your class:")
yr.grid(row= 7, column = 0)

q1 = Label(window,text = ques1, height = 3, bg = 'yellow')
q1.grid(row = 1,column=0)

q2 = Label(window,text = ques2, height = 3, bg = 'yellow')
q2.grid(row = 2,column=0)

q3 = Label(window,text = ques3, height = 3, bg = 'yellow')
q3.grid(row = 3,column=0)

q4 = Label(window,text = ques4, height = 3, bg = 'yellow')
q4.grid(row = 4,column=0)

#entrys
name_entry= Entry(window, textvariable= namestudent)
name_entry.grid(row = 6, column=1)

yr_entry= Entry(window, textvariable= year)
yr_entry.grid(row = 7, column=1)

q1_entry = Entry(window, width = 6, textvariable = ans1)
q1_entry.grid(row = 1,column=1)

q2_entry = Entry(window, width = 6, textvariable = ans2)
q2_entry.grid(row = 2,column=1)

q3_entry = Entry(window, width = 6, textvariable = ans3)
q3_entry.grid(row = 3,column=1)

q4_entry = Entry(window, width = 6, textvariable = ans4)
q4_entry.grid(row = 4,column=1)

#buttons

finish = Button(window, width = 5, text = "finish",command= checkthrough)
finish.grid(row = 5,column=0)

finalS_label = Label(window, textvariable=fscore)
finalS_label.grid(row=5, column=1)

saving = Button(window, width = 5, text = "save", command= savetofile)
saving.grid(row= 8, column=0)


window.mainloop()

I read some other post about the same question and I tried to use their answers in my code but still I'm getting the same error.

thanks.

In order to check if a string is integer-convertible, just try converting it and check for exceptions.

try:
    integer_result = int(string_result)
except ValueError:
    print("not a valid integer")
else:
    print("value is", integer_result)

To do this in your case, you want to extract the values from ans1 &c. beforehand, then pass the raw strings to int() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM