0

I'm relatively new to coding but am trying to make a little game.

I want to make the names of the variables "ship_turned" and "ship_turned_rect" dependent on a given parameter "ship". For example, I want to be able to write "ship1" as the argument in order to make "ship_turned" into "ship1_turned" and "ship_turned_rect" into "ship1_turned_rect".

Here is my incomplete start at the relevant part of the code...

def turningdirection(ship):
        ship_turned, ship_turned_rect = turning(0, ship)
        return ship_turned, ship_turned_rect

I've tried making ship_turned and ship_turned_rect as 2 more parameters, but that doesn't seem to work.

Altareos
  • 843
  • 6
  • 13
  • 4
    From this snippet it doesn't seem that the name of `ship_turned` matters. The two lines are the same as doing `return turning(0, ship)`. Could you elaborate on why the name needs to change? – Kemp Jun 25 '21 at 10:04
  • 2
    Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Jun 25 '21 at 10:08

1 Answers1

0

In your example, the variables do not have to be named differently based on the ship since the are encapsulated in this specific function. If you are intending to store the data further on, the following may help you out.

If you use bare variables, they can not be named easily by strings. What a proper solution would be, is to use a dictionary for that. Dictionaries store data by assigning values to keys. In your case, strings would be a good key. Something like the following:

ship_data = {}
ship_data['shipA'] = 'asdf'
ship_data['shipB'] = 'xyz'

To get the data back for a specific ship, just use ship_data.get('shipA'). The use of 'asdf' and 'xyz' is just an example. You can store nearly every data type you wish. Please be aware, that dictionary keys can not exist twice in the same dictionary.

ifumho
  • 141
  • 6