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.
Related
Here is code
equation1 = input("Please Enter an equation")
a = float(input("For a = "))
c = eval(equation1)
When I am typing equation with cos, tan, sin and ln functions; i.e : a*cos(a)
I am getting this error:
c = eval(equation1)
File "<string>", line 1, in <module>
TypeError: cos() takes exactly one argument (0 given)
and inputs like a*cos(90), a**2+cos(90) are working fine, my application is build to be generic. user can give any value is there any way to fix it?
First it needs to have from math import cos.
When I run with PyCharm, I get the same exception as you.
Then I added print(equation1) and found that when I typed cos(a), printed cos().
At first I thought there was something wrong with the input function, but I couldn't find the reason.
Then I ran it directly from the terminal command line using python xx.py and it worked fine.
So it may be that the PyCharm window does not recognize the contents of the parentheses.
I'm currently working on my homework and the first line code is provided and cannot be changed. I am able to run in PyCharm but not able to run in Hackerrank to submit my homework.
I have tried to find what's wrong with my code but I think the problem is related to input. I think teacher wants us to use input as variable?
def check_character_type(input):
# Write your code
ch = input
if ch[0].isalpha():
print("alphabet")
elif ch[0].isdigit():
print("digit")
else:
print("special")
return ch
check_character_type(input)
When I run the code in Hackerrank, error message are
Traceback (most recent call last):
File "Solution.py", line 29, in <module>
check_character_type(input)
File "Solution.py", line 21, in check_character_type
if ch[0].isalpha():
TypeError: 'builtin_function_or_method' object is not subscriptable
your issue as mentioned in the last answer and comments it that you are using the function named input as the name of your variable...try it like this:
inp = 'test'
def check_character_type(inp):
# Write your code
ch = inp
if ch[0].isalpha():
print("alphabet")
elif ch[0].isdigit():
print("digit")
else:
print("special")
return ch
check_character_type(inp)
output:
alphabet
'test'
if by "I think teacher wants us to use input as variable" you mean that you're supposed to provide input before hand, then do this first:
inp = input('Enter the input')
The issue here is you have named the parameter to your function input, which is a reserved function provided by Python used to read input from the STDIN. You then alias this to ch and attempt to subscript it, effectively trying to access an index of a function (which you can't).
The solution would be to change your parameter name from input to something like in or s instead, something that isn't a reserved keyword.
Getting a traceback error as follows:
Traceback (most recent call last):
File "F:\Python Codes\Falling Distance\hodge_Lab5b.py", line 12, in <module>
main()
File "F:\Python Codes\Falling Distance\hodge_Lab5b.py", line 9, in main
print(get_time, '\t', format(falling_distance, '.2f'))
TypeError: unsupported format string passed to function.__format__
#file 1 named hodge_Lab5b.py
def main():
from falling_distance import falling_distance
get_time = int(input("Enter the time, in seconds, the object has been falling: "))
print("Time",'\t' "Distance")
print("--------------------------")
for get_time in range (1,11):
print(get_time, '\t', format(falling_distance(main), '.2f'))
return get_time
main()
#File 2 named falling_distance.py
def falling_distance(main):
gravity = 9.8
fallingTime = main()
distance = (1/2)*gravity*(fallingTime**2)
return distance
Cannot figure out how to get these to work together. I do not know what I have done wrong. I have read through the relevant parts on the book several times. I feel like I am overlooking something rather simple and it is just not jumping out at me.
string formatting
old python: '%s %s' % ('one', 'two')
new python: '{} {}'.format('one', 'two')
also
for get_time in range(1,11): will iterate over 1,2,3...10
you probably want to do sth like this
for sec_nb in range(1, get_time+1):
print('falling time: {} \t falling dist: {}'.format(sec_nb, falling_distance(sec_nb)))
btw you want to pass number to falling_distance function, not a function
It seems like you have a few issues here. Since it's homework, I'm reluctant to provide any code. Here are a couple of issues that I see:
Naming. You're passing the function named main into the function called falling_distance. This is probably not what you want to do (definitely not with the provided code). If you carefully rename everything, I'm guessing most of the problems will go away with some extra debugging.
Inside calling_distance, you're again calling the function main which would seem to put you in an infinite loop. This is related to issue #1, but know that you'll need to revise how you're using the passed parameter in falling distance
If you're using python 2, I think you'll run into printing problems when printing out the table results
get_time is being reassigned in the for loop, which does not seem to be intended. You'll want to replace this with a new variable here
If you're using python 2, I expect that your falling_distance function will always return 0. This is because (1/2) is going to be interpreted as 0 (due to integer division). You should instead have the division happen last, once you know the numerator.
I see a few other issues as well, plus there are some style and convention issues that are more important long term.
Good luck
This is what I finally found to work. Thanks for your help.
#file 1
def main():
print( "Time\tFalling Distance\n-----------------------" )
from falling_distance import fallingDistance
for currentTime in range(1,11):
print(currentTime, "\t", format(fallingDistance(currentTime),\
".2f"))
main()
#file 2
def fallingDistance(fallingTime):
gravity=9.8
distance=(1/2)*gravity*(fallingTime**2)
return distance
Was certainly naming issues that caused a lot of the problems.
Thank you for your help!
I'm currently writing a python script which plots a numpy matrix containing some data (which I'm not having any difficulty computing). For complicated reasons having to do with how I'm creating that data, I have to go through terminal. I've done problems like this a million times in Spyder using imshow(). So, I thought I'd try to do the same in terminal. Here's my code:
from numpy import *
from matplotlib import *
def make_picture():
f = open("DATA2.txt")
arr = zeros((200, 200))
l = f.readlines()
for i in l:
j = i[:-1]
k = j.split(" ")
arr[int(k[0])][int(k[1])] = float(k[2])
f.close()
imshow(arr)
make_picture()
Suffice it to say, the array stuff works just fine. I've tested it, and it extracts the data perfectly well. So, I've got this 200 by 200 array of numbers floating around my RAM and I'd like to display it. When I run this code in Spyder, I get exactly what I expected. However, when I run this code in Terminal, I get an error message:
Traceback (most recent call last):
File "DATAmine.py", line 15, in <module>
make_picture()
File "DATAmine.py", line 13, in make_picture
imshow(arr)
NameError: global name 'imshow' is not defined
(My program's called DATAmine.py) What's the deal here? Is there something else I should be importing? I know I had to configure my Spyder paths, so I wonder if I don't have access to those paths or something. Any suggestions would be greatly appreciated. Thanks!
P.S. Perhaps I should mention I'm using Ubuntu. Don't know if that's relevant.
To make your life easier you can use
from pylab import *
This will import the full pylab package, which includes matplotlib and numpy.
Cheers
I have a problem with using DLL function in python.
I looked the name of function by dint of "dumpbin".
For example
_xGraphics3D#20
I tried to call the function like this:
from ctypes import *
xorsLib = cdll.LoadLibrary("Xors3D.dll")
width = c_int(800)
height = c_int(600)
depth = c_int(32)
mode = c_int(0)
vsync = c_int(0)
xGraphics3D = getattr(xorsLib,"_xGraphics3D#20")
xGraphics3D(width, height, depth, mode, vsync)
but it's cause the error:
Traceback (most recent call last):
File "D:/Coding/Python/pyASG/main", line 11, in <module>
xGraphics3D(width, height, depth, mode, vsync)
ValueError: Procedure called with not enough arguments (20 bytes missing) or wrong calling convention
what am i doing wrong?
p.s. i haven't know python, but i learn it. i read ctype-manual and tried to find answer...
p.p.s sorry for my awful english.
Try use windll instead of cdll.
xorsLib = windll.LoadLibrary("xors3d.dll")
http://docs.python.org/release/3.1.5/library/ctypes.html
The reason is the same as martineau commented.