如何通过多个函数定义运行Python代码(2.7)

时间:2016-04-18 23:18:34

标签: python-2.7

我是Python的新手,所以请尽量放轻松。我已经完成了几个小时的任务并且遇到了一个骑行障碍。基本上,我需要让Python编写一个包含多达1000个随机整数的文本文件,并让它显示max,min和用户选择的第i个数字。 (例如,如果用户输入9,则返回第9个变量)。然后,我们需要让程序将数字从最小到最大排序,并返回新的整数列表的输出。我已经成功地编写了文件,但我需要将程序分成几个函数。一个readList(infile,first)函数,一个sort(first)函数和一个main()函数,用于程序体。我在read或sort函数中不能有任何打印语句,这让我感到困惑。我试图将我的代码分成这三个函数,现在它不会运行,它不会给出任何错误消息。它确实告诉我,我的一些变量已分配但从未使用过,因为我已经在不同的函数中。它之前也告诉我,我的main()函数中缺少缩进,但我找不到它。

这是我的代码:

import random
with open("1000.txt", "w") as f:
    for x in range(1000):
        f.write(str(random.randint(0, 9999))+"\n")



def readList(infile, first):
    infile = raw_input("Please enter the file name: ")
    file_name = open(infile, 'r')
    List = file_name.readlines()
    n = int(raw_input("please enter the nth number in the list you would like to find: "))
    m = int(float(n-1))
    return List
    return m



def sortList():
    readList(infile, first)
    new_list = List.sort()
    new_min_val = new_list(min)
    new_max_val = new_list(max)
    return new_list
    return new_min_val
    return new_max_value


def main():
    readList(infile, first)
    user_num = List[m]
    first = List[0]
    lines = len(List)
    minimum_val = List(min)
    maximum_val = List(max)
    if m > 1000:
        print (m, "is greater than 1000!")
    elif m > lines:
        print ("There aren't that many numbers in the list!")
    elif lines < 1000:
        print ("WARNING: only", lines, "numbers were read into the list!")
    print (user_num)
    print (minimum_val)
    print (maximum_val)

我很抱歉这么长的帖子。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

以下是您的计划的样子。也许它可以帮助你熟悉python。它可能不完美,但至少它应该工作:)

import random
with open("1000.txt", "w") as f:
    for x in range(1000):
        f.write(str(random.randint(0, 9999))+"\n")

def readList():
    infile = raw_input("Please enter the file name: ")
    rawList = list()    
    with open(infile, 'r') as infi:
        for line in infi:
            rawList.append(int(line))
    sortedList = sortList(rawList) #function call for sorting the list, returned sorted list is stored
    n = int(raw_input("please enter the nth number in the list you would like to find: "))
    m = int(float(n-1))
    return sortedList, m

def sortList(inpList): #function needs list as input and returns sorted list
    inpList.sort() 
    return inpList

if __name__=='__main__': #This is how the main is defined in python
    sortedList, user_num = readList() #function call of readList, returned two objects are stored in variables
    first = sortedList[0] 
    lines = len(sortedList)
    minimum_val = min(sortedList)
    maximum_val = max(sortedList)
    if user_num > 1000:
        print user_num, "is greater than 1000!" # you don't need brackets when printing
    elif user_num > lines:
        print "There aren't that many numbers in the list!"
    elif lines < 1000:
        print "WARNING: only", lines, "numbers were read into the list!"
    print user_num
    print minimum_val
    print maximum_val