I am making a code which calculates the average of credits the user inputs in Python. The loop should break, if the user inputs two zeros in a row and I have tried everything I can to make it so but I am having a hard time. Could someone help me? This is the code I have written so far. Sorry for bad English, I am a student from Finland :D
months = int(input("Enter the number of months: "))
list = []
loops = 1
for loops in range(1, months 1):
print("Enter the number of credits in month", loops, end="")
credits = int(input(": "))
list.append(credits)
(now if credits are zeros two times a row)
print("You did have too many study breaks!")
break
loops = 1
average_credits = sum(list) / months
print("Your monthly credit point average is", average_credits, ".")
CodePudding user response:
Before converting the input string to int, check it if it is two leading zeroes.
months = int(input("Enter the number of months: "))
list = []
loops = 1
for loops in range(1, months 1):
print("Enter the number of credits in month", loops, end="")
input_str = input(": ")
if input_str == "00":
print("You did have too many study breaks!")
break
credits = int(input_str)
list.append(credits)
loops = 1
CodePudding user response:
I hope this answers your question:
months = int(input("Enter the number of months: "))
count_zeros = 0
list = []
loops = 1
for loops in range(1, months 1):
while count_zeros < 1:
print("Enter the number of credits in month", loops, end="")
if credits == 0:
count_zeros = 1
credits = int(input(": "))
list.append(credits)
loops = 1
else:
print("You did have too many study breaks!")
break
average_credits = sum(list) / months
print("Your monthly credit point average is", average_credits, ".")
CodePudding user response:
This is how I would solve the issue of two zeros in a row.
months = int(input("Enter the number of months: "))
list = []
loops = 1
for loops in range(1, months 1):
print("Enter the number of credits in month", loops, end="")
credits = int(input(": "))
# if the length of the list is not 0 (the array is not empty)
# get the last element in the list and check if it is 0
# if it the previous credit was 0, break the loop
if len(list) != 0 and list[-1] == 0:
print("You did have too many study breaks!")
break
list.append(credits)
# loops = 1 - this line is not necessary, the loop will increment automatically in the range
average_credits = sum(list) / months
print("Your monthly credit point average is", average_credits, ".")
