在Python中操作变量

时间:2014-02-21 22:51:22

标签: python algorithm variables

from math import *
from graphics import *
from time import *

def main():

    veloc = .5  #horizontal velocity (pixels per second)
    amp = 50 #sine wave amplitude (pixels)
    freq = .01  #oscillations per second

    #Set up a graphics window:
    win = GraphWin("Good Sine Waves",400,200)
    win.setCoords(0.0, -100.0, 200.0, 100.0)

   #Draw a line for the x-axis:
   p1 = Point(0,0)
   p2 = Point(200,0)
   xAxis = Line(p1,p2)
   xAxis.draw(win)

   #Draw a ball that follows a sine wave
    for time in range(1000):
       amp = amp * 2
       x = time*veloc
       y = amp*sin(freq*time*2*pi)
       #y = abs(amp*sin(freq*time*2*pi))
       ball = Circle(Point(x,y),2)
       ball.draw(win)
       sleep(0.1)  #Needed so that animation runs slowly enough to be seen

#win.getMouse()
#win.close()                
main()

我遇到的问题是尝试在for循环内缓慢减小放大器变量。 amp变量设置为50.我知道为了减少它应该是这样的:

amp = amp
amp = amp / 2

但每次我在for循环中尝试这些语句都不起作用。

2 个答案:

答案 0 :(得分:1)

for i in range(0,10):
    amp= amp/2

打印

25.0
12.5
6.25
3.125
1.5625
0.78125
0.390625
0.1953125
0.09765625
0.048828125
>>> 

答案 1 :(得分:0)

更改

for time in range(1000):
   amp = amp * 2                       #this line multiplies
   x = time*veloc
   y = amp*sin(freq*time*2*pi)
   #y = abs(amp*sin(freq*time*2*pi))
   ball = Circle(Point(x,y),2)
   ball.draw(win)
   sleep(0.1)

为:

for time in range(1000):
   amp /= 2                             #this line now divides
   x = time*veloc
   y = amp*sin(freq*time*2*pi)
   #y = abs(amp*sin(freq*time*2*pi))
   ball = Circle(Point(x,y),2)
   ball.draw(win)
   sleep(0.1)