skip to Main Content

Task: Check if an integer is positive or negative.
Check if the integer is divisible by 2 or not.

When 0 is entered I need to exit the loop and report each of the counts and sums. No output is displayed from the print function.

This is the code I’m using starting from the def main()

def main():
count positive = 0
count negative = 0
count_divisible_by_2 = 0
sum positive = 0
sum negative = 0
sum_divisible_by_2 = 0
while True:
  try:
   number = integer(input("Enter a integer(or the number 0 to stop): "))
  except `Value Error`:
   print("Invalid integer. Please enter a valid number value. :")
   print ("Enter the correct integer")
   
   if number == 0:
        break
   if number > 0:
        count positive += 1
        sum positive += number
   else number < 0:
        count negative += 1
        sum negative += number
  if number % 2 == 0:`
        count_divisible_by_2 += 1
        sum_divisible_by_2 += number
             
print(f "Positive integers count: {count positive}, sum: {sum positive}")
print(f "Negative integers count: {count negative}, sum: {sum negative}")
print(f "Integers divisible by 2 count: {count_divisible_by_2}, sum: {sum_divisible_by_2}")``

The output expected is the positive count, negative count, and if the integer is divisible by 2.

Visual Studio Code

2

Answers


  1. Note that when an exception occurs, you need to go back to entering a number. If you don’t do this, the code below will be executed, but with the previous value that you entered correctly. I.e., the previous value entered correctly will be counted twice.

    In addition, if you immediately enter an incorrect value, you’ll get an unhandled exception, because refer to the num variable that has not yet been created.

    # ...
    
    while True:
        try:
            num = int(input("Enter a integer (or the number 0 to stop): "))
        except ValueError:
            print("Invalid integer. Please enter a valid number value.")
            print("Enter the correct integer.")
            continue                                  # <---
    
    # ...
    

    Another point: Defining the main function isn’t an entry point for Python. This function should be called:

    main()
    
    Login or Signup to reply.
  2. You had a bunch of errors in your code.

    First, the try-catch block had logic executing in the exception part. It’s best practice to just identify the error in the exception part and continue to execute code (or break if needed) and jump back to the try part. I’ve modified the code to do just that.

    You had other syntax errors which I’m not going to go over. I’d suggest you use an IDE like VSCode that will "lint" (linting is a program that checks your code before you run it to identify syntax errors) your code. This will help you learn the syntax quicker as you can see exactly where you went wrong as you write your code. Other comments mentioned the backticks, but I’ll excuse that as I believe you were trying to make a code block using markdown for StackOverflow (I hope).

    When you printed out the strings, you had a space between the "f" character and the string quotes. "f" in this context stands for "format", and needs to be placed next to the string quotes in order for python to recognize it as a formatted string and insert the variables accordingly.

    I updated the variable names to be more readable and use underscores instead of spaces as like other comments mentioned, the python interpreter is going to pick up spaces as new variables, thus throwing errors in your code. (you are declaring two variables that are unassigned when you put a space in what you intended to be one variable name).

    That’s about it. You can learn python syntax with Python’s official tutorial, which I haven’t run through myself (I learned the basics of programming through Java, so python is pretty self-explanatory to me), but I’m sure it is a great starting point, since I can tell you are a beginner: https://docs.python.org/3/tutorial/index.html

    P.S. I also added a main method so you can execute this program with python main.py assuming you named the program main.py (you can name it whatever just point python to that program name).

    def main():
         positive_count = 0
         negative_count = 0
         divisible_count = 0
         positive_sum = 0
         negative_sum = 0
         divisible_sum = 0
    
         while True:
              try:
                   number = int(input("Enter a integer(or the number 0 to stop): "))
    
                   if number == 0:
                        break
                   if number > 0:
                        positive_count += 1
                        positive_sum += number
                   elif number < 0:
                        negative_count += 1
                        negative_sum += number
                   if number % 2 == 0:
                        divisible_count += 1
                        divisible_sum += number
              except ValueError:
                   print("Invalid integer. Please enter a valid number value.n")
                   continue
    
                        
         print(f"Positive integers count: {positive_count}, sum: {positive_sum}")
         print(f"Negative integers count: {negative_count}, sum: {negative_sum}")
         print(f"Integers divisible by 2 count: {divisible_count}, sum: {divisible_sum}")
    
    if __name__ == "__main__":
        main()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search