Home > Mobile >  Asking user to input a category to import file
Asking user to input a category to import file

Time:06-04

How can I ask a user to give input, so that I can import a random word from the list? I have multiple lists ( for eg. people, place, animal, thing) so I want the user to input one of these categories to import a random word from these categories. I can make one list but can't understand for multiple lists

My code for 1 list

import random
from words import word_list

def get_word():
    word = random.choice(word_list)
    return word.upper()

CodePudding user response:

You can use the raw_input function. For example,

category=raw_input('Select a category (people, place, animal, thing):')
word = random.choice(category)

CodePudding user response:

category = input("Enter category: ")

This will set the category Variable to the user input. How youre gonna filter for a specific category will depend on the syntax of your words-library

CodePudding user response:

You can use input() to get input from the user. Then you can simply use a if/else statement to return a word from the selected category. Similar to this:

import random

people = ['ada', 'frank']
animals = ['elephant', 'giraffe']
places = ['new york', 'tokyo']
things = ['phone', 'computer']

def get_word():
    category = input('please enter a category:\n')
    if category == 'people':
        return random.choice(people).upper()
    elif category == 'places':
        return random.choice(places).upper()
    elif category == 'animals':
        return random.choice(animals).upper()
    elif category == 'things':
        return random.choice(things).upper()

word = get_word()
print(word)
  • Related