有没有合理的方法将我的while
循环转换为for
循环?我试图创建这个,但我从来没有走得太远,因为range
和/或xrange
已经破坏,因为数字太大或者他们没有float
。这是我想要查看的while
循环,如果有一个合理的for
循环转换(这是在函数内是为什么它缩进):
a = float(E1.get())
b = (a + 1)
c = sqrt(b)
e = sqrt(a)
f = (unichr(0x221A))
fractional, integral = modf(c)
while integral == integral:
fractional1, integral1 = modf(a / (integral**2))
print(fractional1)
if fractional1 != 0:
integral -= 1
continue
else: break
如果可以range
或xrange
,则必须为range(1,a+1)
或xrange(1,a+1)
这是我的全部代码:
def radical():
# Define variables needed
a = float(E1.get())
b = (a + 1)
c = sqrt(b)
e = sqrt(a)
f = (unichr(0x221A))
fractional, integral = modf(c)
while integral == integral:
fractional1, integral1 = modf(a / (integral**2))
print(fractional1)
if fractional1 != 0:
integral -= 1
continue
else: break
d = (a / (integral**2))
# make pointless floats integers
if integral.is_integer():
integral = int(integral)
if d.is_integer():
d = int(d)
if e.is_integer():
e = int(e)
# set conditions for output
if d == 1:
global master
master = Tkinter.Tk()
w = Tkinter.Message(master, padx=5, pady=5,text=(integral)).grid(ipadx=5, ipady=5)
master.title("Square Root")
master.mainloop()
elif integral == 1:
master = Tkinter.Tk()
w = Tkinter.Message(master, padx=5, pady=5,text=(f,d,"or",e)).grid(ipadx=5, ipady=5)
master.title("Simplified Radical")
master.mainloop()
else:
master = Tkinter.Tk()
w = Tkinter.Message(master, padx=5, pady=5,text=(integral,f,d,"or",e)).grid(ipadx=5, ipady=5)
master.title("Simplified Radical")
master.mainloop()
答案 0 :(得分:0)
如果你想要无限循环,你可以使用无限产生的itertools.repeat(1)
:
import itertools
....
for _ in itertools.repeat(1): # instead of `while integral == integral`
...
您还可以使用itertools.count()
或itertools.cycle([1])
。
<强>更新强>
使用range(integral, 0, -1)
,您可以从integral
向下迭代到1
(不包括0)。
for integral in range(integral, 0, -1): # xrange if you're using Python 2.x
fractional1, integral1 = modf(a / (integral**2))
print(fractional1)