Search code examples
pythonfunctionclasspython-3.9

Functions is the class ignores inputs


I've tried changing around the "if" statements and using else instead of "elif" but when using the Change function it ignores "n" or "N" inputs.

class Settings:
    def __init__(self):
        self.text_speed = 1
        self.companion_name = ("")
        self.player_name = ("")

    def Change_Text_Speed(self):
        choice = int(input("Text Speed Options:\n1.5x [1] \n2x [2] \n2.5x [3] \nExit[4]"))
        if choice == 1:
            self.text_speed = (self.text_speed*1.5)
        elif choice == 2:
            self.text_speed = (self.text_speed*2)
        elif choice ==3:
            self.text_speed = (self.text_speed*2.5)
        else:
            print("No changes have been made...")

    def Change_Companion_Name(self):
        choice = str(input("Do you wish to change your companions name?[Y/N]"))
        if choice == 'y' or 'Y':
            new_name = str(input("Enter in your companions new name: "))
            self.companion_name = new_name
        elif choice == 'n' or 'N':
            print("No changes have been made...")
    
    def Change_Player_Name(self):
        choice = str(input("Do you wish to change your name?[Y/N]"))
        if choice == 'y' or 'Y':
            new_name = str(input("Enter in your new name: "))
            self.player_name = new_name
        elif choice == 'n' or 'N':
            print("No changes have been made...")

Solution

  • You dont need a or in your if. I see two solution:

    Use a list of YES answers:

    def Change_Companion_Name(self):
        choice = str(input("Do you wish to change your companions name?[Y/N]"))
        if choice in ['y', 'Y']:
            new_name = str(input("Enter in your companions new name: "))
            self.companion_name = new_name
        elif choice == ['n', 'N']:
            print("No changes have been made...")
    

    Use a string upper method to avoid multiple choices:

    def Change_Companion_Name(self):
        choice = str(input("Do you wish to change your companions name?[Y/N]"))
        if choice.upper() == 'Y':
            new_name = str(input("Enter in your companions new name: "))
            self.companion_name = new_name
        elif choice.upper() == 'N':
            print("No changes have been made...")
    

    I like the first solution, because you can use more options, like this:

    choice = str(input("Choice Yes or No.[Y/N]"))
    yes_choices = ['YES', 'Y']
    if choice.upper() in yes_choices:
        print('You chose YES')
    elif choice.upper() in ['NO', 'N']:
        print('You chose NO')