如何在if循环中获取字符串变量以进行更改和打印

时间:2012-10-09 15:08:28

标签: python string variables if-statement range

b=int(1)

if b == 1:
     b=2
     c = "on my thumb"
elif b== 2:
    b=3
    c = "on my shoe"
elif b== 3:
    b=4
    c = "on my knee"
elif b== 4:
    b+1
    c = "on my door"
elif b== 5:
    b+1
    c = "on my hive"
elif b== 6:
    b+1
    c = "on my sticks"
elif b== 7:
    b+1
    c = "up in heaven"
elif b== 8:
    b+1
    c = "on my gate"
elif b== 9:
    b+1
    c = "on my spine"
else:
    c = "once again"

for r in range(10):
    print("This old man, he played one He played knick-knack " + c +" Knick-knack paddywhack, give your dog a bone This old man came rolling home")
    b+1

相对较新的编码,所以我真的不知道我在做什么,但我试图让c改变r打印的每一个新时间......这样IT就完成了旧的童谣。我在python编写这个...

3 个答案:

答案 0 :(得分:4)

parts = ["on my thumb", "on my shoe", ...]
numerators = ["one", "two", "three", ...]

for num, part in zip(numerators, parts):
    print "This old man, he played " + num
    print "He played knick-knack " + part
    print "Knick-knack paddywhack, give your dog a bone"
    print "This old man came rolling home"

答案 1 :(得分:0)

只需将字符串存储在数组或列表中

lines = ["on my thumb", "on my shoe", "...."....]

然后在for循环的帮助下迭代该数组(或列表) 在c#-ish语法中:

foreach(line in lines)
{
  print("bla" + line + "blubb");
}

答案 2 :(得分:0)

也许是这样的:

string b[10] = {"on my thumb","on my shoe","on my knee","on my door","on my hive","on my sticks","up in heaven","on my gate","on my spine","once again"};

for (i=0; i<b.length; i++) {
   print("This old man, he played one He played knick-knack " + b[i] +" Knick-knack paddywhack, give your dog a bone This old man came rolling home.\n");
}

由于这些值不会改变,您可以创建一个静态数组来保存值,然后您可以在显示结果时循环显示内容。