如何根据风速在蟒蛇中分配飓风的类别

时间:2017-02-26 19:50:53

标签: python

您好我正在尝试编写一个程序,计算机将随机生成一个风速,风暴潮为飓风。到目前为止它将随机生成这两件事。但现在我无法弄清楚如何将函数wind中的可变风速回调到函数类别中,以使用随机生成的风速来定义它的类别。但是,当我运行该程序时,它将打印风速和风暴潮,但是当它打印类别时,它不打印它与风速相关。这是我的代码。

import os
import sys
import random
import math 
import time

def wind():
    windspeed = randrange(74, 157)
    print "The Hurricanes wind speed is"
    time.sleep(2)
    print windspeed

def stormsurge():
    surgeamount = randrange(3, 19)
    print "The Hurricanes storm storm surge is"
    time.sleep(2)
    print surgeamount

def category():
    categorys = [1, 2, 3, 4, 5]
    for windspeed in range(74, 95):
        print categorys[0]
   else:
       for windspeed in range(96, 110):
           print categorys[1]

wind()
stormsurge()
category()

当我跑的时候,我得到了。     After running it

2 个答案:

答案 0 :(得分:0)

def wind():
    windspeed = randrange(74, 157)
    print "The Hurricanes wind speed is"
    time.sleep(2)
    print windspeed

此功能有效地打印范围内的随机数(74,157)。如果您希望能够使用该数字,则必须返回一个值:

def wind():
    return randrange(74, 157)

然后调用函数可以完成它对该结果所需的操作 - 可能,它首先将它保存到某个变量,然后它可以打印该值或计算类别或类似的东西。

如果你想根据某个数字计算一个类别,最明显的方法就是如下:

def category(windspeed):
  # based on http://www.nhc.noaa.gov/aboutsshws.php
  if windspeed < 74:
    return 0 
  elif 75 <= windspeed < 96:
    return 1 
  if 96 <= windspeed < 111:
    return 2
  elif 111 <= windspeed < 120:
    return 3
  elif 130 <= windspeed < 157:
    return 4
  else: 
    return 5

您的代码如下所示:

windspeed = wind()
hurricane_category = category(windspeed)
print "The windspeed is %d and the category is %d" % (
  windspeed, hurricane_category)

答案 1 :(得分:-1)

您可以使用以下内容:

import os
import sys
import random
import math 

def wind():
   windspeed = random.randrange(74, 157)
   print "The Hurricanes wind speed is", windspeed
   return windspeed

def stormsurge():
   surgeamount = random.randrange(3, 19)
   print "The Hurricanes storm storm surge is", surgeamount
   return surgeamount

def category(windspeed, surgeamount):
   categorys = [1, 2, 3, 4, 5]
   for _windspeed in range(74, 95):
         if _windspeed == windspeed:
            print "Storm category is", categorys[0]
            break
   else:
      for _windspeed in range(96, 157):
         if _windspeed == windspeed:
            print "Storm category is", categorys[1]

windspeed = wind()
surgeamount = stormsurge()
category(windspeed, surgeamount)

甚至更简单:

import os
import sys
import random
import math 

def wind():
   windspeed = random.randrange(74, 157)
   print "The Hurricanes wind speed is", windspeed
   return windspeed

def stormsurge():
   surgeamount = random.randrange(3, 19)
   print "The Hurricanes storm storm surge is", surgeamount
   return surgeamount

def category(windspeed, surgeamount):
   categorys = [1, 2, 3, 4, 5]
   if windspeed in range(74, 95):
      print "Storm category is", categorys[0]
   else:
      print "Storm category is", categorys[1]

windspeed = wind()
surgeamount = stormsurge()
category(windspeed, surgeamount)

不要忘记使用函数返回值')