Reputation: 61
This is my code:
total = 0
s = "helloV"
for i in range(0, len(s)):
total += 4 if s[i] == "V" else (total += 9) # The line where I'm getting the syntax error.
I'm not sure why this code is giving me a syntax error. Any help would be appreciated.
Upvotes: 1
Views: 67
Reputation: 1203
The code should be like this:
total = 0
s = "helloV"
for i in range(0, len(s)):
total += 4 if s[i] == "V" else 9
When the if condition is true add 4
else add 9
.
Upvotes: 2
Reputation: 53
total = 0
s = "helloV"
for i in range(0, len(s)):
if s[i] == "V":
total += 4
else:
total += 9
Above is a clear way to solve the syntax issues.
Upvotes: 0
Reputation: 976
You could also do something like this if you are looking for shorter code. It just uses a list comprehension that makes a list that has a 9
if the character in s
does not equal 'V'
, and 4
if it does. Then, it just sums the resulting list with sum()
:
s = "helloV"
total = sum([4 if i == 'V' else 9 for i in s])
Or you could use map()
to just apply a lambda
function to every element of s
that does the same thing as explained above:
s = "helloV"
total = sum(map(lambda i: 4 if i == 'V' else 9, s))
Upvotes: -1