I've started learning Python (again). This simple code with a cycle works by itself. But when I put it into a Brython it doesn't. No part of it works until I comment out everything, but simple alert() commands. I've tried just a "i+=1" cycle — doesn't work. I've checked indents and spacing, too.
What is wrong?
Thank you.
from browser import document
from browser import alert
i=0
r = ''
s = 'nín'
d = {'nín':'нин','hǎo':'хао','lǎo':'лао','wài':'уай','ī': 'ӣ', 'bī': 'бӣ', 'jī': 'чжӣ', 'nī': 'нӣ', 'nīn': 'нӣнь', 'nīng': 'нӣн'}
def set_r():
r = '12345'
alert(i)
#while i < len(s):
#flag = True
#for j in range(4):
#t = s[i:i+j]
#if t in d:
#r += d[t]
#i += j
#flag = False
#break
#if flag:
#r += s[i]
#i += 1
alert( s );
set_r();
I wanted any part of the Python code to work in the browser, like a simple cycle with an integer.
I see your indentation is wrong, remember Python is sensitive to this and the code will fail if not correct. Remember to always indent the block of a while or if statement (and similar).
When defining the variables outside the methods (globally) in a static context, use the global
keyword followed by the variable names inside of the methods to refer to them. Otherwise the set_r method will not see the globally defined variables.
Also, you don`t need semicolon after a line in python like in other languages.
Try the following code:
from browser import document
from browser import alert
i=0
r = ''
s = 'nín'
d = {'nín':'нин','hǎo':'хао','lǎo':'лао','wài':'уай','ī': 'ӣ',
'bī': 'бӣ', 'jī': 'чжӣ', 'nī': 'нӣ', 'nīn': 'нӣнь', 'nīng': 'нӣн'}
def set_r():
global r, i # Add these lines to access and modify the global variables
r = '12345'
alert(i)
while i < len(s):
flag = True
for j in range(4):
t = s[i:i+j]
if t in d:
r += d[t]
i += j
flag = False
if flag:
r += s[i]
i += 1
alert(s)
set_r()
Hope this helps!