Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3:如何缩短;如果;及;以英语发言;声明?_Python_Python 3.x_If Statement - Fatal编程技术网

Python 3:如何缩短;如果;及;以英语发言;声明?

Python 3:如何缩短;如果;及;以英语发言;声明?,python,python-3.x,if-statement,Python,Python 3.x,If Statement,我需要关于如何缩短此代码的帮助或解释 我想把两者结合起来,但当我尝试时,我总是会出错 有什么想法吗 谢谢大家! 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

我需要关于如何缩短此代码的帮助或解释

我想把两者结合起来,但当我尝试时,我总是会出错

有什么想法吗

谢谢大家!

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)

看起来好像您要重复“Bob”
rand_num
次。您可以这样做:

import random

fave_word = 'hello' + "world"

rand_num = random.randint(0,3)
fave_word += rand_num * "Bob"
print(fave_word)
这会打印出来

helloworldBob

如果
rand_num
为1。

可以使用列表和索引

比如:

单词=[''‘鲍勃’、‘鲍勃’、‘鲍勃’、‘鲍勃’]
fave_word+=单词[rand_num]


我们没有太多关于背后逻辑的细节,而且这些数据看起来相当虚假,因此不能说太多…

使用字典根据索引添加文本。