-1
if strengh1 <=0:
    death1=True
else:
    death1 = False

if strengh2 <=0:
    death2=True
else:
    death2=False

def output(character):
    if death character == False:
        print
        print('Character', character ,' strengh is now %s' % strengh1)    
        print('Character ', character ,' skill is now %s' % skill1)
    else:
        print
        print('Character ', character ,' is dead')

output(1)
output(2)

Hi guys I am currently doing a bit of a project. here is part of my very last lines of code. There are two characters and i want to be able to use a function. I am almost fully self taught and i havnt been coding very long at all so there might be basic errors or i might be doing something that just cant work, but how can i change the name of the "death" variable in the function using what is in the function call? So for example output(10 needs to change death to death1? is this possible. Also i need to be able to print this in one solid output as Character (then the function parameter) is now dead

sundar nataraj
  • 8,524
  • 2
  • 34
  • 46

2 Answers2

0

Your code demonstrates a profound misunderstanding of the way Python names work. Just setting character = 1 and writing death character will not access death1, that simply doesn't make any sense. There is a good primer on how Python deals with names here.

Your specific issue could be solved by passing to output all of the variables it actually needs:

def output(character, strength, skill, death):
    if not death:
        print
        print('Character', character ,' strength is now %s' % strength)    
        print('Character ', character ,' skill is now %s' % skill)
    else:
        print
        print('Character ', character ,' is dead')

output(1, strength1, skill1, death1)

This is obviously a bit awkward, so the next step would be to encapsulate these parameters as attributes in a Character class; see e.g. the tutorial. Then you can pass a single Character instance to the function.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

Very often, the most natural solution is to use a dictionary.

death = dict()
# most probably strength should be a dict too

if strengh1 <=0:
    death[1]=True
else:
    death[1] = False
# or death[1] = bool(strength1<=0)

if strengh2 <=0:
    death[2]=True
else:
    death[2]=False

def output(key):
  if death[key]== False:
    print
    print('Character', character ,' strengh is now %s' % strengh1)    
    print('Character ', character ,' skill is now %s' % skill1)
  else:
    print
    print('Character ', character ,' is dead')

output(1)
output(2)

Depending on what 1 and 2 stand for, you might want to use strings instead -- strength['muscles'], death['poisoning'] perhaps? (Or strength['marketing'] and death['irrelevance'] if this is a startup game.)

tripleee
  • 175,061
  • 34
  • 275
  • 318