Reputation: 825
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
Upvotes: 0
Views: 101
Reputation: 50190
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")
Upvotes: 2
Reputation: 16935
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
Upvotes: 4