mardi 24 janvier 2017

Python 3: How to shorten list of "if" and "elif" statements?

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)

Aucun commentaire:

Enregistrer un commentaire