Build a Number Pattern Generator - Build a Number Pattern Generator

Tell us what’s happening:

I already passed the exercise, I’m just curious as to how I can make the pattern making portion “look better”. Starting with a string that already has “1” in it, making the range be (n-1), and using (num + 2) feels a bit too “brute force-y” for my liking.

Your code so far

def number_pattern(n):
    if type(n) != int:
        return "Argument must be an integer value."
    if n < 1:
        return "Argument must be an integer greater than 0."

    pattern = "1"

    for num in range(n-1):
        pattern += " " + str(num +2)

    return pattern

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 OPR/127.0.0.0

Challenge Information:

Build a Number Pattern Generator - Build a Number Pattern Generator

We have blurred this solution (with [spoiler][/spoiler] tags) so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

why don’t you use range to start from the value you want to start with? so 2, and end with n?

you may want to review about range

1 Like

Admittedly, it’s because I rewrote the code while looking at the terminal, so I adjusted on the fly haha. But I see what you mean, I forgot about adding arguments to the range to streamline it.

But am I correct in thinking that I still need to use n+1 for the range since it’s not inclusive, and so that I can avoid having to use n+1 in the for concatenation portion? So now it looks like this:


    pattern = "1"

    for num in range(2,n+1):

        pattern += " " + str(num)

Also, starting with “1“ is the only way I thought of being able to avoid having an unnecessary whitespace either at the beginning or at the end of the string, apart from having to manually remove it later on. Is there a different way that I missed?

you could add a conditional so to add the space only when needed, and not add it when not needed

1 Like

All the tests pass in the console output, but it shows I’m failing:
3. number_pattern(4) should return 1 2 3 4.

Turns out I missed the critical text return in the Objective “number_pattern(n) should “return”… I used print()because why not. :blush:

Please create your own topic when you have specific questions about your own challenge code. Only respond to another thread when you want to provide help to the original poster of the other thread or have follow up questions concerning other replies given to the original poster.

The easiest way to create a topic for help with your own solution is to click the Ask for Help button located on each challenge. This will automatically import your code in a readable format and pull in the challenge url while still allowing you to ask any question about the challenge or your code.

Thank you.