Xiaoyayayya
Xiaoyayayya

Reputation: 45

How to make a guess in a list of random.sample?

I even provided the answer for myself and copy it, but it shows error. This is what I have so far.

hobbies = ['basketball', 'piano', 'swimming', 'badminton', 'photography', 'gamer']

my_child = random.sample(career_path, k=1)
my_child += random.sample(hobbies, k=1)

Upvotes: 1

Views: 49

Answers (1)

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

To show a working example, I created some sample data for the career_path list. The missing piece was the if statement, where you must take the 1.st element of secret_word like this:

if guess == secret_word[1]:

And the complete code is then:

import random

career_path = ["doctor", "teacher", "author", "researcher", "athlete", "artist"]
hobbies = ["basketball", "piano", "swimming", "badminton", "photography", "gamer"]

my_child = random.sample(career_path, k=1)
my_child += random.sample(hobbies, k=1)

name = input("Please enter your name: ")
print(f"{name}'s career and hobby are {my_child}")
secret_word = my_child
guess_count = 0
guess_limit = 3
guess = ""
while guess_count < guess_limit:
    guess = input(f"Guess the hobby of {name}: ").lower()
    guess_count += 1
    if guess == secret_word[1]:
        print("You won!")
        break
    else:
        print("You guessed wrong!")

Note that instead of

random.sample(career_path, k=1)

You could also have used random.choice():

random.choice(career_path)

As they will do the same.

Upvotes: 1

Related Questions