1

I am making a program that generates the phrase, "The enemy of my friend is my enemy!" actually, I want this phrase to print out a random permutation of (Friend/Enemy) in each place every time it is re-ran.

so far I got the code to print out the same word 3 times in each, but not a different word in each place.

I couldn't get python to access each string individually from a list. Any ideas?

Thanks!

`

import random

en = 'Enemy'
fr = 'Friend'
words = en, fr

for word in words:
    sentence = f"The {word} of my {word} is my {word}!"
    print(sentence)

`

2 Answers 2

2

If you want to print random sentence each time a script is run, you can use random.choices to choose 3 words randomly and str.format to format the new string. For example:

import random

en = "Enemy"
fr = "Friend"
words = en, fr

sentence = "The {} of my {} is my {}!".format(*random.choices(words, k=3))
print(sentence)

Prints (randomly):

The Enemy of my Friend is my Friend!
Sign up to request clarification or add additional context in comments.

2 Comments

The use of * for iterable unpacking might not be very beginner friendly, hence my version
@SamMason I agree, it's slightly advanced topic for beginner.
1

I'd make more changes to the code as it looks like the code in the question is trying to use the wrong tools.

import random

words = ['Enemy', 'Friend']

# three independent draws from your words
w1 = random.choice(words)
w2 = random.choice(words)
w3 = random.choice(words)

# assemble together using an f-string
sentence = f"The {w1} of my {w2} is my {w3}!"
print(sentence)

Not sure if this will be easier to understand, but hopefully!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.