-1

I need help or an explanation as to how I would shorten this code?

I thought about just combining the two, but when I tried, I just keep getting errors

Any ideas?

Thank You!

import random

fave_word = 'hello' + "world"

rand_num = random.randint(0,3)

if rand_num == 0:
    fave_word += ''

elif rand_num == 1:
    fave_word += 'Bob'
elif rand_num == 2:
    fave_word += 'BobBob'
elif rand_num == 3:
    fave_word += 'BobBobBob'
else:
    fave_word += ''
print(fave_word)

fave_word_2 = 'csc108' + "world"
if rand_num == 0:
    fave_word_2 += ''
elif rand_num == 1:
    fave_word_2 += 'Bob'
elif rand_num == 2:
    fave_word_2 += 'BobBob'
elif rand_num == 3:
    fave_word_2 += 'BobBobBob'
else:
    fave_word_2 += ''
print(fave_word_2)

2 Answers2

1

It looks as if you want to repeat "Bob" rand_num times. You can do it like this:

import random

fave_word = 'hello' + "world"

rand_num = random.randint(0,3)
fave_word += rand_num * "Bob"
print(fave_word)

This will print

helloworldBob

if rand_num is 1.

yogabonito
  • 657
  • 5
  • 14
0

You can use a list & indices.

Like: words = ['', 'Bob', 'BobBob', 'BobBobBob'] fave_word += words[rand_num]

We do not have much detail about the logic behind and this look quite dummy data so can't say much...

pltrdy
  • 2,069
  • 1
  • 11
  • 29