I need to write a function that will take a list as a parameter and will replace numbers other than zero as 6. It will not print or return anything. for example if it gets [3],it will print [6]. If it gets [5,,5,5,5] it will print[6,,6,6,6]. I wrote this, but it does not work:
def main():
grades = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0]
convert_grades(grades) # Should print [0, 6, 0, 6, 0, 6, 0, 6, 0, 6, 0]
def convert_grades (a):
for i in range(len(a)):
if(a[i]!=0):
a[i]==6
pass
if __name__ == "__main__":
main()
CodePudding user response:
Change == 6
to = 6
to make the assignment otherwise it is evaluating a boolean expression if a[i]
equals to 6.
def convert_grades(a):
for i in range(len(a)):
if a[i] != 0:
a[i] = 6
grades = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0]
convert_grades(grades)
print(grades)
Output:
[0, 6, 0, 6, 0, 6, 0, 6, 0, 6, 0]
CodePudding user response:
You can use enumerate
for an elegant solution:
def convert_grades(grades):
for index, grad in enumerate(grades):
if grad != 0:
grades[index] = 6
g = [1, 0, 2, 2, 0]
convert_grades(g)
print(g)
Output:
[6, 0, 6, 6, 0]
CodePudding user response:
I have just used list comprehension to do it in one line
grades = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0]
new_grades = [6 if i!=0 else 0 for i in grades])
print(new_grades)
output
[0, 6, 0, 6, 0, 6, 0, 6, 0, 6, 0]