0

I am trying to randomly select a string from a list and am having trouble stopping the user from getting 0 items from the list.

import random
Uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

def pick():
    while True:
        try:
            UCL = random.sample(Uppercase, k=int(input("How many uppercase letters do you want in your password(Pick a number between 1 and 26)?: ")))
            break
        except ValueError:
            print("Please give an Number")
            continue
martineau
  • 119,623
  • 25
  • 170
  • 301
Man in hat
  • 11
  • 2
  • 2
    You should validate your input before you pass it to `random.sample`. See: [Asking the user for input until they give a valid response](https://stackoverflow.com/q/23294658/15497888) – Henry Ecker Apr 10 '21 at 18:47

2 Answers2

0

You need to check if the entered number is zero, (or also negative).

k=int(input("How many uppercase letters do you want in your password(Pick a number between 1 and 26)?: ")
if k<=0:
    print('Invalid number, try agian')
    continue
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

You can raise a validation error from your input data and continue a loop. You might need to incorporate a check break clause to stop an infinite loop


import random
Uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

def pick():
    while True:
        try:
            val =int(input("How many uppercase letters do you want in your password(Pick a number between 1 and 26)?: "))
            if val == 0:
                print('Select another no')
                raise ValueError 
            UCL = random.sample(Uppercase, val)
            break
        except ValueError:
            print("Please give an Number")
            continue
Ade_1
  • 1,480
  • 1
  • 6
  • 17