Python Forum
how to avoid a lot of 'if' statments ?
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to avoid a lot of 'if' statments ?
#6
(Aug-27-2018, 11:56 AM)buran Wrote: use dictionary. Can you elaborate what your ultimate goal is. I see that you have also different variable names based on politicians names. That's also not good idea (not that they are names of politicians, but to design the code like this). EDIT: maybe there is class and in this case it's better to have dict of class instances, not just strings. If you show more of your code, we may help more

print('Вас вітає гра "Мортал Комбат: Політична Версія"!\n')
print('Наші політики: 1 -- Ляшко, 2 -- Порошенко, 3 -- Яценюк, 4 -- Тимошенко\n')
print('Виберіть батл який бажаєте побачити\n')

class politics:

    def __init__ (self, name, damage, health):
        self.name = name
        self.damage = damage
        self.health = health

    def attack (self, other_guy):
        other_guy.health = other_guy.health - self.damage
        print('БАБАХ!!')
        print('{} атакує {} !!!'.format(self.name, other_guy.name))
        print('У {} лишилось {} ХП\n'.format(other_guy.name, other_guy.health))
    
lyashko = politics('Ляшко', 15, 100)
poroh = politics('Порошенко', 12, 100)
yacenyuk = politics('Яценюк', 9, 100)
tymoshenko = politics('Тимошенко', 11, 100)

politics_dict = {'Ляшко': '1', 'Порошенко': '2', 'Яценюк': '3', 'Тимошенко': '4'}


pol1 = (str(input('Хто буде бити ? (Виберіть цифру)\n')))
pol2 = (str(input('Кого будуть бити ? (Виберіть цифру\n')))

if pol1 == '2' and pol2 == '1':
    print(poroh.attack(lyashko))
elif pol1 == '2' and pol2 == '3':
    poroh.attack(yacenyuk)
elif pol1 == '2' and pol2 == '4':
    poroh.attack(tymoshenko)
this is the full code

(Aug-27-2018, 12:03 PM)Larz60+ Wrote: You can use a dictionary with complex key, this will allow you to add other conditions:

politics_dict = {'Ляшко': '1', 'Порошенко': '2', 'Яценюк': '3', 'Тимошенко': '4'}
 
pol1 = (str(input('Хто буде бити ? (Виберіть цифру)\n')))
pol2 = (str(input('Кого будуть бити ? (Виберіть цифру)\n')))

options = {
    ('2', '1'): 'poroh.attack(lyashko)',
    ('2', '3'): 'poroh.attack(yacenyuk)', 
    ('2', '4'): 'poroh.attack(tymoshenko)'
}

if (pol1, pol2) not in options:
    print('Недійсний вибір')
else:
    print(options[(pol1, pol2)])

cool, this is working, but why does it execute choice 1,2,3 at a same time? when I for example choose 2 and 1, I get poroh.attack(lyashko) and poroh.attack(yacenyuk) and poroh.attack(tymoshenko), and other question, how do I loop it ? so the game doesnt end after one choice ?
Reply


Messages In This Thread
how to avoid a lot of 'if' statments ? - by witch - Aug-27-2018, 11:36 AM
RE: how to avoid a lot of 'if' statments ? - by witch - Aug-27-2018, 12:06 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020