如果某些条件是m,则打印消息而不是数字

2024-05-19 03:02:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要建立一个程序,打印1到n之间的所有数字,如果我们有一个数字可以被7整除打印“boom!”如果数字的数字是7,则打印“boom!”相反,如果两个都打印了繁荣!。例如,对于n=18:

1
2
3
4
5
6
boom-boom!
8
9
10
11
12
13
boom!
15
16
boom!
18

这就是我目前所做的,我几乎没有编码经验,所以我一定是做错了什么:

^{pr2}$

模运算正常,但字符串检查不起作用。我试着在没有模数部分的情况下运行它,只得到正常的1到100打印。在


Tags: 字符串程序编码情况数字经验boom模数
2条回答

试试这个:

n = 100
for i in xrange(1, n + 1):
    s = str(i)
    if "7" in s and i % 7 == 0:
        print "boom-boom!"
    elif "7" in s or i % 7 == 0:
        print "boom!"
    else:
        print i

如果你不熟悉编码,一个好主意就是用一种简单的“伪代码”语言写下你的算法。这样你就不会被奇怪的名字和函数淹没了。如果我没弄错的话,你在找这样的东西:

for each *number* in the range [1,100] do:
    if *number* is divisible by 7 and contains the number 7 then print "boom-boom!"
    else if *number* has digit 7 in it or is divisible by 7, then print "boom!"
    else print *number*

现在你要做的就是把这个算法翻译成python,realli已经把我打败了;)

相关问题 更多 >

    热门问题