Carter
Carter

Reputation: 63

How do I create a random variable inserted to a string in python?

I am trying to insert a color out of a random choice and put it in the specific string (where the random.randint is located). When I run the code I am granted the number from the dictionary, not the color. Here is the code I have so far:

import random

def character_setup1():
    name = input("What's your name? ")
    Favorite_Color = input(f"Hi {name}, now that I know your name what is your favorite color? ")
    d = {0: "Green", 1: "Red", 2: "Blue", 3: "Purple", 4: "Yellow", 5: "Orange"}
    print(f"interesting {name}, your favorite color is {Favorite_Color} I seriously thought it would be a {random.randint(0, 5)}")


# This is temporary just to run the program
print(character_setup1())

Upvotes: 1

Views: 284

Answers (2)

Kieran Wood
Kieran Wood

Reputation: 1447

There are a few things I think are useful to mention about the sample code:

  1. It looks like you only need a list and not a dictionary for this. A list would be a bit easier to work with and would make the second part a bit easier.
  2. If you just want a random choice random has a function called choice you can use
  3. because you are printing the value in character_setup1() you don't need to also add print() around it

That being said, here is what I think you are looking for:

from random import choice # When given a list will return a random value from it

def character_setup1():
    name = input("What's your name? ")
    favourite_colour = input(f"Hi {name}, now that I know your name what is your favorite color? ")
    colours =  ["Green",  "Red",  "Blue",  "Purple",  "Yellow",  "Orange"]
    print(f"interesting {name}, your favorite color is {favourite_colour} I seriously thought it would be {choice(colours)}")


# This is temporary just to run the program
character_setup1()

Upvotes: 0

Michael
Michael

Reputation: 869

You access the value in a dictionary by using it's key.

import random

def character_setup1():
    name = input("What's your name? ")
    Favorite_Color = input(f"Hi {name}, now that I know your name what is your favorite color? ")
    d = {0: "Green", 1: "Red", 2: "Blue", 3: "Purple", 4: "Yellow", 5: "Orange"}
    print(f"interesting {name}, your favorite color is {Favorite_Color} I seriously thought it would be a {d[random.randint(0, 5)]}")


# This is temporary just to run the program
print(character_setup1())

Upvotes: 2

Related Questions