Answer the question
In order to leave comments, you need to log in
Does not enter the loop even though the conditions are met. Where is the mistake?
import random
import sys
def print_mimic(mimic_dict, word):
bred = []
x = 0
while x < 200:
if x == 0:
first = word ### В это части цикла всё хорошо
dobav = random.choice(mimic_dict[first])
bred.append(dobav)
x += 1
else:
print (dobav in mimic_dict)
if dobav in mimic_dict == True: ### А вот тут проблема. Строчка
dobav = random.choice(mimic_dict[dobav]) ### выше выдает True но почему то в цикл if
bred.append(dobav) ### не переходит, а соскакивает
x +=1 ### в else. Как такое
else: ### может быть? Спасибо
dobav = random.choice(mimic_dict[" "])
bred.append(dobav)
x += 1
print (bred)
return bred
mimic_dict = {" " : ["A", "B" , "C"],
"A" : ["1", "2" "3"],
"B" : ["4", "5" "6"],
"C" : ["7", "8" "9"] }
print_mimic(mimic_dict, " ")
Answer the question
In order to leave comments, you need to log in
The priority of operations must be taken into account, apparently:
it will give False, since (1, 2, 3) == True will be executed first, which will return False, and then the check 1 in False will turn out, which is False.
And this is correct: it
will give True.
And this is even more correct:
if 1 in (1, 2, 3):
pass
There are a lot of strange places in the source code. For example, the commas in the dictionary definition are omitted in a strange and dangerous way, the dangerous use of the dobav variable in the else branch... This all leads to unsafe code in terms of understanding and future modifications. There is an obvious lack of experience.
You have already been answered about the precedence of operations, but let's try to refactor your code step by step for clarity.
This is what your function body is equivalent to:
def print_mimic(mimic_dict, word):
bred = []
x = 0
dobav = word
while x < 200:
if x == 0 or dobav in mimic_dict:
dobav = random.choice(mimic_dict[dobav])
else:
dobav = random.choice(mimic_dict[" "])
bred.append(dobav)
x += 1
print (bred)
return bred
def print_mimic(mimic_dict, word):
bred = []
dobav = word
for x in range(200):
dobav = random.choice(mimic_dict.get(dobav, mimic_dict[" "]))
bred.append(dobav)
print (bred)
return bred
if dobav in mimic_dict == True:
>>> False
if (dobav in mimic_dict) == True:
>>> True
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question