Converting C loops to Python UserPageVisits:472 active 80 80 DaniWeb 561 60 2015-07-19T17:53:58+00:00

Converting C loops to Python


karmstrong ask in the Python chat if any one was farmilar with converting a for loop in C to Python. Here is a program in python that will do it for you!

Thank You!

Gribouillis commented: interesting attempt +14
About the Author
code snippet
testCLoop = "for(int a=10;a<20;a=a+1)"
cLoop = input("Enter C For Loop:\t")
#cLoop = testCLoop
cLoopStriped = cLoop.strip("for(").strip(")")
cLoopList = cLoopStriped.split(";")


cLoopListInit = str(cLoopList[0]).split("=")
if "<" in cLoopList[1]:
	cLoopListCondition = cLoopList[1].split("<")
elif ">" in cLoopList[1]:
	cLoopListCondition = cLoopList[1].split(">")
if "+" in cLoopList[2]:
	cLoopListAdd = cLoopList[2].split("+")
	condition = "+"
elif "-" in cLoopList[2]:
	cLoopListAdd = cLoopList[2].split("-")
	condition = "-"

pythonLoop = "for x in range("
pythonLoop += str(cLoopListInit[1]+", ")
pythonLoop += str(cLoopListCondition[1]+", ")
if condition == "+":
	pythonLoop += str(cLoopListAdd[1])
if condition == "-":
	pythonLoop += str("-"+cLoopListAdd[1])
pythonLoop += ")"


Instead of parsing the C code by hand, you could start from an ast produced by an existing C parser written in python: module pycparser. Here is an example, adapted from pycparser's example

# see pycparser for complete example
from __future__ import print_function
import sys

from pycparser import c_parser, c_ast

text = """
void foo(){
    for(int a=10;a<20;a=a+1)

parser = c_parser.CParser()
ast = parser.parse(text, filename='<none>')

""" my output -->
    Decl: foo, [], [], []
        TypeDecl: foo, []
          IdentifierType: ['void']
          Decl: a, [], [], []
            TypeDecl: a, []
              IdentifierType: ['int']
            Constant: int, 10
        BinaryOp: <
          ID: a
          Constant: int, 20
        Assignment: =
          ID: a
          BinaryOp: +
            ID: a
            Constant: int, 1

Starting from an ast gives a robust base for translation to python.

Thanks! Never knew about that. See you learn some thing new ever day!

In Python range() will do the work for you, no reason to go back to the medieval times. Even the newer curly brace languages have gone to on "in range" iterative approach.

Note that the minute you see code like for i in range(len(items)) in Python you should sense a code smell.

You should sense a "code smell" because the code should be
for item in items

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.