using functions to display numbers in a list

后端 未结 4 1132
面向向阳花
面向向阳花 2021-01-29 14:09

I have a list of numbers and I have to use a function to display them in celsius, they are in fahrenheit now.

nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,         


        
4条回答
  •  南旧
    南旧 (楼主)
    2021-01-29 14:47

    The simplest way would be to use a for loop to iterate over the list and printing each result:

    #!/usr/bin/env python
    
    # def farentoCel(x): ...
    # ...
    
    if __name__ == '__main__':
        import sys
    
        for each_num in sys.argv[1:]:
            print farentoCel(int(each_num))
    

    As others have said you can replace this explicit loop with a list comprehension (expression), or even a generator comprehension (in newer versions of Python).

    In this case I'm showing a very simple skeleton for you to use for testing simple functions. The if _ name _ == '_ main _': suite is a Python convention used to separate your function, class, and other definitions from the run-time of your code. This can be used to structure your code so that it can be re-used in (imported into) other code while also exposing some functionality in a command line utility (wrapper) or providing a default interface (perhaps a GUI).

    In the fairly common case where your module doesn't have simply accessible utility (where it's only useful when incorporated into other code) then you can use the '_ main _' suite to contain unit test cases.

提交回复
热议问题