Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New to Python. Need help!!!
#1
Hello everyone,

My name is Thai and I am new to Python. I have a question and really need your help so that I can have a better understanding about Python. The original problem is about the division operation between two numbers whichever is greater. I already had my code but I would like to modify it a little bit in such a way that if I enter "exit" or "e" for either the first or second number, the program will stop immediately. For example, if I enter "exit" for the first number, the program will stop without entering the second number. Here is my codes. Thank you for your help.
while True:
    num_1 = input("enter your first number: ")
    if num_1.isdigit() == False:
        print("Invalid Input")
    else:
        break   
while True:
    num_2 = input("enter your second number: ")
    if num_2.isdigit() == False:
        print("Invalid Input")
    else:
        break       
while True:
    if int(num_1) == 0 or int(num_2) == 0:
        print("Cannot divide by zero. The answer is zero by default.")
        break
    if int(num_1) > int(num_2):
        print("The answer is ",int(int(num_1) / int(num_2)))
        break
    if int(num_1) < int(num_2):
        print("The answer is ",int(int(num_2) / int(num_1))) 
        break
    if int(num_1) == int(num_2):
        print("Two number are equal. The answer is one.")
        break
Reply
#2
import sys


while True:
    num_1 = input("enter your first number (exit or 'e' to quit): ")
    if num_i == 'e' or num_1 == 'exit'):
        print('Good Bye')
        sys.exit(0)
    if num_1.isdigit() == False:
        print("Invalid Input")
    else:
        break   
while True:
    num_2 = input("enter your second number: ")
    if num_2.isdigit() == False:
        print("Invalid Input")
    else:
        break       
while True:
    if int(num_1) == 0 or int(num_2) == 0:
        print("Cannot divide by zero. The answer is zero by default.")
        break
    if int(num_1) > int(num_2):
        print("The answer is ",int(int(num_1) / int(num_2)))
        break
    if int(num_1) < int(num_2):
        print("The answer is ",int(int(num_2) / int(num_1))) 
        break
    if int(num_1) == int(num_2):
        print("Two number are equal. The answer is one.")
        break
Reply
#3
I observe some ambiguity in conditions: "The original problem is about the division operation between two numbers whichever is greater.". Your code assumes that 0 is smallest number, but in narrow scope numbers are natural numbers (1, 2 .., without zero), or in some flavour of extended scope of numbers i.e including zero or including zero and negative numbers. Is this absolutely sure that in scope of this assignment numbers can't be negative? This is important because if 0 is smallest possible number --> if 0 entered by user it will always be divider --> dividing with zero is undefined. Therefore if user enters zero (either as first or second number) no calculations are needed. Code should short-circuit at that point.

Dividing with zero doesn't have zero as default answer. Default answer is undefined (math) or ZeroDivisonError (Python) error:

if int(num_1) == 0 or int(num_2) == 0:
        print("Cannot divide by zero. The answer is zero by default.")
This is probably homework so I will not provide full code but one idea. If there are two numbers and you want divide largest with smallest then you can append them to list and sort. This way you don't need so many conditions. You can also take advantage of set to determine whether numbers are equal. Algorithm can be something like that (apart of exit):

- if user enters zero --> answer is 'undefined'
- valid numbers entered by user appended to list
- if clause checks whether length of set made from list is 2, then divide second element in sorted list with first element in sorted list
- else clause (if set is length is not two but one i.e. numbers are equal) --> 'answer is one'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
A little bit optimized. The function follows the "don't ask for permission, ask for forgiveness".
I don't need to know how a integer is parsed and I don't need to know all corner cases. For floats it
is more complex, because there are many valid representations. The Python built-in functions does know
all this corner cases and if something fail, they'll raise an exception. For wrong Values you get a ValueError.
If you want to add an integer with a string, you'll get a TypeError. If you divide by zero, you will get
the ZeroDivisionError. Mathematically it's not defined and there is no solution.

The rest of the code is reusing the function to get the values.
This follows the dry (dont-repeat-yourself) principle.
The while-loop is not needed. This changes the way, how you use
the control flow. You can break only out of loops.
In if-elif-else conditions it's not possible outside of a loop to break.
But the if-elif-else pattern runs only the block, where the condition
is valid.

                                                                                         
def get_int(question):
    while True:
        try:
            return int(input(question + ' '))
        except ValueError:
            print('Invalid input')


num_1 = get_int("enter your first number:")
num_2 = get_int("enter your second number:")
if num_1 == 0 or num_2 == 0:
    print("Cannot divide by zero. The answer is zero by default.")
elif num_1 > num_2:
    print("The answer is", num_1 / num_2)
elif num_1 < num_2:
    print("The answer is", num_2 / num_1) 
elif num_1 == num_2:
    print("Two number are equal. The answer is one.")
else:
    print("Impossible, this case should not happen")
For division you can make also a function.

def division(a, b):
    x = max(a, b)
    y = min(a, b)
    return x / y
num_1 = get_int("enter your first number:")
num_2 = get_int("enter your second number:")
if num_1 == 0 or num_2 == 0:
    print("Cannot divide by zero.")
elif num_1 == num_2:
    print("Two number are equal. The answer is one.")
else:
    result = division(num_1, num_2)
    print("Your answer is", result)
If you disallow the use of 0 as input, you can handle this in the get_int function.
Then you can remove the check in the elif block.

By the way, if you check for Zero in the get_int function, you can remove the elif-block.

def get_int(question):
    """
    Get a valid integer. 0 is not allowed.
    A white space is concatenated to the question.
    If the result is valid, the function
    returns the integer.
    """
    while True:
        try:
            value = int(input(question + ' '))
        except ValueError:
            print('Invalid input')
            continue # starts on top again
        # this point is reached if no error happens
        if value == 0:
            print('0 is not allowed')
            continue # starts on top again
        # this point is reached, if value != 0
        return value # returns the valid result


def division(a, b):
    """
    Divide the bigger number by smaller number
    and return the result.
    """
    x = max(a, b)
    y = min(a, b)
    return x / y

### here is now your main part
num_1 = get_int("enter your first number:")
num_2 = get_int("enter your second number:")
if num_1 == num_2:
    print("Two number are equal. The answer is one.")
else:
    result = division(num_1, num_2)
    print("Your answer is", result)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020