Package: pytago
pytagoPytago is a source-to-source transpiler that converts some Python into human-readable Go.Try out the web demoInstallation and usageThere are two "officially" supported ways to use Pytago:A web application you can run via dockerA locally-installed command-line toolWeb applicationPrerequisitesDockerInstallationgit clone https://github.com/nottheswimmer/pytago/
cd pytago
docker build -t pytago .Usagedocker run -p 8080:8080 -e PORT=8080 -it pytago

# User interface
open http://127.0.0.1:8080/

# API
curl --request POST 'http://127.0.0.1:8080/' \
  --header 'Content-Type: application/json'  \
  --data-raw '{"py": "print(\"Hello World\")"}'Local command-line applicationPrerequisitesGo 1.16.xPython 3.10.xNo, it will not work on 3.9. Search the code for "match."go get -u golang.org/x/tools/cmd/goimports mvdan.cc/gofumpt github.com/segmentio/golinesInstallationvia pippip install pytagovia setup.py (dev)git clone https://github.com/nottheswimmer/pytago/
cd pytago
pip install -e .via setup.pygit clone https://github.com/nottheswimmer/pytago/
cd pytago
pip install .Usageusage: pytago [-h] [-o OUTFILE] INFILE

positional arguments:
  INFILE                read python code from INFILE

