Вот несколько способов создания звуков животных с использованием примеров кода на Python:
Метод 1: использование словаря
def animal_sound(animal):
sounds = {
'cat': 'Meow',
'dog': 'Woof',
'cow': 'Moo',
'duck': 'Quack',
'elephant': 'Trumpet'
# Add more animal sounds as needed
}
if animal in sounds:
return sounds[animal]
else:
return 'Unknown animal'
animal = 'cat'
sound = animal_sound(animal)
print(sound) # Output: Meow
Метод 2: использование операторов if-elif
def animal_sound(animal):
if animal == 'cat':
return 'Meow'
elif animal == 'dog':
return 'Woof'
elif animal == 'cow':
return 'Moo'
elif animal == 'duck':
return 'Quack'
elif animal == 'elephant':
return 'Trumpet'
else:
return 'Unknown animal'
animal = 'dog'
sound = animal_sound(animal)
print(sound) # Output: Woof
Метод 3. Использование списка
def animal_sound(animal):
animals = ['cat', 'dog', 'cow', 'duck', 'elephant']
sounds = ['Meow', 'Woof', 'Moo', 'Quack', 'Trumpet']
if animal in animals:
index = animals.index(animal)
return sounds[index]
else:
return 'Unknown animal'
animal = 'cow'
sound = animal_sound(animal)
print(sound) # Output: Moo
Метод 4. Использование класса
class Animal:
def __init__(self, animal):
self.animal = animal
def make_sound(self):
if self.animal == 'cat':
return 'Meow'
elif self.animal == 'dog':
return 'Woof'
elif self.animal == 'cow':
return 'Moo'
elif self.animal == 'duck':
return 'Quack'
elif self.animal == 'elephant':
return 'Trumpet'
else:
return 'Unknown animal'
animal = Animal('duck')
sound = animal.make_sound()
print(sound) # Output: Quack