trying to condense if statements and want to know if there is a proper why of writing this. Also this is my first post as well as being new to programming
mark1 = int(input("Enter mark 1: ")) if mark1 < 0 or mark1 > 100: help() mark1 = input(1) mark2 = int(input("Enter mark 2: ")) if mark2 < 0 or mark2 > 100: help() mark2 = int(input("Enter mark 2: ")) mark3 = int(input("Enter mark 3: ")) if mark3 < 0 or mark3 > 100: help() mark3 = int(input("Enter mark 3: ")) mark4 = int(input("Enter mark 4: ")) if mark4 < 0 or mark4 > 100: help() mark4 = int(input("Enter mark 4: ")) mark5 = int(input("Enter mark 5: ")) if mark5 < 0 or mark5 > 100: help() mark5 = int(input("Enter mark 5: "))
Advertisement
Answer
First, you should review the logic to get marks: in your case, it prompts once, and if the entered mark is outside the range, it prompts again. However, if an invalid value is entered at the second time of asking, it simply accepts that value. Instead, you should use a while
loop so that it keeps asking until a valid value is returned. You also probably want to account for the case where the entered number is not an integer. You can do this by trying to cast it to an int()
and then catching the resulting ValueError
.
Now, repeated code can be wrapped in a function, and then you just call that function:
def get_mark(prompt): while True: m = input(prompt) try: m = int(m) except ValueError: print("Please enter an integer") continue # skip the rest of the loop and prompt for input again if 0 <= m <= 100: # If it's a valid mark, we return it return m help() # If we haven't returned so far, it was an invalid mark so we call help()
Then, do
mark1 = get_mark("Enter mark 1: ") mark2 = get_mark("Enter mark 2: ") ...