How to avoid repeating code?

Asked

Viewed 187 times

1

I have a Python 3 script that tries to be a chatbot, where there are several if and elses which are used based on what the user responds to.

The problem is that in all functions, like get_name() or get_age(), those if and Else repeat.

def get_name():
while True:
    global name
    name = question_renderer("What's your name?")
    name = name.lower().capitalize()
    if name == '':
        continue
    elif name.isdigit():
        typing(1)
        print("Please don't type numbers.")
    else:
        list = ["I like your name.", "I always wanted to have that name.", "My friend has the same name."]
        typing(1)
        print(choice(list))
        break

def get_age():
while True:
    try:
        age = int(question_renderer("How old are you, {}?".format(name)))
    except ValueError:
        typing(1)
        print("Please, just type numbers.")
    else:
        if int(age) <= 25:
            typing(2)
            list = ["You're still young.", "Being young is very good.", "Enjoy your youth."]
            print(choice(list))
        elif int(age) > 25:
            typing(1)
            list = ["You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends."]
            print(choice(list))
        break

How do I make it not happen across the code?

  • 1

    Why instead of that continue you do not put an if name != '': and put the Elif as if and Else inside the first if?

2 answers

1


I can’t think of a better way to get your code to remove these if, But I tweaked your code and took away unnecessary things.

1 - I took the continue, it is not necessary.

2 - You created two phrase lists, the list type is the slowest type of Data Structure, and it was something unnecessary for Choice, so I created 2 Sets(Sets) and already applied them within Choice.

from random import choice

def get_name():
    while True:
        global name
        name = input("What's your name?")
        name = name.lower().capitalize()
        if name != '':
            if name.isdigit():
                print("Please don't type numbers.")
            else:
                print(choice(("I like your name.", "I always wanted to have that name.", "My friend has the same name.")))
                break

def get_age():
    while True:
        try:        
            age = int(input("How old are you, "+name+"?"))
        except ValueError:
            print("Please, just type numbers.")
        else:
            if int(age) <= 25:
                print(choice(("You're still young.", "Being young is very good.", "Enjoy your youth.")))
            elif int(age) > 25:
                print(choice(("You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends.")))
            break

0

You can also replace the loop while calling the function again in places where it theoretically would not receive the desired input.

I’m reusing the user92257 code

from random import choice

def get_name():
    global name
    name = input("What's your name? ")
    name = name.lower().capitalize()

    if name != '':
        if name.isdigit():
            print("Please don't type numbers.")
            get_name() # aqui

        else:
            print(choice(("I like your name.", "I always wanted to have that name.", "My friend has the same name.")))
            
def get_age():
    try:        
        age = int(input("How old are you, "+name+"? "))

    except ValueError:
        print("Please, just type numbers.")
        get_age() # E aqui também

    else:
        if int(age) <= 25:
            print(choice(("You're still young.", "Being young is very good.", "Enjoy your youth.")))

        elif int(age) > 25:
            print(choice(("You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends.")))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.