简体   繁体   中英

Python Factorial Calculator Error?

So, I starting to learning Tkinter in Python, (just starting to learn Python, for that matter) and decided to try and create a factorial calculator using Tkinter. I'm not going for anything too fancy and here is what I've come up with:

from Tkinter import *
import tkMessageBox

def calculate():
    number = inputNumber.get()
    inputNumber.delete(0, END)
    product = 1
    for i in range(number):
        product = product * (i+1)
    inputNumber.insert(product)

cal = Tk()
cal.title("Factorial Calculator")
cal.geometry('450x300+200+200')

factorialNumber = IntVar()
inputNumber = Entry(cal, textvariable=factorialNumber)
inputNumber.pack()

enterButton= Button(cal, text="CALCULATE!", width=20,command=calculate)
enterButton.pack(side='bottom',padx=15,pady=15)

cal.mainloop()

So I ran this, and when I hit the "CALCULATE," button: it spits out this error:

Traceback (most recent call last):
File "C:\Python27\Lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Wesley Yu\Desktop\New folder (4)\module1.py", line 8, in calculate
for i in range(number):
TypeError: range() integer end argument expected, got str.

I've already tried fixing it, but to no avail. What should I do?

Sorry if this is very basic, still learning:)

Entries result in strings. Pass it to the int() constructor first.

>>> int('42')
42

Try this:

for i in range(int(number)):
    etc

python has a built in function for calculating factorials with the math module:

import math

i = 40      #an example number

print math.factorial(i)

It looks like you are running python 3.x, so you will be unable to use the exact code above without any modifications to it. I hope this helps.

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