Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to create a program that will take the user input for a positive integer number value and it should loop to get the total of all integers from 1 up to the entered number. 

Below is my code, but this will also take a negative number, but I don't want to, kindly help:

x=int(input("Please pick a positive integer"))

sum=0

for i in range(1,x):

    sum=sum+1

    print(sum)

else:

    x=int(input("Please pick a positive integer"))

1 Answer

0 votes
by (108k points)

See, for taking only positive numbers, you can have the if-else condition like you can only proceed with the program, when the number is positive, refer to the below code:

def intpicker():

        x=int(input("Please pick a positive integer"))

        sum=0

        if x >= 0:

            for i in range(1,x):

                sum=sum+i

            print(sum)

        else:

            return intpicker()

If you are a beginner and want to know more about Python, then do refer to the Python online course that will help you out in a better way.

Related questions

0 votes
1 answer
asked Jan 10, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Feb 14, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Dec 17, 2020 in Python by laddulakshana (16.4k points)

Browse Categories

...