【问题标题】:Execute a function for a user defined number of times python执行用户定义次数的函数python
【发布时间】:2015-07-12 18:43:07
【问题描述】:

我有两个功能,一个要求用户输入三项,另一个要求用户输入一个数字。我想创建一个for 循环,以便第一个函数运行用户在第二个函数中输入的次数。

这是我的代码:

def get_user_input():
    name = raw_input("What is the name?")
    bas_lat = float(input("What is the latitude?"))
    bas_long = float(input("What is the longitude?"))
    print name, "has a latitude of ", bas_lat, 
    print "degrees and a longitude of ", bas_long

def get_number_stations():
    number_of_stations = float(input("How many stations are there?"))
    print "There are ", number_of_stations, 
    print "stations to have their distance from"
    print "from the headquarters determined"
    return number_of_stations

main()

【问题讨论】:

  • 如果你知道你需要一个 for 循环,你尝试了哪些没用的方法?

标签: python for-loop return user-input execute


【解决方案1】:
num = get_number_stations()

for _ in xrange(int(num)):
    get_user_input()

xrange() 需要一个 int 作为参数。你可以使用上面的代码,或者让get_number_stations() 返回一个int(这样更有意义,因为站的数量无论如何都应该是一个整数)。

【讨论】:

    【解决方案2】:

    试试这个:

    def get_user_input():
        name = raw_input("What is the name? ")
        bas_lat = float(input("What is the latitude? "))
        bas_long = float(input("What is the longitude? "))
    
        print "{} has a latitude of {} degrees and a longitude of {}.\n".format(
            name, bas_lat, bas_long
        )
    
        return name, bas_lat, bas_long
    
    
    def get_number_stations():
        number_of_stations = int(input("How many stations are there? "))
        print "There are {} stations to have their distance from the headquarters determined.\n".format(
            number_of_stations
        )
    
        return number_of_stations
    
    def main():
        stations = []
        number_of_stations = get_number_stations()
    
        for station_number in xrange(0, number_of_stations):
            (name, bas_lat, bas_long) = get_user_input()
            stations.append((name, bas_lat, bas_long))
    
        print "\nHere are the stations:"
        for station in stations:
            print "\t{}\t\t{}, {}".format(station[0], station[1], station[2])
    
    
    main()
    

    我的结果:

    How many stations are there? 2
    There are 2 stations to have their distance from the headquarters determined.
    
    What is the name? Station One
    What is the latitude? -44.3
    What is the longitude? 33.2
    Station One has a latitude of -44.3 degrees and a longitude of 33.2.
    
    What is the name? Station Two
    What is the latitude? -33.2
    What is the longitude? 11.55
    Station Two has a latitude of -33.2 degrees and a longitude of 11.55.
    
    
    Here are the stations:
        Station One     -44.3, 33.2
        Station Two     -33.2, 11.55
    

    请注意,这不考虑错误处理,并且某些输入可能不会转换为浮点数或整数。

    【讨论】:

      【解决方案3】:

      您可以返回数字并将其作为参数传递给函数,在函数中进行循环:

      def get_user_input(t):
          for _ in xrange(t):
              name = raw_input("What is the name?")
              # raw_input not input
              bas_lat = float(raw_input("What is the latitude?"))
              bas_long = float(raw_input("What is the longitude?"))
              print "{} has a latitude and longitude of ({},{})".format(name, bas_lat, bas_long)
      
      
      def get_number_stations():
          # get int to pass to range
          number_of_stations = int(raw_input("How many stations are there?"))
          print "There are {} stations to have their distance " \
                "from from the headquarters determined.".format(number_of_stations,) 
          return number_of_stations
      
      
      # get number of stations/times to loop returned from get_number_stations
      t = get_number_stations()
      # pass t to get_user_input
      get_user_input(t)
      

      你需要一个int 来表示范围,当你想要一个浮点数、整数等时,你还应该转换raw_input。不要使用input

      如果要存储数据,可以使用字典,使用名称作为键,元组作为存储坐标的值:

      def get_user_input(t):
          data = {}
          for _ in xrange(t):
              name = raw_input("What is the name?")
              bas_lat = float(raw_input("What is the latitude?"))
              bas_long = float(raw_input("What is the longitude?"))
              print "{} has a latitude and longitude of ({},{})".format(name, bas_lat, bas_long)
              data[name] = (bas_lat,bas_long)
          return data
      

      您可能还需要try/except 来捕获无法转换为浮点数的无效输入:

      def get_user_input(t):
          data = {}
          for _ in xrange(t):
              name = raw_input("What is the name?")
              while True:
                  try:
                      bas_lat = float(raw_input("What is the latitude?"))
                      bas_long = float(raw_input("What is the longitude?"))
                      print "{} has a latitude and longitude of {},{}".format(bas_lat, bas_long)g
                      # if all data was valid break
                      break
                  except ValueError:
                      # else we got data that could not be cast
                      # so print message and aska again
                      print("Invald input")
                      continue
              data[name] = (bas_lat,bas_long)
          return data
      

      将验证设为一个函数validate 可能会更好一些,它接受一个字符串作为参数和一个类型_type,它可以验证纬度和经度输入以及站数:

      def validate(s ,_type):
          while True:
              try:
                  return _type(raw_input(s))
              except ValueError:
                  print("Invalid input")
      
      
      def get_user_input(t):
          data = {}
          for _ in xrange(t):
              name = raw_input("What is the name? ")
              bas_lat = validate("What is the latitude? ", float)
              bas_long = validate("What is the longitude? ", float)
              print "{} has a latitude and longitude of ({},{})".format(name, bas_lat, bas_long)
              data[name] = (bas_lat, bas_long)
          return data
      
      
      def get_number_stations():
          number_of_stations = validate("How many stations are there? ",int)
          print "There are {} stations to have their distance " \
                "from from the headquarters determined.".format(number_of_stations)
          return number_of_stations
      
      
      
      t = get_number_stations()
      
      get_user_input(t)
      

      您可以在循环中重复调用get_user_input,但这有点毫无意义,因为您没有将任何新信息传递给get_user_input

      输出:

      How many stations are there?s
      Invalid input
      How many stations are there?2
      There are 2 stations to have their distance from from the headquarters determined.
      What is the name? foo
      What is the latitude? 0.123
      What is the longitude? 1.12s
      Invalid input
      What is the longitude? 1.345
      foo has a latitude and longitude of (0.123,1.345)
      What is the name? bar
      What is the latitude? 1.234
      What is the longitude? 2.345
      bar has a latitude and longitude of (1.234,2.345)
      

      【讨论】:

        猜你喜欢
        • 2019-08-27
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-06
        • 1970-01-01
        • 2018-04-22
        相关资源
        最近更新 更多