简体   繁体   中英

python for loops being started at 1st element no 0th element

I am writing a simple text-based RPG battle simulator using Python (running on PyCharm). I created a class called Person which has initialization parameters as follows:

def __init__(self, name, HP, MP, ATK, DEF, magic, items):
    self.name = name
    self.HP = HP
    etc...

this class gets instantiated 3 times in main for 3 unique players ( player1, player2, player3 ). I also have a function get_stats(self) which does

print(self.name + ", HP: " + self.HP + ", MP: " + self.MP)

but when I run in main

for player in players:
    player.get_stats()

where players = {player1, player2, player3} , I get the output (note that the MP/HP values are arbitrary):

name2, HP: 200, MP: 200
name3, HP: 300, MP: 300
name1, HP: 100, MP: 100

and if players = {player0, player1, player2, player3} , I get the output:

name2, HP: 200, MP: 200
name3, HP: 300, MP: 300
name0, HP: 400, MP: 400
name1, HP: 100, MP: 100

why does this happen and how can I fix it?

{} creates a set in python, which are not ordered: the elements are not stored in the way they are entered.

You need a list, which can be created as:

players = [player1, player2, player3]

or a tuple:

players = (player1, player2, player3)

You are using the {} syntax that is meant for set s in Python. Sets do not have an order, and will yield their members at random when used in a for statement.

Simply be consistent and use (Player0, ...) to denote a tuple, or [Player0, ...] to denote a list - both of these types are "sequences", which have a well defined order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM