0

Currently learning python. Normally a C++ guy.

if wallpaper == "Y":
    charge = (70)
    print ("You would be charged £70")
    wallpaperList.append(charge)

elif wallpaper == "N" :
    charge = (0)

else:
    wallPaper ()

surfaceArea
    totalPapers = 0
    for item in range (len(wallpaperList)):
        totalPapers += wallpaperList[item]

I am trying do a for loop for the if statement.

In c++ this will just be a simple

for (I=0; i<pRooms; i++){
}

I am trying to add the above code in a for loop but I seem to fail.

Thanks

3
  • Show the code that's failing, please. Commented Apr 22, 2016 at 19:30
  • 1
    Not sure over what you're looping... if it's pRooms, you do for i in xrange(pRooms): Commented Apr 22, 2016 at 19:30
  • Please correct your indentation, also, currently there are mistakes, and in Python, indentation matters. Commented Apr 22, 2016 at 19:31

2 Answers 2

4

Python loops iterate over everything in the iterable:

for item in wallpaperList:
        totalPapers += item

In modern C++, this is analogous to:

std::vector<unsigned int> wallpaperList;

// ...

for(auto item: wallpaperList) {
    totalPapers += item
}

You could also just use the sum function:

cost = sum(wallpaperList)

If the charge is 70 every time, why not just do multiplication?

while wallPaper == 'Y':
    # ...

    # Another satisfied customer!
    i += 1

cost = i * 70
Sign up to request clarification or add additional context in comments.

Comments

2

For the exact equivalent of your for loop, use range:

for (i=0; i<pRooms; i++){   # C, C++
}

for i in range(pRooms):     # Python
    ...

Both loops iterate over the values 0 to pRooms-1. But python gives you other options. You can iterate over the elements of the list without using an index:

for room in listOfRooms:
    if room.wallpaper == "Y":
        ...

List comprehensions are also nice. If you don't care about the print calls in your code, you could compute the cost in one line with something like this:

totalPapers = sum(70 for room in listOfRooms if room.wallpaper == "Y")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.