编程语言
首页 > 编程语言> > python – 为什么这个函数不返回值?

python – 为什么这个函数不返回值?

作者:互联网

预先警告,我刚刚开始学习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作为因子.在我去之前做其他可能的因素之前,我想想出这个功能的东西

解决方法:

当你这样做

(dist/speed)/3600

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

print 3599/3600

将打印

0

因此,您需要将数据转换为浮动状态

def Convert (factor):
    speed = light*factor
    return (float(dist)/float(speed))/3600.0

标签:python,function,easygui
来源: https://codeday.me/bug/20190725/1532411.html