4 Replies - 20661 Views - Last Post: 20 September 2016 - 10:59 AM Rate Topic: -----

#1 MitchCochran55   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-September 16

I need a exception that won't allow negative numbers

Posted 19 September 2016 - 09:35 PM

Hello!

I am having a really tough time trying to add an an exception that will not allow users to input 0 and negative numbers. Can someone please point me in the right direction?
The Program writes random values according to the user's input of how many random variables they want.

Here is what I have so far:

import random



rand_write= open("randomnum.txt", "w")

while(True):
    
    try:
        for i in range(int(input('How many random numbers would you like to generate?:  '))):
            line = str(random.randint(1,999)) +"\n"
            rand_write.write(line)
            print(line)
        
    except ValueError:
            print()
            print('PLEASE ENTER NUMERICAL VALUE ONLY')
            print()

    else:
        break


rand_write.close()



This post has been edited by Atli: 19 September 2016 - 09:50 PM
Reason for edit:: Fixed the code tags.


Is This A Good Question/Topic? 0
  • +

Replies To: I need a exception that won't allow negative numbers

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5612
  • View blog
  • Posts: 14,686
  • Joined: 18-April 07

Re: I need a exception that won't allow negative numbers

Posted 19 September 2016 - 10:40 PM

You mean something like this...

try:
    myint = int(input('How many random numbers would you like to generate?:  '))
    if myint <= 0:
        raise ValueError("Please enter a number greater than zero")
except ValueError:
    # Do stuff



Here we take in the value, convert it to an integer, compare it to see if it is less than or equal to zero. If so, we raise an error.
Was This Post Helpful? 0
  • +
  • -

#3 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: I need a exception that won't allow negative numbers

Posted 20 September 2016 - 03:51 AM

While I'm normally a big fan of compact syntax; here it's not working for you.

You want to get the amount from the user, then proceed. Combining the two is cause for confusion.

So, with comments:
# get the count, first
count = None
# loop until we have our count
while count == None:
    try:
        # ask for the count
        count = int(input('How many random numbers would you like to generate?:  '))
        # if we got this far, we actually have an int
        # now we can apply further tests
        if count < 1:
            # fail, print a message
            print('Value must be greater than zero.')
            # note, we needn't raise an error
            # the goal is to loop until we have a valid value
            # so, set count back to an invalid value
            count = None
        
    except ValueError:
        # if we get here, count was never assigned
        # tell the user, the loop will continue
        print('Numerical values only, please.')
# if we get here
# then count actually contains a value >0

# time to do work
rand_write= open("randomnum.txt", "w")
for i in range(count):
    line = str(random.randint(1,999)) +"\n"
# ...



Ideally, that whole business of getting a number from a user could go in a function. Then, your code might read something like:
# returns a positive int greater than zero
def get_pos_int(prompt):
    # your code here, see above

def dump_rand_nums(filename, count):
    # your code here

dump_rand_nums("randomnum.txt", get_pos_int('How many random numbers would you like to generate?:  '))



Hope this helps.
Was This Post Helpful? 2
  • +
  • -

#4 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 607
  • View blog
  • Posts: 1,927
  • Joined: 27-December 13

Re: I need a exception that won't allow negative numbers

Posted 20 September 2016 - 10:36 AM

baavgai, I admire your structure and your clear explanations. The clarity in this one is an example to all of us.
Was This Post Helpful? 0
  • +
  • -

#5 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: I need a exception that won't allow negative numbers

Posted 20 September 2016 - 10:59 AM

*Takes a bow.*

Thank you. I find myself moving code around until I'm happy: mine, yours, anyone's that catches my eye. Here, I get to use that for good; I hope. I rarely post my refactors, as they would be spoilers and often have drifted too far from the original. The real trick is offering less code, not more, that most applicable to the OP.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1