简体   繁体   中英

Print the integers from 1 up to n (given number)

so if the function is:

function(n)

what can i do to if i want.

function(5)

to return as

1
2
3
4
5

I'm thinking towards creating an empty list, but i don't know what to append into the list to get the number 1 up to 'n'

You can try

def function(n):
    for x in range(0, n):
        print x+1

if you want to print the values, or

def function(n):
    returnlist = []
    for x in range(0, n):
        returnlist.append(x+1)
    return returnlist

to return a list.

The for x in range(0, n): part of the code is called a for loop. It repeats itself n times, and x is incremented by one each time is repeats. You can then use x to accomplish different tasks within your code. In this case, we're simply taking its value plus one and printing it or appending it to a list. We have to add one to the value because x is zero based, although it doesn't have to be. We could just as easily have written for x in range(1, n+1): and not have had to add one to the x value.

Here is a simple example:

def function(n):
    for i in range(1, n+1):
        print i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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