Python中如何将一个函数内定义的变量传递给另一个独立函数
彩票生成器参数传递问题
背景
我确信这个问题在其他地方已有提问,但我目前找到的相关主题都比我现在做的内容更复杂,只会让我更困惑。我是Python入门课程的学生,正在完成一个“彩票号码”作业,基础要求是随机生成7位彩票号码并打印输出。
基础要求我已经掌握,但我不想只按字面要求完成,想做得更实用:也就是让用户自定义需要生成的号码数量、可选号码的取值范围,再由程序生成符合用户设定标准的随机号码。
我的讲师要求所有逻辑都要在函数内实现,所以我计划按如下结构开发:
实现思路
main()函数:作为程序入口调度所有逻辑get_info()函数:收集用户输入的参数,包括号码数量MaxDigits、取值范围最小值MinChoice、取值范围最大值MaxChoicelottery_pick()函数:接收上述参数,完成彩票号码生成逻辑
问题描述
目前代码可以运行,但我只能把lottery_pick() 函数定义在get_info() 函数内部才能调用执行。我想知道有没有方法可以将两个函数独立定义,只把get_info() 中生成的变量传递给lottery_pick() 即可。
原始代码
import random # Define the main function def main(): get_info() exit_prompt() def get_info(): # Set Variables to 0 MaxDigits = 0 # Let the user know what we are doing print("Let's choose your lottery numbers!") print("First, How many numbers do you need for this lottery?") # Request the user input the number of lottery numbers we need while True: try: MaxDigits = int(input('Please enter how many numbers you need to choose: ')) if MaxDigits > 0: break; else: print('Please enter an integer for how many numbers are being drawn. ') except: continue print('Next, we need to know the smallest and largest numbers allowed to choose from') # Request user input smallest number in range of numbers to pick from. while True: try: MinChoice = int(input('Please enter the lowest number you are allowed to choose from: ')) if MinChoice >= 0: break; else: print ('Please enter an integer, 0 or greater for the smallest number to pick from.') except: continue # Request user input largest number in range of numbers to pick from. while True: try: MaxChoice = int(input('Please enter the largest number you are allowed to choose from: ')) if MaxChoice >= 0: break; else: print ('Please enter an integer, 0 or greater for the greatest number to pick from.') except: continue # Define the function to actually assemble the lottery number def lottery_pick(lot_digits, lot_min, lot_max): numbers = [0] * lot_digits for index in range(lot_digits): numbers[index] = random.randint (lot_min, lot_max) print('Here are your lottery numbers!:') print(numbers) # Execute the function - I've not yet figured out how to pass the variables from the get_info # function to the lottery_pick function without lottery_pick being inside of get_info. lottery_pick(MaxDigits, MinChoice, MaxChoice) def exit_prompt(): while True: try: # use lower method to convert all strings input to lower-case. This method # allows user to input their answer in any case or combination of cases. ExitPrompt = str.lower(input('Would you like to generate another lottery number? Please enter "yes" or "no" ')) if ExitPrompt == 'yes': main() elif ExitPrompt =='no': print('Goodbye!') exit() # If an answer other than yes or no is input, prompt the user again to choose to re-run or to exit # until an acceptable answer is provided. else: print('Please enter "yes" to generate another lottery number, or "no" to exit. ') except: continue main()
修改方案
核心调整点
- 将
lottery_pick()函数从get_info()内部移出,作为独立的顶层函数定义 - 改造
get_info(),收集完三个参数后直接返回这三个值 - 在
main()函数中接收get_info()的返回值,再传递给lottery_pick()执行
修改后完整代码(已汉化交互提示)
import random # 独立定义的彩票生成函数 def lottery_pick(lot_digits, lot_min, lot_max): numbers = [random.randint(lot_min, lot_max) for _ in range(lot_digits)] print('您的彩票号码如下:') print(numbers) def main(): # 接收get_info返回的三个参数 max_digits, min_choice, max_choice = get_info() # 传递参数给独立的lottery_pick函数 lottery_pick(max_digits, min_choice, max_choice) exit_prompt() def get_info(): max_digits = 0 print("欢迎使用彩票号码生成器!") print("第一步,请输入需要生成的号码位数:") while True: try: max_digits = int(input('请输入需要生成的号码个数:')) if max_digits > 0: break else: print('请输入大于0的正整数') except: print('输入无效,请输入正整数') continue print('第二步,请输入可选号码的取值范围') while True: try: min_choice = int(input('请输入取值范围的最小值:')) if min_choice >= 0: break else: print('请输入大于等于0的整数作为最小值') except: print('输入无效,请输入整数') continue while True: try: max_choice = int(input('请输入取值范围的最大值:')) if max_choice >= 0 and max_choice > min_choice: break elif max_choice <= min_choice: print('最大值必须大于你输入的最小值,请重新输入') else: print('请输入大于等于0的整数作为最大值') except: print('输入无效,请输入整数') continue # 收集完所有参数后直接返回 return max_digits, min_choice, max_choice def exit_prompt(): while True: try: exit_prompt_val = input('是否需要重新生成号码?请输入“是”或“否”:').lower() if exit_prompt_val == '是': main() elif exit_prompt_val == '否': print('再见!') exit() else: print('输入无效,请输入“是”重新生成,或输入“否”退出程序') except: continue if __name__ == "__main__": main()
补充说明
修改后额外增加了最大值必须大于最小值的校验,避免用户输入无效的取值范围。同时将原来的列表赋值写法改成了更简洁的列表推导式写法,功能完全一致,更符合Python的常用写法。
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

