Python Forum
how to avoid a lot of 'if' statments ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to avoid a lot of 'if' statments ? (/thread-12489.html)

Pages: 1 2


how to avoid a lot of 'if' statments ? - witch - Aug-27-2018

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)
Im making a game and I don`t know how to avoid theese if, elif statments, is there a way to not write a huge code ?


RE: how to avoid a lot of 'if' statments ? - woooee - Aug-27-2018

Use a list of lists
list_of_lists = [[2', '1', lyashko],
                [2', '3', yacenyuk],
                [2', '4', tymoshenko]]

for one, two, arg in list_of_lists:
    if pol1 == one and pol2 == two:
        poroh.attack(arg)
Edit:
Quote:I inserted your code into mine and unfortunetely it doesnt work(( it says invalid syntax
No one can help with an invalid syntax on an unknown line, in code you used but did not post here.


RE: how to avoid a lot of 'if' statments ? - buran - Aug-27-2018

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


RE: how to avoid a lot of 'if' statments ? - witch - Aug-27-2018

(Aug-27-2018, 11:49 AM)woooee Wrote: Use a list of lists
list_of_lists = [[2', '1', lyashko],
                [2', '3', yacenyuk],
                [2', '4', tymoshenko]]

for one, two, arg in list_of_lists:
    if pol1 == one and pol2 == two:
        poroh.attack(arg)

I inserted your code into mine and unfortunetely it doesnt work(( it says invalid syntax


RE: how to avoid a lot of 'if' statments ? - Larz60+ - Aug-27-2018

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)])



RE: how to avoid a lot of 'if' statments ? - witch - Aug-27-2018

(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 ?


RE: how to avoid a lot of 'if' statments ? - buran - Aug-27-2018

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)
 
politicians = {'1':lyashko, '2':poroh, '3':yacenyuk, '4':tymoshenko}
 
 
pol1 = input('Хто буде бити ? (Виберіть цифру)\n')
pol2 = input('Кого будуть бити ? (Виберіть цифру\n')
 
politician1 = politicians[pol1]
politician2 = politicians[pol2]
politician1.attack(politician2)
Output:
Вас вітає гра "Мортал Комбат: Політична Версія"! Наші політики: 1 -- Ляшко, 2 -- Порошенко, 3 -- Яценюк, 4 -- Тимошенко Виберіть батл який бажаєте побачити Хто буде бити ? (Виберіть цифру) 2 Кого будуть бити ? (Виберіть цифру 4 БАБАХ!! Порошенко атакує Тимошенко !!! У Тимошенко лишилось 88 ХП
You can skip some of intermediate steps.


RE: how to avoid a lot of 'if' statments ? - witch - Aug-27-2018

(Aug-27-2018, 12:48 PM)buran Wrote:
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)
 
politicians = {'1':lyashko, '2':poroh, '3':yacenyuk, '4':tymoshenko}
 
 
pol1 = input('Хто буде бити ? (Виберіть цифру)\n')
pol2 = input('Кого будуть бити ? (Виберіть цифру\n')
 
politician1 = politicians[pol1]
politician2 = politicians[pol2]
politician1.attack(politician2)
Output:
Вас вітає гра "Мортал Комбат: Політична Версія"! Наші політики: 1 -- Ляшко, 2 -- Порошенко, 3 -- Яценюк, 4 -- Тимошенко Виберіть батл який бажаєте побачити Хто буде бити ? (Виберіть цифру) 2 Кого будуть бити ? (Виберіть цифру 4 БАБАХ!! Порошенко атакує Тимошенко !!! У Тимошенко лишилось 88 ХП
You can skip some of intermediate steps.

yes it worked, you are awesome ! can you explain it a little bit please ? and other question, how do I loop it so the game doesnt end after one choice
EDIT: now I get it, thanks man !


RE: how to avoid a lot of 'if' statments ? - Gribouillis - Aug-27-2018

(Aug-27-2018, 12:06 PM)witch Wrote: why does it execute choice 1,2,3 at a same time?
Use a list and write simply
politicians = [ryashko, poroh, yacenyuk, tymoshenko]

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

politicans[pol1 - 1].attack(politicians[pol2 - 1])



RE: how to avoid a lot of 'if' statments ? - buran - Aug-27-2018

To make it more universal
class Politician(object):
 
    def __init__ (self, name, damage, health):
        self.name = name
        self.damage = damage
        self.health = health
 
    def attack (self, other_guy):
        other_guy.health -= self.damage
        print('БАБАХ!!')
        print('{} атакує {} !!!'.format(self.name, other_guy.name))
        print('У {} лишилось {} ХП\n'.format(other_guy.name, other_guy.health))
     
politicians_data = (('Ляшко', 15, 100), ('Порошенко', 12, 100), ('Яценюк', 9, 100), ('Тимошенко', 11, 100))
politicians = [Politician(name, damage, health) for name, damage, health in politicians_data]

print('Вас вітає гра "Мортал Комбат: Політична Версія"!\n')
print('Наші політики:\n')
for i, pol in enumerate(politicians, start=1):
  print('{} --> {}'.format(i, pol.name))
print('Виберіть батл який бажаєте побачити\n')
 
 
pol1 = int(input('Хто буде бити ? (Виберіть цифру)\n')) - 1
pol2 = int(input('Кого будуть бити ? (Виберіть цифру\n')) -1 
 
politician1 = politicians[pol1]
politician2 = politicians[pol2]
politician1.attack(politician2)
Output:
Вас вітає гра "Мортал Комбат: Політична Версія"! Наші політики: 1 --> Ляшко 2 --> Порошенко 3 --> Яценюк 4 --> Тимошенко Виберіть батл який бажаєте побачити Хто буде бити ? (Виберіть цифру) 3 Кого будуть бити ? (Виберіть цифру 1 БАБАХ!! Яценюк атакує Ляшко !!! У Ляшко лишилось 91 ХП
Now you can add more politician by just changing politicians_data and nothing else