Reputation: 156
my problem is that I only want to add the string "Karte1" once to a list. But right now, the string "Karte1" is adding to a list unlimited times.. Hope u can help me :)
import random
Deck1 = []
def startgame():
try:
"Karte1" not in Deck1
if True:
Deck1.append("Karte1")
if False:
pass
except:
pass
while True:
startgame()
print(Deck1)
Upvotes: 5
Views: 9084
Reputation: 2416
You can use a set data structure rather than a list. A set holds unique values, by default.
From Python Docs
https://docs.python.org/2/library/sets.html
The sets module provides classes for constructing and manipulating unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.
Example
my_set = set([1,2,3,2])
print(my_set) # prints [1,2,3]
my_set.add(4)
print(my_set) # prints [1,2,3,4]
my_set.add(3)
print(my_set) # prints [1,2,3,4]
Upvotes: 2
Reputation: 10641
You can use a set if you want unique values.
But in your case just change your code to:
if "Karte1" not in Deck1:
Deck1.append("Karte1")
EDIT:
Notice that in your while statement you call to the function startgame2, when the name of the function you defined is startgame
Upvotes: 6
Reputation: 196
The if True
statement will allways be True, so each time you call the startgame()
function it will add it to the Deck
What you probably want to do is :`
if "Karte1" not in Deck1:
Deck1.append("Karte1")
Upvotes: 0