简体   繁体   English

如何打印星号而不是数字?

[英]How to print a star instead of a number?

I need to write a function numbers_around(n, k) that prints the numbers smaller and larger than n in order.我需要编写一个 function numbers_around(n, k) 来按顺序打印小于和大于 n 的数字。 Instead of the number n, it should print an asterisk.它应该打印一个星号而不是数字 n。

What I've done:我做了什么:

def numbers_around(n, k):
    for n in range((n-k),(n+k+1)):
        print(n, end=' ')
    print()

numbers_around(15, 3)        
numbers_around(8, 6)        
numbers_around(27, 2)

My output:我的 output:

12 13 14 15 16 17 18 
2 3 4 5 6 7 8 9 10 11 12 13 14 
25 26 27 28 29 

The output needed: output 需要:

12 13 14 * 16 17 18 
2 3 4 5 6 7 * 9 10 11 12 13 14 
25 26 * 28 29 

You are using the same name for two variables, this is bad practice.您对两个变量使用相同的名称,这是不好的做法。 If you change one of the variable in the for loop and check if it is equal to the original number you can print out a "*" when needed like so:如果您更改 for 循环中的一个变量并检查它是否等于原始数字,您可以在需要时打印出一个“*”,如下所示:

def numbers_around(n, k):
    for i in range((n-k),(n+k+1)):
        if i == n:
            print("*", end = " ")
        else:
            print(i, end=' ')
    print()

numbers_around(15, 3)        
numbers_around(8, 6)        
numbers_around(27, 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM