Home > OS >  I try to display Random Strings with random.randint or random.randstr python
I try to display Random Strings with random.randint or random.randstr python

Time:09-20

I try to make an app that is generating random questions when i press the button "ask" but i am stuck at this error..

{ return self.randrange(a, b 1) TypeError: can only concatenate str (not "int") to str }

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import random


class MyRoot(BoxLayout):

    def __init__(self):
        super(MyRoot, self).__init__()

    def generate_question(self):
        self.random_question.text = str(random.randint("Is a car a car?", "Is a color a color"))


class RandomQuestionApp(App):
    def build(self):
        return MyRoot()





randomApp = RandomQuestionApp()
RandomQuestionApp().run()



<MyRoot>:
    random_question: random_question
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Question"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_question
            text: "_"
            font_size: 30

        Button:
            text: "Ask"
            font_size: 15
            on_press: root.generate_question()


THANKS !!

CodePudding user response:

Your type error is coming from calling randint() on two string objects. If you want to randomly select from a list of strings you should first define the list and then call random.choice() on it:

def generate_question(self):
    choices = ["Is a car a car?", "Is a color a color?"]
    random_question.text = random.choice(choices)
    

This should get your desired behavior.

CodePudding user response:

Randint function can not work with string parameters. It returns you an integer from a given range. You should create a list of your question, then generate random index and access by it.

questions = ["str1", "str2", "str3"]
index = random.randint(0, len(questions))
print(question[index])     # Your random question

More about randint here

  • Related