Home > Enterprise >  Last paragraph of code is running when it does not need to
Last paragraph of code is running when it does not need to

Time:07-10

I am working on a username generator in Python, and everything is going well but one thing: the "IF" statement at the very end of the code is malfunctioning. The first part of the code works, but the last paragraph kicks in, even when I have typed in a supposedly valid choice.

The code:

[import random, tkinter

#variables that make up the name. the "1" symbolises the first part and the "2" symbolises the last part of the username
general1 = \["noob","baby","dude","soldier","discount"\]
general2 = \["kid","plant","painter","officer","conscience"\]

animal1 = \["frantic","fiesty","quick","quiet","loud"\]
animal2 = \["ferret","dog","hampster","cat","rabbit"\]

food1 = \["delicious","disgusting","stinky","fried","bitter"\]
food2 = \["pickle","chocolate","rice","water","lemonade"\]

name1 = \["dylan","eve","chris","simon","adele"\]
name2 = \["christopher","sharp","smith","james","baker"\]

#the main part
category = str(input("**USERNAME GENERATOR**\n\nWhat category do you want?\n1 for general\n2 for animals\n3 for food\n4 for human names\n\n"))

if category == "1":
    output1 = random.choice((general1))
    output2 = random.choice((general2))
    endNumber = random.randint(0, 100)
    print("\nYour random username is: ",output1,output2,endNumber)

if category == "2":
    output1 = random.choice((animal1))
    output2 = random.choice((animal2))
    endNumber = random.randint(0, 100)
    print("\nYour random username is: ",output1,output2,endNumber)

if category == "3":
    output1 = random.choice((food1))
    output2 = random.choice((food2))
    endNumber = random.randint(0, 100)
    print("\nYour random username is: ",output1,output2,endNumber)

if category == "4":
    output1 = random.choice((name1))
    output2 = random.choice((name2))
    endNumber = random.randint(0, 100)
    print("\nYour random username is: ",output1,output2,endNumber)

if category != ("1","2","3","4"):
    print("\nPlease enter a valid option:")
    category = str(input("What category do you want?\n1 for general\n2 for animals\n3 for food\n4 for human names\n\n"))][1]

CodePudding user response:

if category != ("1","2","3","4"):

This only checks if category is equal to the tuple ("1","2","3","4"). You want to check if category is equal to any value of the tuple. Do that by changing that line to this:

if category not in ("1","2","3","4"):

CodePudding user response:

After an if statement ends, the next line is executed. In your case, the next line is the next if paragraph. And after that the next one and so on. e.g.:

if a:
   do_action_a()
if b:
   do_action_b()
if c:
   do_action_c()
if not(a or b or c):
   do_action_all_others()

Here you will always execute each paragraph independently of the previous one(s).

To avoid this, you can put each of the following statements in the else of the previous if statement:

if a:
   do_action_a()
else:
   if b:
      do_action_b()
   else:
      if c:
         do_action_c()
      else:
         do_action_all_others()

However, there is an idiom for this: elif

so the pythonic is to use:

if a:
   do_action_a()
elif b:
   do_action_b()
elif c:
   do_action_c()
else:
   do_action_all_others()

CodePudding user response:

Change the last conditional statement to

if category not in ('1', '2', '3', '4'):
    print('\nPlease enter a valid option:')
    category = str(input('. . .'))

My Refined Implementation of your code

import random

general_first = ['noob', 'baby', 'dude', 'soldier', 'discount']
general_last = ['kid', 'plant', 'painter', 'officer', 'conscience']

animal_first = ['frantic', 'fiesta', 'quick', 'quiet', 'loud']
animal_last = ['ferret', 'dog', 'hamster', 'cat', 'rabbit']

food_first = ['delicious', 'disgusting', 'stinky', 'fried', 'bitter']
food_last = ['pickle', 'chocolate', 'rice', 'water', 'lemonade']

name_first = ['dylan', 'eve', 'chris', 'simon', 'adele']
name_last = ['christopher', 'sharp', 'smith', 'james', 'baker']


def endNumber(): return str(random.randint(0, 100))


def firstName(values): return random.choice(values)


def lastName(values): return random.choice(values)


def generate_usernames(category):
    if category == 1:
        return firstName(general_first)   lastName(general_last)   endNumber()
    elif category == 2:
        return firstName(animal_first)   lastName(animal_last)   endNumber()
    elif category == 3:
        return firstName(food_first)   lastName(food_last)   endNumber()
    elif category == 4:
        return firstName(name_first)   lastName(name_last)   endNumber()
    else:
        return None


input_prompt = "What category do you want?" \
               "\n'1' for general" \
               "\n'2' for animals" \
               "\n'3' for food" \
               "\n'4' for human names" \
               "\n\nCHOICE : "

invalid_prompt = "\nPlease enter a valid option"

print('\tUSERNAME GENERATOR')
while True:
    input_category = int(input(input_prompt))
    username = generate_usernames(input_category)
    if username is not None:
        print(f'Your Random Username is : {username}')
        break
    else:
        print(invalid_prompt)
  • Related