简体   繁体   English

如何在python3中跳转到随机函数

[英]How to jump to a random function in python3

i am making a python script that talks back to just for fun and i want it to pick a random subject to talk about each time here is a snippet of my code 我正在制作一个python脚本,回聊只是为了好玩,我希望它每次在我的代码段中都随机选择一个主题进行讨论

def randsub():
     rand = random.randrange(1,3)
     rand.toString()
     randsub = "sub" + rand
     randsub()

but it keeps giveing me this error TypeError: Can't convert 'int' object to str implicitly 但它一直给我这个错误TypeError:无法将'int'对象隐式转换为str

Put the functions in a list, then use the random.choice() function to pick one at random for you. 将函数放在列表中,然后使用random.choice()函数为您随机选择一个。 Functions are just objects, just like any other value in Python: 函数只是对象,就像Python中的其他任何值一样:

import random

def sub_hello():
    print('Well, hello there!')

def sub_nice_weather():
    print("Nice weather, isn't it?")

def sub_sports():
    print('What about them Broncos, eh?')

chat_functions = [sub_hello, sub_nice_weather, sub_sports]
randsub = random.choice(chat_functions)
randsub()

You got your specific error because you tried to concatenate an integer with a string ( "sub" is a string, rand an integer); 您遇到了特定的错误,因为您试图将一个整数与一个字符串连接起来( "sub"是一个字符串, rand一个整数); you'd normally convert the integer to a string first, or use a string template that supports converting other objects to strings for you (like str.format() or str % (values,) ). 您通常会先将整数转换为字符串,或者使用支持为您将其他对象转换为字符串的字符串模板(例如str.format()str % (values,) )。 But the string doesn't turn into a function, even if the string value was the same as a function name you happen to have defined. 但是,即使该字符串与您刚定义的函数名称相同,该字符串也不会变成函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM