Search code examples
pythonfunctionpycharmnew-operator

Running different functions based on the user's input


I am new to Pycharm, and Python as a whole, and for my first project I decided to do a random name/object selector which chooses a name from a pre-made variable of letters and prints that result. I wanted to expand on this and have the user either use the default names in the code or add their own names to be used. I gave it my best effort but when it came to the script running 1 of two functions I was unable to figure out how to do that. Any help?

import string
import random
import os

letters = 'wjsdc' #*Default letters*
choice = random.choice(letters)

decision = input("Hello, use default? y/n")
print("You have chosen " + decision + ", Running function.")

def generator():
if decision == "y":        #*Default function*
    choice = random.choice(letters)
    print("Name chosen is " + generator())
elif decision == "n":       #*Attempted new function*
    new_name1 = input("Please add a name")
    new_name2 = input("Please add a name")
    new_name3 = input("Please add a name")
    new_name4 = input("Please add a name")
    new_name5 = input("Please add a name")
    if choice == "w":
        finalname = new_name1
    elif choice == "j":
        finalname = new_name2
    elif choice == "s":
        finalname = new_name3
    elif choice == "c":
        finalname = new_name4
    elif choice == "d":
        finalname = new_name5
    name = finalname
    return name
print("Name chosen is " + name)

def generator():        #*Default function script*
    if choice == "w":
        finalname = "Wade"
    elif choice == "j":
        finalname = "Jack"
    elif choice == "s":
        finalname = "Scott"
    elif choice == "d":
        finalname = "Dan"
    elif choice == "c":
        finalname = "Conall"
    name = finalname
    return name

print("Name chosen is " + generator())

Solution

  • Your code is pretty weird, and I'm not sure what you are trying to achieve.

    • you define two functions generator; you should give them different names
    • instead of chosing from one of the letters and then selecting the "long" name accordingly, just chose from the list of names in the first place
    • you can use a list for the different user-inputted names

    I'd suggest using something like this:

    import random
    
    def generate_name():
        names = "Wade", "Jack", "Scott", "Dan", "Conall"
        decision = input("Use default names? Y/n ")
        if decision == "n":
            print("Please enter 5 names")
            names = [input() for _ in range(5)]
        return random.choice(names)
    
    print("Name chosen is " + generate_name())