options:
  -h, --help            show this help message and exit
  -o OUTFILE, --out OUTFILE
                        write go code to OUTFILEExamplesAll examples presented here are used as tests for the program.listappendPythondefmain():a=[1,2,3]a.append(4)print(a)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]int{1,2,3}a=append(a,4)fmt.Println(a)}absPythondefmain():print(abs(-6))print(abs(3))if__name__=='__main__':main()Gopackagemainimport("fmt""math")funcmain(){fmt.Println(math.Abs(-6))fmt.Println(math.Abs(3))}helloworldPythondefmain():print("hello world")if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){fmt.Println("hello world")}inputPythondefmain():print("Hi, what's your name?")name=input("Name: ")print("Hi",name,"how old are you?")age=int(input("Age: "))print("Describe yourself in one sentence:")description=input()print("So your name is",name,"and you are",age,"years old, and your description is",'"'+description+'"')if__name__=='__main__':main()Gopackagemainimport("bufio""fmt""os""strconv""strings")funcmain(){fmt.Println("Hi, what's your name?")name:=func(msgstring)string{fmt.Print(msg)text,_:=bufio.NewReader(os.Stdin).ReadString('\n')returnstrings.ReplaceAll(text,"\n","")}("Name: ")fmt.Println("Hi",name,"how old are you?")age:=func()int{i,err:=strconv.ParseInt(func(msgstring)string{fmt.Print(msg)text,_:=bufio.NewReader(os.Stdin).ReadString('\n')returnstrings.ReplaceAll(text,"\n","")}("Age: "),10,64)iferr!=nil{panic(err)}returnint(i)}()fmt.Println("Describe yourself in one sentence:")description:=func()string{text,_:=bufio.NewReader(os.Stdin).ReadString('\n')returnstrings.ReplaceAll(text,"\n","")}()fmt.Println("So your name is",name,"and you are",age,"years old, and your description is","\""+description+"\"",)}randomnessPythonimportrandomdefmain():print(random.random())print(random.randrange(9000,10000))print(random.randint(9000,10000))items=["Hello",3,"Potato","Cake"]print(random.choice(items))random.shuffle(items)print(items)u=random.uniform(200,500)print(u)ifrandom.random()>0.5:print("50/50")names=['Kitchen','Animal','State','Tasty','Big','City','Fish','Pizza','Goat','Salty','Sandwich','Lazy','Fun']company_type=['LLC','Inc','Company','Corporation']company_cuisine=['Pizza','Bar Food','Fast Food','Italian','Mexican','American','Sushi Bar','Vegetarian']forxinrange(1,501):business={'name':names[random.randint(0,(len(names)-1))]+' '+names[random.randint(0,(len(names)-1))]+' '+company_type[random.randint(0,(len(company_type)-1))],'rating':random.randint(1,5),'cuisine':company_cuisine[random.randint(0,(len(company_cuisine)-1))]}print(business)if__name__=='__main__':main()Gopackagemainimport("fmt""math/rand""time")funcinit(){rand.Seed(time.Now().UnixNano())}funcmain(){fmt.Println(rand.Float64())fmt.Println(func(startint,stopint)int{n:=stop-startreturnrand.Intn(n)+start}(9000,10000))fmt.Println(func(startint,stopint)int{n:=stop-startreturnrand.Intn(n)+start}(9000,10000+1))items:=[]interface{}{"Hello",3,"Potato","Cake"}fmt.Println(items[rand.Intn(len(items))])rand.Shuffle(len(items),func(iint,jint){items[i],items[j]=items[j],items[i]})fmt.Println(items)u:=func(afloat64,bfloat64)float64{returnrand.Float64()*(b-a)+b}(200,500)fmt.Println(u)ifrand.Float64()>0.5{fmt.Println("50/50")}names:=[]string{"Kitchen","Animal","State","Tasty","Big","City","Fish","Pizza","Goat","Salty","Sandwich","Lazy","Fun",}company_type:=[]string{"LLC","Inc","Company","Corporation"}company_cuisine:=[]string{"Pizza","Bar Food","Fast Food","Italian","Mexican","American","Sushi Bar","Vegetarian",}forx:=1;x<501;x++{business:=map[string]interface{}{"name":names[func(startint,stopint)int{n:=stop-startreturnrand.Intn(n)+start}(0,len(names)-1+1)]+" "+names[func(startint,stopint)int{n:=stop-startreturnrand.Intn(n)+start}(0,len(names)-1+1)]+" "+company_type[func(startint,stopint)int{n:=stop-startreturnrand.Intn(n)+start}(0,len(company_type)-1+1)],"rating":func(startint,stopint)int{n:=stop-startreturnrand.Intn(n)+start}(1,5+1),"cuisine":company_cuisine[func(startint,stopint)int{n:=stop-startreturnrand.Intn(n)+start}(0,len(company_cuisine)-1+1)]}fmt.Println(business)}}string_methodsPythondefmain():lower="hello world"crazy="HeLLo WoRlD"upper="HELLO WORLD"lol="---LOL---"hearts="🧡💛💚💙💜"arabic_indic_digit="٠"whitespace="\v\f\t\r\n"s_hello_s=whitespace+lower+whitespacemultiline=lower+"\n"+crazy+"\r\n"+upper+"\n"print(crazy.capitalize())print(lower.endswith("world"))print(lower.find(" "))print(lower.find(" ",2))print(upper.find(" ",7,8))print(lower.index(" "))print(lower.index(" ",2))print(upper.index(" ",2,8))print(lower.isalnum())print(hearts.isascii())print(arabic_indic_digit.isdecimal())print(arabic_indic_digit.isdigit())print(lower.islower())print(arabic_indic_digit.isnumeric())print(hearts.isprintable())print(whitespace.isspace())print(upper.isupper())print(hearts.join([lower,crazy,upper]))print(crazy.lower())print(s_hello_s.lstrip()+"|")print(lower.lstrip("h"))print(lower.removeprefix("hello "))print(lower.removesuffix(" world"))print(lower.replace("world","gophers"))print(upper.replace("O","OOOOO",1))print(upper.rfind("O"))print(upper.rfind("O",1))print(upper.rfind("O",1,6))print(upper.rindex("O"))print(upper.rindex("O",1))print(upper.rindex("O",1,6))print(s_hello_s.rstrip()+"|")print(lower.rstrip("d"))print(lower.split())print(upper.split("L"))print(upper.split("L",1))print(multiline.splitlines())print(upper.startswith("HELLO"))print(s_hello_s.strip()+"|")print(lol.strip("-"))print(crazy.title())print(crazy.upper())if__name__=='__main__':main()Gopackagemainimport("bufio""errors""fmt""strings""unicode")funcmain(){lower:="hello world"crazy:="HeLLo WoRlD"upper:="HELLO WORLD"lol:="---LOL---"hearts:="🧡💛💚💙💜"arabic_indic_digit:="٠"whitespace:=" \u000b\f\t\r\n"s_hello_s:=whitespace+lower+whitespacemultiline:=lower+"\n"+crazy+"\r\n"+upper+"\n"fmt.Println(strings.ToUpper(crazy[0:1])+strings.ToLower(crazy[1:]))fmt.Println(strings.HasSuffix(lower,"world"))fmt.Println(strings.Index(lower," "))fmt.Println(func()int{ifr:=strings.Index(lower[2:]," ");r!=-1{returnr+2}return-1}())fmt.Println(func()int{ifr:=strings.Index(upper[7:8]," ");r!=-1{returnr+7}return-1}())fmt.Println(func(Xstring,substring)int{ifi:=strings.Index(X,sub);i!=-1{returni}panic(errors.New("ValueError: substring not found"))}(lower," "))fmt.Println(func(Xstring,substring,startint)int{ifi:=func()int{ifr:=strings.Index(X[start:],sub);r!=-1{returnr+start}return-1}();i!=-1{returni}panic(errors.New("ValueError: substring not found"))}(lower," ",2))fmt.Println(func(Xstring,substring,startint,endint)int{ifi:=func()int{ifr:=strings.Index(X[start:end],sub);r!=-1{returnr+start}return-1}();i!=-1{returni}panic(errors.New("ValueError: substring not found"))}(upper," ",2,8))fmt.Println(func(Xstring)bool{for_,r:=rangeX{if!((unicode.IsLetter(r)||unicode.IsDigit(r))&&(unicode.IsDigit(r)||unicode.IsNumber(r))){returnfalse}}returntrue}(lower))fmt.Println(func(Xstring)bool{for_,r:=rangeX{ifr>unicode.MaxASCII{returnfalse}}returntrue}(hearts))fmt.Println(func(Xstring)bool{for_,r:=rangeX{if!unicode.Is(unicode.Nd,r){returnfalse}}returnlen(X)!=0}(arabic_indic_digit))fmt.Println(func(Xstring)bool{for_,r:=rangeX{if!unicode.IsDigit(r){returnfalse}}returnlen(X)!=0}(arabic_indic_digit))fmt.Println(func(Xstring)bool{lower_found:=falsefor_,r:=rangeX{if!unicode.IsLower(r){if!unicode.IsSpace(r){returnfalse}}else{lower_found=true}}returnlower_found&&len(X)!=0}(lower))fmt.Println(func(Xstring)bool{for_,r:=rangeX{if!(unicode.IsDigit(r)||unicode.IsNumber(r)){returnfalse}}returnlen(X)!=0}(arabic_indic_digit))fmt.Println(func(Xstring)bool{for_,r:=rangeX{if!unicode.IsPrint(r){returnfalse}}returntrue}(hearts))fmt.Println(func(Xstring)bool{for_,r:=rangeX{if!unicode.IsSpace(r){returnfalse}}returnlen(X)!=0}(whitespace))fmt.Println(func(Xstring)bool{upper_found:=falsefor_,r:=rangeX{if!unicode.IsUpper(r){if!unicode.IsSpace(r){returnfalse}}else{upper_found=true}}returnupper_found&&len(X)!=0}(upper))fmt.Println(strings.Join([]string{lower,crazy,upper},hearts))fmt.Println(strings.ToLower(crazy))fmt.Println(strings.TrimLeftFunc(s_hello_s,unicode.IsSpace)+"|")fmt.Println(strings.TrimLeft(lower,"h"))fmt.Println(strings.TrimPrefix(lower,"hello "))fmt.Println(strings.TrimSuffix(lower," world"))fmt.Println(strings.ReplaceAll(lower,"world","gophers"))fmt.Println(strings.Replace(upper,"O","OOOOO",1))fmt.Println(strings.LastIndex(upper,"O"))fmt.Println(func()int{ifr:=strings.LastIndex(upper[1:],"O");r!=-1{returnr+1}return-1}())fmt.Println(func()int{ifr:=strings.LastIndex(upper[1:6],"O");r!=-1{returnr+1}return-1}())fmt.Println(func(Xstring,substring)int{ifi:=strings.LastIndex(X,sub);i!=-1{returni}panic(errors.New("ValueError: substring not found"))}(upper,"O"))fmt.Println(func(Xstring,substring,startint)int{ifi:=func()int{ifr:=strings.LastIndex(X[start:],sub);r!=-1{returnr+start}return-1}();i!=-1{returni}panic(errors.New("ValueError: substring not found"))}(upper,"O",1))fmt.Println(func(Xstring,substring,startint,endint)int{ifi:=func()int{ifr:=strings.LastIndex(X[start:end],sub);r!=-1{returnr+start}return-1}();i!=-1{returni}panic(errors.New("ValueError: substring not found"))}(upper,"O",1,6))fmt.Println(strings.TrimRightFunc(s_hello_s,unicode.IsSpace)+"|")fmt.Println(strings.TrimRight(lower,"d"))fmt.Println(strings.Fields(lower))fmt.Println(strings.Split(upper,"L"))fmt.Println(strings.SplitN(upper,"L",1))fmt.Println(func(sstring)(lines[]string){sc:=bufio.NewScanner(strings.NewReader(s))forsc.Scan(){lines=append(lines,sc.Text())}return}(multiline))fmt.Println(strings.HasPrefix(upper,"HELLO"))fmt.Println(strings.TrimSpace(s_hello_s)+"|")fmt.Println(strings.Trim(lol,"-"))fmt.Println(func(sstring)string{ws:=truevarsbstrings.Builderfor_,r:=ranges{ifunicode.IsSpace(r){ws=truesb.WriteRune(r)}elseifws{ws=falsesb.WriteRune(unicode.ToUpper(r))}else{sb.WriteRune(unicode.ToLower(r))}}returnsb.String()}(crazy))fmt.Println(strings.ToUpper(crazy))}list_methodsPythondefmain():l1=[1]l2=["hello","how","are","you?"]l3=[6.2,1.6,1.2,20.1]l1.append(2)print(l1)l1.extend([4,5])print(l1)l1.insert(3,3)print(l1)print(l1.index(2))print(l1.count(3))l1.remove(3)print(l1)whilel1:print(l1.pop())l3.clear()print(l3)l1.sort()print(l1)l2.sort()print(l2)l3.sort()print(l3)l3.sort(reverse=True)print(l3)l2.reverse()print(l2)l4=l2.copy()l4.pop()print(l4)print(l2)if__name__=='__main__':main()Gopackagemainimport("errors""fmt""reflect""sort")funcmain(){l1:=[]int{1}l2:=[]string{"hello","how","are","you?"}l3:=[]float64{6.2,1.6,1.2,20.1}l1=append(l1,2)fmt.Println(l1)l1=append(l1,[]int{4,5}...)fmt.Println(l1)l1=append(l1,3)copy(l1[3+1:],l1[3:])l1[3]=3fmt.Println(l1)fmt.Println(func()int{fori,val:=rangel1{ifval==2{returni}}panic(errors.New("ValueError: element not found"))}())fmt.Println(func()int{n:=0for_,v:=rangel1{ifv==3{n+=1}}returnn}())func(s*[]int,xint){fori,val:=range*s{ifreflect.DeepEqual(val,x){*s=append((*s)[:i],(*s)[i+1:]...)return}}panic(errors.New("ValueError: element not found"))}(&l1,3)fmt.Println(l1)forlen(l1)!=0{fmt.Println(func(s*[]int)int{i:=len(*s)-1popped:=(*s)[i]*s=(*s)[:i]returnpopped}(&l1))}l3=nilfmt.Println(l3)sort.Ints(l1)fmt.Println(l1)sort.Strings(l2)fmt.Println(l2)sort.Float64s(l3)fmt.Println(l3)sort.Sort(sort.Reverse(sort.Float64Slice(l3)))fmt.Println(l3)func(arr[]string){fori,j:=0,len(arr)-1;i<j;i,j=i+1,j-1{arr[i],arr[j]=arr[j],arr[i]}}(l2)fmt.Println(l2)l4:=func(s*[]string)(tmp[]string){tmp=append(tmp,*s...)return}(&l2)func(s*[]string)string{i:=len(*s)-1popped:=(*s)[i]*s=(*s)[:i]returnpopped}(&l4)fmt.Println(l4)fmt.Println(l2)}set_methodsPythondefmain():a={1,2,3,4}b={4,5,6}b.add(7)print(a.union(b))print(a.intersection(b))print(a.difference(b))print(a.symmetric_difference(b))print(a.issubset(b))print(a.issuperset(b))if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=map[int]struct{}{1:{},2:{},3:{},4:{}}b:=map[int]struct{}{4:{},5:{},6:{}}b[7]=struct{}{}fmt.Println(func(s1map[int]struct{},s2map[int]struct{})map[interface{}]struct{}{union:=map[interface{}]struct{}{}forelt:=ranges1{union[elt]=struct{}{}}forelt:=ranges2{union[elt]=struct{}{}}returnunion}(a,b))fmt.Println(func(s1map[int]struct{},s2map[int]struct{})map[interface{}]struct{}{intersection:=map[interface{}]struct{}{}forelt:=ranges1{iffunc()bool{_,ok:=s2[elt]returnok}(){intersection[elt]=struct{}{}}}returnintersection}(a,b))fmt.Println(func(s1map[int]struct{},s2map[int]struct{})map[interface{}]struct{}{difference:=map[interface{}]struct{}{}forelt:=ranges1{if!func()bool{_,ok:=s2[elt]returnok}(){difference[elt]=struct{}{}}}returndifference}(a,b))fmt.Println(func(s1map[int]struct{},s2map[int]struct{})map[interface{}]struct{}{symmetric_difference:=map[interface{}]struct{}{}forelt:=ranges1{if!func()bool{_,ok:=s2[elt]returnok}(){symmetric_difference[elt]=struct{}{}}}forelt:=ranges2{if!func()bool{_,ok:=s1[elt]returnok}(){symmetric_difference[elt]=struct{}{}}}returnsymmetric_difference}(a,b))fmt.Println(func(s1map[int]struct{},s2map[int]struct{})bool{forelt:=ranges1{if!func()bool{_,ok:=s2[elt]returnok}(){returnfalse}}returntrue}(a,b))fmt.Println(func(s1map[int]struct{},s2map[int]struct{})bool{forelt:=ranges2{if!func()bool{_,ok:=s1[elt]returnok}(){returnfalse}}returntrue}(a,b))}global_codePythonA=[1,2,3]fori,xinenumerate(A):A[i]+=xB=A[0]C=A[0]D:int=3whileC<A[2]:C+=1ifC==A[2]:print('True')defmain():print("Main started")print(A)print(B)print(C)print(D)if__name__=='__main__':main()Gopackagemainimport"fmt"var(A=[]int{1,2,3}BintCintDint)funcinit(){fori,x:=rangeA{A[i]+=x}B=A[0]C=A[0]D=3forC<A[2]{C+=1}ifC==A[2]{fmt.Println("True")}}funcmain(){fmt.Println("Main started")fmt.Println(A)fmt.Println(B)fmt.Println(C)fmt.Println(D)}boolnumcomparePythondefmain():print(1==True)print(1==False)print(0==True)print(0==False)print()print(1.==True)print(1.==False)print(0.==True)print(0.==False)print()print(1+0j==True)print(1+0j==False)print(0+0j==True)print(0+0j==False)print()print(2==True)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){fmt.Println(1==1)fmt.Println(1==0)fmt.Println(0==1)fmt.Println(0==0)fmt.Println()fmt.Println(1.0==1)fmt.Println(1.0==0)fmt.Println(0.0==1)fmt.Println(0.0==0)fmt.Println()fmt.Println(1+0.0i==1)fmt.Println(1+0.0i==0)fmt.Println(0+0.0i==1)fmt.Println(0+0.0i==0)fmt.Println()fmt.Println(2==1)}addPythondefmain():print(add(2,2))defadd(a:int,b:int)->int:returna+bif__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){fmt.Println(add(2,2))}funcadd(aint,bint)int{returna+b}exponentsPythondefmain():print(2**8)if__name__=='__main__':main()Gopackagemainimport("fmt""math")funcmain(){fmt.Println(math.Pow(2,8))}variablesPythondefmain():a=3b=7a=a+bprint(a+b)another_scope()defanother_scope():a=1b=12a=a+bprint(a+b)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=3b:=7a=a+bfmt.Println(a+b)another_scope()}funcanother_scope(){a:=1b:=12a=a+bfmt.Println(a+b)}floatsPythondefmain():a=7b=3c=4.5print(a/b)print(a//b)print(a/c)print(a//c)print(a+b)print(a+c)if__name__=='__main__':main()Gopackagemainimport("fmt""math")funcmain(){a:=7b:=3c:=4.5fmt.Println(float64(a)/float64(b))fmt.Println(a/b)fmt.Println(float64(a)/c)fmt.Println(math.Floor(float64(a)/c))fmt.Println(a+b)fmt.Println(float64(a)+c)}numlistPythondefmain():a=[1,2,3]print(a[0])print(a[1])print(a[2])a.append(4)print(a[3])a+=[5,6,7]a=a+[8,9,10]print(a[4])print(a[-1])if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]int{1,2,3}fmt.Println(a[0])fmt.Println(a[1])fmt.Println(a[2])a=append(a,4)fmt.Println(a[3])a=append(a,[]int{5,6,7}...)a=append(a,[]int{8,9,10}...)fmt.Println(a[4])fmt.Println(a[len(a)-1])}loopsPythondefmain():a=[1,2,3]forvina:print(v)fori,vinenumerate(a):print(i+v)foriinrange(5):print(i)foriinrange(10,15):print(i)foriinrange(10,15,2):print(i)forjinrange(15,10,-1):print(j)forjinrange(15,10,-2):print(j)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]int{1,2,3}for_,v:=rangea{fmt.Println(v)}fori,v:=rangea{fmt.Println(i+v)}fori:=0;i<5;i++{fmt.Println(i)}fori:=10;i<15;i++{fmt.Println(i)}fori:=10;i<15;i+=2{fmt.Println(i)}forj:=15;j>10;j--{fmt.Println(j)}forj:=15;j>10;j-=2{fmt.Println(j)}}stringsPythondefmain():a="hello"b="world"c=a+" "+bprint(c)print(double_it(c))print(c[1])print(c[1:6])defdouble_it(c:str)->str:returnc+cif__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:="hello"b:="world"c:=a+" "+bfmt.Println(c)fmt.Println(double_it(c))fmt.Println(string(c[1]))fmt.Println(c[1:6])}funcdouble_it(cstring)string{returnc+c}logicalPythondefmain():a=Trueb=Falseprint(a)print(b)print(aandb)print(aorb)print(nota)print(notb)print(aandnotb)print(aornotb)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=trueb:=falsefmt.Println(a)fmt.Println(b)fmt.Println(a&&b)fmt.Println(a||b)fmt.Println(!a)fmt.Println(!b)fmt.Println(a&&!b)fmt.Println(a||!b)}mathsPythonimportmathdefmain():print(math.sin(3))print(math.cosh(3))print(math.pi)print(math.acosh(6))print(math.atan2(4,7))if__name__=='__main__':main()Gopackagemainimport("fmt""math")funcmain(){fmt.Println(math.Sin(3))fmt.Println(math.Cosh(3))fmt.Println(math.Pi)fmt.Println(math.Acosh(6))fmt.Println(math.Atan2(4,7))}requestslibPythonimportrequestsdefmain():resp=requests.get("http://tour.golang.org/welcome/1")print(resp.text)if__name__=='__main__':main()Gopackagemainimport("fmt""io/ioutil""net/http")funcmain(){resp,err:=http.Get("http://tour.golang.org/welcome/1")iferr!=nil{panic(err)}deferresp.Body.Close()fmt.Println(func()string{body,err:=ioutil.ReadAll(resp.Body)iferr!=nil{panic(err)}returnstring(body)}())}conditionalsPythondefmain():a=7b=add(a,-2)ifa>b:print("It's bigger")elifa==b:print("They're equal")else:print("It's smaller")defadd(a:int,b:int)->int:returna+bif__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=7b:=add(a,-2)ifa>b{fmt.Println("It's bigger")}elseifa==b{fmt.Println("They're equal")}else{fmt.Println("It's smaller")}}funcadd(aint,bint)int{returna+b}fstringsPythondefmain():name="Michael"age=24print(f"My name is{name}and I am{age}years old. Later this year I'll be{age+1}!")if__name__=='__main__':main()Gopackagemainimport("bytes""fmt""text/template")funcmain(){name:="Michael"age:=24fmt.Println(func()string{varbufbytes.Buffererr:=template.Must(template.New("f").Parse("My name is {{.name}} and I am {{.age}} years old. Later this year I'll be {{.expr1}}!")).Execute(&buf,map[string]interface{}{"name":name,"age":age,"expr1":age+1})iferr!=nil{panic(err)}returnbuf.String()}())}nestedfstringsPythondefmain():name="Michael"age=24print(f"My name is{name}and I am{age}years old. Later this year I'll be{f'{age+1}'}!")if__name__=='__main__':main()Gopackagemainimport("bytes""fmt""text/template")funcmain(){name:="Michael"age:=24fmt.Println(func()string{varbufbytes.Buffererr:=template.Must(template.New("f").Parse("My name is {{.name}} and I am {{.age}} years old. Later this year I'll be {{.expr1}}!")).Execute(&buf,map[string]interface{}{"name":name,"age":age,"expr1":func()string{varbufbytes.Buffererr:=template.Must(template.New("f").Parse("{{.expr1}}")).Execute(&buf,map[string]interface{}{"expr1":age+1})iferr!=nil{panic(err)}returnbuf.String()}()})iferr!=nil{panic(err)}returnbuf.String()}())}dictionaryPythondefmain():a={"name":"Michael","age":24,1337:True}print(a)a["sleepiness"]=1.0dela[1337]fork,vina.items():print(k)print(v)Gopackagemainimport"fmt"funcmain(){a:=map[interface{}]interface{}{"name":"Michael","age":24,1337:true}fmt.Println(a)a["sleepiness"]=1.0delete(a,1337)fork,v:=rangea{fmt.Println(k)fmt.Println(v)}}writefilePythondefmain():withopen("file_1.tmp","w+")asf:f.write("This file was created in w+ mode\n")withopen("file_2.tmp","x")asf:f.write("This file was created by x mode\n")withopen("file_2.tmp","w")asf:f.write("This file was created by x mode and then overwritten in w mode\n")withopen("file_2.tmp","a")asf:f.write("... And then appended to in a mode\n")withopen("file_2.tmp","r")asf:print(f.read())withopen("file_3.tmp","a+")asf:f.write("This file was created in a+ mode\n")withopen("file_4.tmp","x+")asf:f.write("This file was created by x+ mode\n")withopen("file_5.tmp","wb+")asf:f.write(b"This file was created in wb+ mode\n")withopen("file_6.tmp","xb")asf:f.write(b"This file was created by xb mode\n")withopen("file_6.tmp","wb")asf:f.write(b"This file was created by xb mode and then overwritten in wb mode\n")withopen("file_6.tmp","ab")asf:f.write(b"... And then appended to in ab mode\n")withopen("file_6.tmp","rb")asf:print(f.read().decode())withopen("file_7.tmp","ab+")asf:f.write(b"This file was created in ab+ mode\n")withopen("file_8.tmp","xb+")asf:f.write(b"This file was created by xb+ mode\n")if__name__=='__main__':main()Gopackagemainimport("fmt""io/ioutil""os")funcmain(){func(){f:=func()*os.File{f,err:=os.OpenFile("file_1.tmp",os.O_RDWR|os.O_TRUNC|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.WriteString("This file was created in w+ mode\n")iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_2.tmp",os.O_WRONLY|os.O_EXCL|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.WriteString("This file was created by x mode\n")iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_2.tmp",os.O_WRONLY|os.O_TRUNC,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.WriteString("This file was created by x mode and then overwritten in w mode\n",)iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_2.tmp",os.O_WRONLY|os.O_APPEND|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.WriteString("... And then appended to in a mode\n")iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_2.tmp",os.O_RDONLY,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()fmt.Println(func()string{content,err:=ioutil.ReadAll(f)iferr!=nil{panic(err)}returnstring(content)}())}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_3.tmp",os.O_RDWR|os.O_APPEND|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.WriteString("This file was created in a+ mode\n")iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_4.tmp",os.O_RDWR|os.O_EXCL|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.WriteString("This file was created by x+ mode\n")iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_5.tmp",os.O_RDWR|os.O_TRUNC|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.Write([]byte("This file was created in wb+ mode\n"))iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_6.tmp",os.O_WRONLY|os.O_EXCL|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.Write([]byte("This file was created by xb mode\n"))iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_6.tmp",os.O_WRONLY|os.O_TRUNC,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.Write([]byte("This file was created by xb mode and then overwritten in wb mode\n"),)iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_6.tmp",os.O_WRONLY|os.O_APPEND|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.Write([]byte("... And then appended to in ab mode\n"))iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_6.tmp",os.O_RDONLY,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()fmt.Println(string(func()[]byte{content,err:=ioutil.ReadAll(f)iferr!=nil{panic(err)}returncontent}()))}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_7.tmp",os.O_RDWR|os.O_APPEND|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.Write([]byte("This file was created in ab+ mode\n"))iferr!=nil{panic(err)}returnn}()}()func(){f:=func()*os.File{f,err:=os.OpenFile("file_8.tmp",os.O_RDWR|os.O_EXCL|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()func()int{n,err:=f.Write([]byte("This file was created by xb+ mode\n"))iferr!=nil{panic(err)}returnn}()}()}passPythondefmain():passif__name__=='__main__':main()Gopackagemainfuncmain(){}ellipsisPythondefmain():...if__name__=='__main__':main()Gopackagemainfuncmain(){}missingreturntypePythondefmain():print(add(1,3))defadd(a:int,b:int):returna+bGopackagemainimport"fmt"funcmain(){fmt.Println(add(1,3))}funcadd(aint,bint)int{returna+b}continuestmtPythondefmain():foriinrange(10):ifi<3ori>7:continueprint(i)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){fori:=0;i<10;i++{ifi<3||i>7{continue}fmt.Println(i)}}breakstmtPythondefmain():foriinrange(10):ifi>7:breakprint(i)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){fori:=0;i<10;i++{ifi>7{break}fmt.Println(i)}}whileloopPythondefmain():i=0whileTrue:print(i)i+=1ifi>5:breakj=10whilej<100:print(j)j+=10while1:print(j+i)breakwhile0.1:print(j+i)breakwhile0:print("This never executes")while0.0:print("This never executes")whileNone:print("This never executes")whileFalse:print("This never executes")while"":print("This never executes")while"hi":print("This executes")breakif__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){i:=0for{fmt.Println(i)i+=1ifi>5{break}}j:=10forj<100{fmt.Println(j)j+=10}for{fmt.Println(j+i)break}for{fmt.Println(j+i)break}forfalse{fmt.Println("This never executes")}forfalse{fmt.Println("This never executes")}forfalse{fmt.Println("This never executes")}forfalse{fmt.Println("This never executes")}forfalse{fmt.Println("This never executes")}for{fmt.Println("This executes")break}}setsPythondefmain():s={1,2,3}x=1print(len(s))print(xins)print(xnotins)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){s:=map[int]struct{}{1:{},2:{},3:{}}x:=1fmt.Println(len(s))fmt.Println(func()bool{_,ok:=s[x]returnok}())fmt.Println(!func()bool{_,ok:=s[x]returnok}())}containsPythondefmain():a=[1,2,3]print(1ina)print(4ina)print(5notina)b="hello world"print("hello"inb)print("Hello"notinb)c={"hello":1,"world":2}print("hello"inc)print("Hello"notinc)d=b'hello world'print(b'hello'ind)print(b'Hello'notind)e={1,2,3,"hello"}print("hello"ine)print(4notine)if__name__=='__main__':main()Gopackagemainimport("bytes""fmt""strings")funcmain(){a:=[]int{1,2,3}fmt.Println(func()int{fori,v:=rangea{ifv==1{returni}}return-1}()!=-1)fmt.Println(func()int{fori,v:=rangea{ifv==4{returni}}return-1}()!=-1)fmt.Println(func()int{fori,v:=rangea{ifv==5{returni}}return-1}()==-1)b:="hello world"fmt.Println(strings.Contains(b,"hello"))fmt.Println(!strings.Contains(b,"Hello"))c:=map[string]int{"hello":1,"world":2}fmt.Println(func()bool{_,ok:=c["hello"]returnok}())fmt.Println(!func()bool{_,ok:=c["Hello"]returnok}())d:=[]byte("hello world")fmt.Println(bytes.Contains(d,[]byte("hello")))fmt.Println(!bytes.Contains(d,[]byte("Hello")))e:=map[interface{}]struct{}{1:{},2:{},3:{},"hello":{}}fmt.Println(func()bool{_,ok:=e["hello"]returnok}())fmt.Println(!func()bool{_,ok:=e[4]returnok}())}tryexceptPythondefmain():a=[1,2,3]forindexinrange(4):try:print(a[index])ifindex==1:raiseValueError(index)exceptIndexError:print("That index was out of bounds")except(NotImplementedError,RuntimeError):print("This won't actually happen...")exceptExceptionase:print("Some other exception occurred")print(e)if__name__=='__main__':main()Gopackagemainimport("fmt""strings")funcmain(){a:=[]int{1,2,3}forindex:=0;index<4;index++{func(){deferfunc(){ifr:=recover();r!=nil{iferr,ok:=r.(error);ok{ifstrings.HasPrefix(err.Error(),"IndexError")||strings.HasPrefix(err.Error(),"runtime error: index out of range"){fmt.Println("That index was out of bounds")return}elseifstrings.HasPrefix(err.Error(),"NotImplementedError")||(strings.HasPrefix(err.Error(),"RuntimeError")||strings.HasPrefix(err.Error(),"runtime error")){fmt.Println("This won't actually happen...")return}else{e:=errfmt.Println("Some other exception occurred")fmt.Println(e)return}}panic(r)}}()fmt.Println(a[index])ifindex==1{panic(fmt.Errorf("ValueError: %v",index))}}()}}tryfinallyPythondefmain():a=[1,2,3]forindexinrange(4):try:print(a[index])exceptException:passfinally:print("Finished an iteration")forindexinrange(4):try:print(a[index])finally:print("Finished an iteration")if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]int{1,2,3}forindex:=0;index<4;index++{func(){deferfunc(){fmt.Println("Finished an iteration")}()deferfunc(){ifr:=recover();r!=nil{if_,ok:=r.(error);ok{return}panic(r)}}()fmt.Println(a[index])}()}forindex:=0;index<4;index++{func(){deferfunc(){fmt.Println("Finished an iteration")}()fmt.Println(a[index])}()}}assertsPythondefmain():assert1+1==2assertTrueassert1+3==5,"Math must be broken"if__name__=='__main__':main()Gopackagemainimport("errors""fmt")funcmain(){if!(1+1==2){panic(errors.New("AssertionError"))}if!true{panic(errors.New("AssertionError"))}if!(1+3==5){panic(fmt.Errorf("AssertionError: %v","Math must be broken"))}}classesPythonclassWelcome:greeting:strinstructions:list[str]def__init__(self,greeting:str,instructions:list[str])->None:self.greeting=greetingself.instructions=instructionsdefgreet(self):print(self.greeting)forinstructioninself.instructions:print(instruction)defmain():welcome=Welcome("Hello World",["This is a class!","Support will be limited at first.","Still, I hope you'll find them useful."])welcome.greet()if__name__=='__main__':main()Gopackagemainimport"fmt"typeWelcomestruct{greetingstringinstructions[]string}funcNewWelcome(greetingstring,instructions[]string)(self*Welcome){self=new(Welcome)self.greeting=greetingself.instructions=instructionsreturn}func(self*Welcome)greet(){fmt.Println(self.greeting)for_,instruction:=rangeself.instructions{fmt.Println(instruction)}}funcmain(){welcome:=NewWelcome("Hello World",[]string{"This is a class!","Support will be limited at first.","Still, I hope you'll find them useful.",},)welcome.greet()}globalsPythonSITE="https://www.google.com/"NAME=["Michael","Wayne","Phelps"]KEYS={1:2,3:4}AGE=1000BIRTH_YEAR=2050defmain():globalAGEprint(SITE)print(NAME)print(BIRTH_YEAR)print(KEYS)print(AGE)AGE=20# This should use the variable from the global scopeother_1()print(AGE)other_2()defother_1():AGE=200# This should declare a new variable ageprint(AGE)defother_2():print(AGE)# This should still be able to access the globalif__name__=='__main__':main()Gopackagemainimport"fmt"var(SITE="https://www.google.com/"NAME=[]string{"Michael","Wayne","Phelps"}KEYS=map[int]int{1:2,3:4}AGE=1000BIRTH_YEAR=2050)funcmain(){fmt.Println(SITE)fmt.Println(NAME)fmt.Println(BIRTH_YEAR)fmt.Println(KEYS)fmt.Println(AGE)AGE=20other_1()fmt.Println(AGE)other_2()}funcother_1(){AGE:=200fmt.Println(AGE)}funcother_2(){fmt.Println(AGE)}asyncawaitPythonimportasyncioasyncdefmyAsyncFunction()->int:awaitasyncio.sleep(2)return2asyncdefmain():r=awaitmyAsyncFunction()print(r)if__name__=='__main__':asyncio.run(main())Gopackagemainimport("fmt""time")funcmyAsyncFunction()<-chanint{r:=make(chanint)gofunc(){deferclose(r)time.Sleep(time.Second*2)r<-2}()returnr}funcmain(){r:=<-myAsyncFunction()fmt.Println(r)}yieldsPythondefmain():my_gen=gen()forxinmy_gen:print("Received next number!")print(x)defgen():print("Yielding next number...")yield1print("Yielding next number...")yield2print("Yielding next number...")yield3if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){my_gen:=gen()forx,ok:=<-my_gen();ok;x,ok=<-my_gen(){fmt.Println("Received next number!")fmt.Println(x)}}funcgen()func()<-chanint{wait:=make(chanstruct{})yield:=make(chanint)gofunc(){deferclose(yield)<-waitfmt.Println("Yielding next number...")yield<-1<-waitfmt.Println("Yielding next number...")yield<-2<-waitfmt.Println("Yielding next number...")yield<-3<-wait}()returnfunc()<-chanint{wait<-struct{}{}returnyield}}isvseqlPythondefmain():a=[1,2,3]b=[1,2,3]print(a==b)# Trueprint(a!=b)# Falseprint(aisa)# Trueprint(aisb)# Falseprint(aisnota)# Falseprint(aisnotb)# Trueif__name__=='__main__':main()Gopackagemainimport("fmt""reflect")funcmain(){a:=[]int{1,2,3}b:=[]int{1,2,3}fmt.Println(reflect.DeepEqual(a,b))fmt.Println(!reflect.DeepEqual(a,b))fmt.Println(&a==&a)fmt.Println(&a==&b)fmt.Println(&a!=&a)fmt.Println(&a!=&b)}matchcasePythondefmain():a=1matcha:case1:print(1)case2:print(2)case3:print(3)matcha:case4:print("Never gonna happen")case_:print("Nice, defaults!")if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=1switcha{case1:fmt.Println(1)case2:fmt.Println(2)case3:fmt.Println(3)}switcha{case4:fmt.Println("Never gonna happen")default:fmt.Println("Nice, defaults!")}}defaultargsPythondefmain():a=increment(1)print(a)b=increment(a,2)print(b)c=increment(a,decrement=True,amount=3)print(c)defincrement(n:int,amount:int=1,decrement:bool=False)->int:ifdecrement:returnn-amountreturnn+amountif__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=increment(1,1,false)fmt.Println(a)b:=increment(a,2,false)fmt.Println(b)c:=increment(a,3,true)fmt.Println(c)}funcincrement(nint,amountint,decrementbool)int{ifdecrement{returnn-amount}returnn+amount}walrusPythondefmain():if(a:=some_func())==7:print(a)forxin(y:=[1,2,3]):print(y)print(x)matchj:=5:case5:print(j)while(t1:=thing_1())<5and(t2:=thing_2())==3:print(t1)print(t2)defsome_func():return7call_count=0defthing_1():globalcall_countcall_count+=1returncall_countdefthing_2():return3if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){ifa:=some_func();a==7{fmt.Println(a)}y:=[]int{1,2,3}for_,x:=rangey{fmt.Println(y)fmt.Println(x)}switchj:=5;j{case5:fmt.Println(j)}fort1,t2:=thing_1(),thing_2();t1<5&&t2==3;t1,t2=thing_1(),thing_2(){fmt.Println(t1)fmt.Println(t2)}}funcsome_func()int{return7}varcall_count=0functhing_1()int{call_count+=1returncall_count}functhing_2()int{return3}truthinessPythondefmain():ifa:=1:print(a)ifc:="":print(c)ifd:=b"":print(d)ife:="Hello":print(e)iff:=b"Goodbye":print(f)ifg:=1.0:print(g)ifh:=1j:print(h)ifi:=0.0:print(i)ifj:=0j:print(j)ifk:=[]:print(k)ifl:=[1,2,3]:print(l)ifm:=True:print(m)ifn:=False:print(n)ifo:=():print(o)ifp:=(1,2,3):print(p)ifq:=set():print(q)ifr:={1,2,3}:print(r)ifs:={}:print(s)ift:={1:2}:print(t)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){ifa:=1;a!=0{fmt.Println(a)}ifc:="";len(c)!=0{fmt.Println(c)}ifd:=[]byte("");len(d)!=0{fmt.Println(d)}ife:="Hello";len(e)!=0{fmt.Println(e)}iff:=[]byte("Goodbye");len(f)!=0{fmt.Println(f)}ifg:=1.0;g!=0{fmt.Println(g)}ifh:=1.0i;h!=0{fmt.Println(h)}ifi:=0.0;i!=0{fmt.Println(i)}ifj:=0.0i;j!=0{fmt.Println(j)}ifk:=[]interface{}{};len(k)!=0{fmt.Println(k)}ifl:=[]int{1,2,3};len(l)!=0{fmt.Println(l)}ifm:=true;m{fmt.Println(m)}ifn:=false;n{fmt.Println(n)}ifo:=[0]interface{}{};len(o)!=0{fmt.Println(o)}ifp:=[3]int{1,2,3};len(p)!=0{fmt.Println(p)}ifq:=map[interface{}]struct{}{};len(q)!=0{fmt.Println(q)}ifr:=map[int]struct{}{1:{},2:{},3:{}};len(r)!=0{fmt.Println(r)}ifs:=map[interface{}]interface{}{};len(s)!=0{fmt.Println(s)}ift:=map[int]int{1:2};len(t)!=0{fmt.Println(t)}}minmaxPythondefmain():print(max([1,2,3]))print(min([1,2,3]))print(max("a","b","c"))print(min("a","b","c"))if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){fmt.Println(func()(mint){fori,e:=range[]int{1,2,3}{ifi==0||e>m{m=e}}return}())fmt.Println(func()(mint){fori,e:=range[]int{1,2,3}{ifi==0||e<m{m=e}}return}())fmt.Println(func()(mstring){fori,e:=range[]string{"a","b","c"}{ifi==0||e>m{m=e}}return}())fmt.Println(func()(mstring){fori,e:=range[]string{"a","b","c"}{ifi==0||e<m{m=e}}return}())}sumPythondefmain():print(sum([1,2,3]))print(sum([1.5,2.6,3.7]))print(sum([1j,2j,3j]))if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){fmt.Println(func()(sint){for_,e:=range[]int{1,2,3}{s+=e}return}())fmt.Println(func()(sfloat64){for_,e:=range[]float64{1.5,2.6,3.7}{s+=e}return}())fmt.Println(func()(scomplex128){for_,e:=range[]complex128{1.0i,2.0i,3.0i}{s+=e}return}())}reversePythondefmain():a=[1,2,3,4,5]forxinreversed(a):print(x)forxina:print(x)a.reverse()forxina:print(x)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]int{1,2,3,4,5}for_,x:=rangefunc(arr[]int)[]int{arr2:=make([]int,len(arr))fori,e:=rangearr{arr2[len(arr)-i-1]=e}returnarr2}(a){fmt.Println(x)}for_,x:=rangea{fmt.Println(x)}func(arr[]int){fori,j:=0,len(arr)-1;i<j;i,j=i+1,j-1{arr[i],arr[j]=arr[j],arr[i]}}(a)for_,x:=rangea{fmt.Println(x)}}listcompPythondefmain():a=[xforxinrange(10)]b=[xforxinrange(10)ifx%2==0]c=[xifx%2==0else777forxinrange(10)]d=[xfori,xinenumerate(c)ifi%2==0ifi%3==1]e=[(x,y)forxincforyind]f=[(x,y)forxincforyinnext_five_numbers_times_two(x)]g=[(i,j)foriinrange(10)forjinrange(i)]print(a)print(b)print(c)print(d)print(e)print(f)print(g)defnext_five_numbers_times_two(a:int)->list[int]:return[(a+i)*2foriinrange(1,6)]if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=func()(elts[]int){forx:=0;x<10;x++{elts=append(elts,x)}return}()b:=func()(elts[]int){forx:=0;x<10;x++{ifx%2==0{elts=append(elts,x)}}return}()c:=func()(elts[]int){forx:=0;x<10;x++{elts=append(elts,func()int{ifx%2==0{returnx}return777}())}return}()d:=func()(elts[]int){fori,x:=rangec{ifi%2==0{ifi%3==1{elts=append(elts,x)}}}return}()e:=func()(elts[][2]int){for_,x:=rangec{for_,y:=ranged{elts=append(elts,[2]int{x,y})}}return}()f:=func()(elts[][2]int){for_,x:=rangec{for_,y:=rangenext_five_numbers_times_two(x){elts=append(elts,[2]int{x,y})}}return}()g:=func()(elts[][2]int){fori:=0;i<10;i++{forj:=0;j<i;j++{elts=append(elts,[2]int{i,j})}}return}()fmt.Println(a)fmt.Println(b)fmt.Println(c)fmt.Println(d)fmt.Println(e)fmt.Println(f)fmt.Println(g)}funcnext_five_numbers_times_two(aint)[]int{returnfunc()(elts[]int){fori:=1;i<6;i++{elts=append(elts,(a+i)*2)}return}()}dictcompPythondefmain():a={(x,y):x*yforxinrange(20)foryinrange(5)ifx*y!=0}fork,vina.items():print(k,v)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=func()(dmap[[2]int]int){d=make(map[[2]int]int)forx:=0;x<20;x++{fory:=0;y<5;y++{ifx*y!=0{d[[2]int{x,y}]=x*y}}}return}()fork,v:=rangea{fmt.Println(k,v)}}setcompPythondefmain():a={xforxinrange(20,39)}b={(x,y)forxinrange(100)foryinrange(x,x+5)ifx%39ina}print(a)print(b)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=func()(smap[int]struct{}){s=make(map[int]struct{})forx:=20;x<39;x++{s[x]=struct{}{}}return}()b:=func()(smap[[2]int]struct{}){s=make(map[[2]int]struct{})forx:=0;x<100;x++{fory:=x;y<x+5;y++{iffunc()bool{_,ok:=a[x%39]returnok}(){s[[2]int{x,y}]=struct{}{}}}}return}()fmt.Println(a)fmt.Println(b)}generatorexpPythondefmain():a=((x,y)forxinrange(5)foryinrange(x))b=(wforwin("Where","Are","You?","And","I'm","So","Sorry"))forlinb:print(l,next(a))forrestina:print(rest)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=func()func()<-chan[2]int{wait:=make(chanstruct{})yield:=make(chan[2]int)gofunc(){deferclose(yield)<-waitforx:=0;x<5;x++{fory:=0;y<x;y++{yield<-[2]int{x,y}<-wait}}}()returnfunc()<-chan[2]int{wait<-struct{}{}returnyield}}()b:=func()func()<-chanstring{wait:=make(chanstruct{})yield:=make(chanstring)gofunc(){deferclose(yield)<-waitfor_,w:=range[7]string{"Where","Are","You?","And","I'm","So","Sorry"}{yield<-w<-wait}}()returnfunc()<-chanstring{wait<-struct{}{}returnyield}}()forl,ok:=<-b();ok;l,ok=<-b(){fmt.Println(l,<-a())}forrest,ok:=<-a();ok;rest,ok=<-a(){fmt.Println(rest)}}ternaryPythondefmain():a=1ifTrueelse2print(a)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=func()int{iftrue{return1}return2}()fmt.Println(a)}isinstancePythondefmain():a=["a",1,"5",2.3,1.2j]some_condition=Trueforxina:ifisinstance(x,(str,float)):print("String or float!")elifisinstance(x,int):print("Integer!")else:print("Dunno!")print(":)")ifisinstance(x,str)andsome_condition:print("String")elifisinstance(x,int):print("Integer!")else:print("Dunno!!")print(":O")if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]interface{}{"a",1,"5",2.3,1.2i}some_condition:=truefor_,x:=rangea{switchx.(type){casestring,float64:fmt.Println("String or float!")caseint:fmt.Println("Integer!")default:fmt.Println("Dunno!")fmt.Println(":)")}iffunc()bool{switchx.(type){casestring:returntrue}returnfalse}()&&some_condition{fmt.Println("String")}else{switchx.(type){caseint:fmt.Println("Integer!")default:fmt.Println("Dunno!!")fmt.Println(":O")}}}}zipPythondefmain():x=[1,2,3]y=[4,5,6]zipped=zip(x,y)forpairinzipped:print(pair)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){x:=[]int{1,2,3}y:=[]int{4,5,6}zipped:=func()func()<-chan[2]int{wait:=make(chanstruct{})yield:=make(chan[2]int)gofunc(){deferclose(yield)<-waitfori,e:=rangex{ifi>=len(y){break}yield<-[2]int{e,y[i]}<-wait}}()returnfunc()<-chan[2]int{wait<-struct{}{}returnyield}}()forpair,ok:=<-zipped();ok;pair,ok=<-zipped(){fmt.Println(pair)}}mapPythondefmain():a=[1,2,3]b=map(increment,a)forvalueinb:print(value)defincrement(n:int)->int:returnn+1if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]int{1,2,3}b:=func()func()<-chanint{wait:=make(chanstruct{})yield:=make(chanint)gofunc(){deferclose(yield)<-waitfor_,x:=rangea{yield<-increment(x)<-wait}}()returnfunc()<-chanint{wait<-struct{}{}returnyield}}()forvalue,ok:=<-b();ok;value,ok=<-b(){fmt.Println(value)}}funcincrement(nint)int{returnn+1}reprPythondefmain():nums=[1,2,3,4,5,6,7,8,9]s=repr(nums)print(s+s)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){nums:=[]int{1,2,3,4,5,6,7,8,9}s:=fmt.Sprintf("%#v",nums)fmt.Println(s+s)}lambdafuncPythondefmain():f=lambdax:x*2forainrange(10):print((lambdax:x+1)(a)+f(a))if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){f:=func(xint)int{returnint(x)*2}fora:=0;a<10;a++{fmt.Println(func(xint)int{returnint(x)+1}(a)+f(a))}}timemodulePythonimporttimedefmain():print("Hello")time.sleep(3)print("... time!")if__name__=='__main__':main()Gopackagemainimport("fmt""time")funcmain(){fmt.Println("Hello")time.Sleep(3*time.Second)fmt.Println("... time!")}exitPythonimportsysdefmain():quit()quit(1)exit()exit(1)sys.exit()sys.exit(1)if__name__=='__main__':main()Gopackagemainimport"os"funcmain(){os.Exit(0)os.Exit(1)os.Exit(0)os.Exit(1)os.Exit(0)os.Exit(1)}retroactive_composite_typesPythondefmain():a=[]a.append(3)b=[]b+=ac={}c["hello"]=1d={}d[1]=2d["gonna_be_an_interface"]="yup"e=set()e.add(1)f=[[]]f[0].append(1)g={}g[(1,2)]=3h=[]h.append(1)h.append("hi")i={}i[1]="lol"i["2"]="lmao"print(a,b,c,d,e,f,g,h)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){a:=[]int{}a=append(a,3)b:=[]int{}b=append(b,a...)c:=map[string]int{}c["hello"]=1d:=map[interface{}]interface{}{}d[1]=2d["gonna_be_an_interface"]="yup"e:=map[int]struct{}{}e[1]=struct{}{}f:=[][]int{{}}f[0]=append(f[0],1)g:=map[[2]int]int{}g[[2]int{1,2}]=3h:=[]interface{}{}h=append(h,1)h=append(h,"hi")i:=map[interface{}]string{}i[1]="lol"i["2"]="lmao"fmt.Println(a,b,c,d,e,f,g,h)}isinstance_gives_type_assertionPythondefmain():stuff=[1,5,"hello",5,12,19,12.5,[1,2,3]]write_contents(stuff)items=["",0,1.1]forxinitems:ifisinstance(x,str):print("See? It's not used here so we don't have a type assertion")elifisinstance(x,int):print("This is very important because go's compiler will complain")else:print("You know, I wouldn't have to worry about this if we had something to remove unused initializations")defwrite_contents(contents):withopen("contents.txt","w+")asf:foritemincontents:ifisinstance(item,str):f.write("str: "+item+"\n")elifisinstance(item,int):f.write("int: "+str(item)+"\n")else:f.write("unknown: "+repr(item)+"\n")if__name__=='__main__':main()Gopackagemainimport("fmt""os")funcmain(){stuff:=[]interface{}{1,5,"hello",5,12,19,12.5,[]int{1,2,3}}write_contents(stuff)items:=[]interface{}{"",0,1.1}for_,x:=rangeitems{switchx.(type){casestring:fmt.Println("See? It's not used here so we don't have a type assertion")caseint:fmt.Println("This is very important because go's compiler will complain")default:fmt.Println("You know, I wouldn't have to worry about this if we had something to remove unused initializations")}}}funcwrite_contents(contents[]interface{}){f:=func()*os.File{f,err:=os.OpenFile("contents.txt",os.O_RDWR|os.O_TRUNC|os.O_CREATE,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=f.Close();err!=nil{panic(err)}}()for_,item:=rangecontents{switchitem:=item.(type){casestring:func()int{n,err:=f.WriteString("str: "+item+"\n")iferr!=nil{panic(err)}returnn}()caseint:func()int{n,err:=f.WriteString("int: "+fmt.Sprintf("%v",item)+"\n")iferr!=nil{panic(err)}returnn}()default:func()int{n,err:=f.WriteString("unknown: "+fmt.Sprintf("%#v",item)+"\n")iferr!=nil{panic(err)}returnn}()}}}fileloopPythondefmain():fh=open("file.txt")forlineinfh:print(line)fh.close()withopen("file2.txt")asfh2:forlineinfh2:print(line)withopen("file3.txt","rb")asfh3:forlinfh3:print(l)if__name__=='__main__':main()Gopackagemainimport("bufio""fmt""io""os")funcmain(){fh:=func()*os.File{f,err:=os.OpenFile("file.txt",os.O_RDONLY,0o777)iferr!=nil{panic(err)}returnf}()ifsc,line,err:=bufio.NewReader(fh),"",*new(error);true{for{line,err=sc.ReadString('\n')iferr!=nil&&(err==io.EOF&&len(line)==0||err!=io.EOF){break}fmt.Println(line)}iferr!=io.EOF{panic(err)}}iferr:=fh.Close();err!=nil{panic(err)}func(){fh2:=func()*os.File{f,err:=os.OpenFile("file2.txt",os.O_RDONLY,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=fh2.Close();err!=nil{panic(err)}}()ifsc,line,err:=bufio.NewReader(fh2),"",*new(error);true{for{line,err=sc.ReadString('\n')iferr!=nil&&(err==io.EOF&&len(line)==0||err!=io.EOF){break}fmt.Println(line)}iferr!=io.EOF{panic(err)}}}()func(){fh3:=func()*os.File{f,err:=os.OpenFile("file3.txt",os.O_RDONLY,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=fh3.Close();err!=nil{panic(err)}}()ifsc,l,err:=bufio.NewReader(fh3),[]byte{},*new(error);true{for{l,err=sc.ReadBytes('\n')iferr!=nil&&(err==io.EOF&&len(l)==0||err!=io.EOF){break}fmt.Println(l)}iferr!=io.EOF{panic(err)}}}()}unpackingPythondefmain():name="Michael Wayne Phelps"first,middle,last=name.split()x=[1,2,3]a,b,c=xd,e,f=4,5,6g,h,i=[7,8,9]print(first,middle,last,a,b,c,d,e,f,g,h,i)if__name__=='__main__':main()Gopackagemainimport("fmt""strings")funcmain(){name:="Michael Wayne Phelps"first,middle,last:=func(s[]string)(string,string,string){returns[0],s[1],s[2]}(strings.Fields(name))x:=[]int{1,2,3}a,b,c:=x[0],x[1],x[2]d,e,f:=4,5,6g,h,i:=7,8,9fmt.Println(first,middle,last,a,b,c,d,e,f,g,h,i)}cast_to_floatPythondefmain():num1=input('Enter first number: ')num2=input('Enter second number: ')sum=float(num1)+float(num2)print("The sum of",num1,"and",num2,"is",sum)if__name__=='__main__':main()Gopackagemainimport("bufio""fmt""os""strconv""strings")funcmain(){num1:=func(msgstring)string{fmt.Print(msg)text,_:=bufio.NewReader(os.Stdin).ReadString('\n')returnstrings.ReplaceAll(text,"\n","")}("Enter first number: ")num2:=func(msgstring)string{fmt.Print(msg)text,_:=bufio.NewReader(os.Stdin).ReadString('\n')returnstrings.ReplaceAll(text,"\n","")}("Enter second number: ")sum:=func()float64{i,err:=strconv.ParseFloat(num1,64)iferr!=nil{panic(err)}returni}()+func()float64{i,err:=strconv.ParseFloat(num2,64)iferr!=nil{panic(err)}returni}()fmt.Println("The sum of",num1,"and",num2,"is",sum)}jsondumpPythonimportjsonimportrandomdefmain():print(json.dumps(1))print(json.dumps("hello"))c=json.dumps({"hello":1,"how":"are you"})print(c+c)print(json.dumps([1,2,3]))if__name__=='__main__':main()Gopackagemainimport("encoding/json""fmt")funcmain(){fmt.Println(func()string{b,err:=json.Marshal(1)iferr!=nil{panic(err)}returnstring(b)}())fmt.Println(func()string{b,err:=json.Marshal("hello")iferr!=nil{panic(err)}returnstring(b)}())c:=func()string{b,err:=json.Marshal(map[string]interface{}{"hello":1,"how":"are you"})iferr!=nil{panic(err)}returnstring(b)}()fmt.Println(c+c)fmt.Println(func()string{b,err:=json.Marshal([]int{1,2,3})iferr!=nil{panic(err)}returnstring(b)}())}strdunderPythonclassA:a:strdef__init__(self,val):self.a=valdef__str__(self):returnself.adefmain():val=A("ok")print(val)if__name__=='__main__':main()Gopackagemainimport"fmt"typeAstruct{astring}funcNewA(valstring)(self*A){self=new(A)self.a=valreturn}func(self*A)String()string{returnself.a}funcmain(){val:=NewA("ok")fmt.Println(val)}globfilesPythonimportglobdefmain():forpy_fileinglob.glob("./*.py"):print("="*20,py_file,"="*20)withopen(py_file)aspy_f:forlineinpy_f:print(line.rstrip())if__name__=='__main__':main()Gopackagemainimport("bufio""fmt""io""os""path/filepath""strings""unicode")funcmain(){for_,py_file:=rangefunc(patternstring)[]string{matches,err:=filepath.Glob(pattern)iferr!=nil{panic(err)}returnmatches}("./*.py"){fmt.Println(strings.Repeat("=",20),py_file,strings.Repeat("=",20))func(){py_f:=func()*os.File{f,err:=os.OpenFile(py_file,os.O_RDONLY,0o777)iferr!=nil{panic(err)}returnf}()deferfunc(){iferr:=py_f.Close();err!=nil{panic(err)}}()ifsc,line,err:=bufio.NewReader(py_f),"",*new(error);true{for{line,err=sc.ReadString('\n')iferr!=nil&&(err==io.EOF&&len(line)==0||err!=io.EOF){break}fmt.Println(strings.TrimRightFunc(line,unicode.IsSpace))}iferr!=io.EOF{panic(err)}}}()}}stringmultiplyPythondefmain():s="1, 2, 3, 4"x=s*5y=str({1,2,3,4})*6z=str([1,2,3,4])*7a=str({1:2,3:4})*8b=str((1,2,3,4))*9c="1, 2, 3, 4"*10d="  1, 2, 3, 4  ".strip()*11print(x,y,z,a,b,c,d)if__name__=='__main__':main()Gopackagemainimport("fmt""strings")funcmain(){s:="1, 2, 3, 4"x:=strings.Repeat(s,5)y:=strings.Repeat(fmt.Sprintf("%v",map[interface{}]struct{}{1:{},2:{},3:{},4:{}}),6)z:=strings.Repeat(fmt.Sprintf("%v",[]int{1,2,3,4}),7)a:=strings.Repeat(fmt.Sprintf("%v",map[interface{}]interface{}{1:2,3:4}),8)b:=strings.Repeat(fmt.Sprintf("%v",[4]int{1,2,3,4}),9)c:=strings.Repeat("1, 2, 3, 4",10)d:=strings.Repeat(strings.TrimSpace("  1, 2, 3, 4  "),11)fmt.Println(x,y,z,a,b,c,d)}scopePythonimportrandomdefmain():ifrandom.random()>0.5:a=1else:a=2ifrandom.random()>0.5:ifrandom.random()>0.5:b=1else:b=2else:b=3defhello_world():c=3print(c)hello_world()print(a,b)if__name__=='__main__':main()Gopackagemainimport("fmt""math/rand""time")funcinit(){rand.Seed(time.Now().UnixNano())}funcmain(){varaintvarbintifrand.Float64()>0.5{a=1}else{a=2}ifrand.Float64()>0.5{ifrand.Float64()>0.5{b=1}else{b=2}}else{b=3}hello_world:=func(){c:=3fmt.Println(c)}hello_world()fmt.Println(a,b)}forelsePythondefmain():forxinrange(4):ifx==5:breakelse:print("Well of course that didn't happen")forxinrange(7):ifx==5:breakelse:print("H-hey wait!")i=0whilei<3:print("Works with while too")forxinrange(3):print("BTW don't worry about nested breaks")breakifi==10:breaki+=1else:print("Yeah not likely")print(i)if__name__=='__main__':main()Gopackagemainimport"fmt"funcmain(){varxintiffunc()bool{forx=0;x<4;x++{ifx==5{returnfalse}}returntrue}(){fmt.Println("Well of course that didn't happen")}iffunc()bool{forx=0;x<7;x++{ifx==5{returnfalse}}returntrue}(){fmt.Println("H-hey wait!")}i:=0iffunc()bool{fori<3{fmt.Println("Works with while too")forx=0;x<3;x++{fmt.Println("BTW don't worry about nested breaks")break}ifi==10{returnfalse}i+=1}returntrue}(){fmt.Println("Yeah not likely")}fmt.Println(i)}algomajorityelementPythondefmajorityElement(nums:list[int])->int:element,cnt=0,0foreinnums:ifelement==e:cnt+=1elifcnt==0:element,cnt=e,1else:cnt-=1returnelementdefmain():print(majorityElement([3,2,3]))# 3print(majorityElement([2,2,1,1,1,2,2]))# 2if__name__=='__main__':main()Gopackagemainimport"fmt"funcmajorityElement(nums[]int)int{element,cnt:=0,0for_,e:=rangenums{ifelement==e{cnt+=1}elseifcnt==0{element,cnt=e,1}else{cnt-=1}}returnelement}funcmain(){fmt.Println(majorityElement([]int{3,2,3}))fmt.Println(majorityElement([]int{2,2,1,1,1,2,2}))}algobisectionPythondefbisection(function,a:float,b:float)->float:start=aend=biffunction(a)==0:# one of the a or b is a root for the functionreturnaeliffunction(b)==0:returnbelif(function(a)*function(b)>0):# if none of these are root and they are both positive or negative,raiseValueError("could not find root in given interval.")else:mid=start+(end-start)/2.0whileabs(start-mid)>10**-7:# until precisely equals to 10^-7iffunction(mid)==0:returnmideliffunction(mid)*function(start)<0:end=midelse:start=midmid=start+(end-start)/2.0returnmiddeff(x:float):returnx**3-2*x-5defmain():print(bisection(f,1,1000))Gopackagemainimport("fmt""math")funcbisection(functionfunc(xfloat64)float64,afloat64,bfloat64)float64{start:=aend:=biffunction(a)==0{returna}elseiffunction(b)==0{returnb}elseiffunction(a)*function(b)>0{panic(fmt.Errorf("ValueError: %v","could not find root in given interval."))}else{mid:=start+(end-start)/2.0formath.Abs(start-mid)>math.Pow(10,-7){iffunction(mid)==0{returnmid}elseiffunction(mid)*function(start)<0{end=mid}else{start=mid}mid=start+(end-start)/2.0}returnmid}}funcf(xfloat64)float64{returnmath.Pow(x,3)-float64(2*x)-5}funcmain(){fmt.Println(bisection(f,1,1000))}algointersectionPythonimportmathdefintersection(function,x0:float,x1:float)->float:x_n=x0x_n1=x1whileTrue:ifx_n==x_n1orfunction(x_n1)==function(x_n):raiseZeroDivisionError("float division by zero, could not find root")x_n2=x_n1-(function(x_n1)/((function(x_n1)-function(x_n))/(x_n1-x_n)))ifabs(x_n2-x_n1)<10**-5:returnx_n2x_n=x_n1x_n1=x_n2deff(x:float)->float:returnmath.pow(x,3)-(2*x)-5defmain():print(intersection(f,3,3.5))if__name__=='__main__':main()Gopackagemainimport("fmt""math")funcintersection(functionfunc(xfloat64)float64,x0float64,x1float64)float64{x_n:=x0x_n1:=x1for{ifx_n==x_n1||function(x_n1)==function(x_n){panic(fmt.Errorf("ZeroDivisionError: %v","float division by zero, could not find root"),)}x_n2:=x_n1-function(x_n1)/((function(x_n1)-function(x_n))/(x_n1-x_n))ifmath.Abs(x_n2-x_n1)<math.Pow(10,-5){returnx_n2}x_n=x_n1x_n1=x_n2}}funcf(xfloat64)float64{returnmath.Pow(x,3)-float64(2*x)-5}funcmain(){fmt.Println(intersection(f,3,3.5))}indexPythondefmain():x=[1,2,3,7,3]print(x.index(7))if__name__=='__main__':main()Gopackagemainimport("errors""fmt")funcmain(){x:=[]int{1,2,3,7,3}fmt.Println(func()int{fori,val:=rangex{ifval==7{returni}}panic(errors.New("ValueError"))}())}TODOsSome things I'd like to add soon..."value in range(start, stop, step)" => a conditional statementExhaustive implementation of list/dict/int/float/bytes methods