3

请注意,我刚开始学习 Python,这是我第一次来这个网站。如果我表现得像个 n00b,请不要讨厌。

所以我创建了一个程序,它应该告诉你以光速到达恒星(指定距离)需要多长时间,以及光速因素。它从一个名为 easygui 的库开始,它创建了一个漂亮的窗口,用户可以选择一个因素。他们选择的因素成为变量“选择”。这部分代码工作正常。理想情况下,该值将被输入到一个函数中,该函数将进行因式分解,并返回一个旅行天数的值。这是不成功的。很可能,我只是把它设置错了,所以如果有人知道使用函数的正确方法,我真的很感谢你的帮助!哦,我试着像疯了一样发表评论,所以希望一切都有意义!

import easygui as eg                #the gui creation library I am using

dist  = 41000000000000          #distance to the star
light = 300000                  #speed of light


def Convert (factor):           #takes in factor chosen by user
    speed = light*factor        #the speed is the factor multiplied by the speed of light
    time = (dist/speed)/3600    # the time is the distance/divided by the speed, since thats a huge value in seconds, the /3600 should reduce it to days
    return time                 #"should" return the value it got for "time"


msg     = "Choose a warp factor:"                   #creates a gui  window for user to select factor
title   = "Warp Factor Selection"
choices = ["1", "3", "5", "10", "50", "100", "200", "500", "1000"]
choice   = eg.buttonbox(msg, title, choices)        #gui returns the user's selection as "choice" WORKS!

choice = float(choice)                                      #changes choice to float

if choice == 1:
    Convert(choice)                                         #attempts to feed  "choice" into the function "convert" DOES NOT WORK :(
    print (Convert(1))                                      #then print the value created from convert (have also tried print(time) but it always returns 0)

此时,有意设置为仅接受选择 1 作为因子。我想在我去做其他可能的因素之前弄清楚这个功能

4

3 回答 3

5

thefourtheye 已经解释了原因,但是如果您想在将来避免这种情况,您可以通过将其放在文件顶部来切换到 Python 3 分区:

from __future__ import division

在 Python 3 中,它在 ( ) 这样的情况下表现得更直观,1/2 == .5而您仍然可以使用//( 1//2 == 0)获得整数除法行为

于 2013-11-17T06:47:20.033 回答
2

当你这样做

(dist/speed)/3600

如果(dist/speed)小于 3600,则结果将为 0。您可以自己尝试一下,

print 3599/3600

将打印

0

因此,您需要像这样将数据转换为浮动

def Convert (factor):
    speed = light*factor
    return (float(dist)/float(speed))/3600.0
于 2013-11-17T06:38:34.860 回答
1

你可能想这样做

if str(choice) in choices:
    Convert(choice)
    print (Convert(choice))

这样,您不必创建新的 if 条件来测试每个数字。这只是说如果choicechoices列表中,则使用choice.

于 2013-11-17T06:38:16.970 回答