#python #function #class #python-3.9
#python #функция #класс #python-3.9
Вопрос:
Я пытался изменить операторы «if» и использовать else вместо «elif», но при использовании функции изменения он игнорирует «n» или «N» входов.
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...")
Ответ №1:
Вам не нужно or
«а» в вашем «если». Я вижу два решения:
Используйте список ответов «ДА»:
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...")
Используйте строковый upper
метод, чтобы избежать множественного выбора:
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...")
Мне нравится первое решение, потому что вы можете использовать больше опций, например:
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')
Комментарии:
1. Спасибо за отзыв 🙂
Ответ №2:
def Change_Companion_Name(self):
choice = str(input("Do you wish to change your companions name?[Y/N]"))
if choice == 'y' or choice == 'Y':
new_name = str(input("Enter in your companions new name: "))
self.companion_name = new_name
elif choice == 'n' or choice == 'N':
print("No changes have been made...")
Я думаю, вам следует написать свой оператор if, как указано выше. Теперь вы можете изменить elif с помощью оператора else.