Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – if statements

I’m exercising and:

  • Can a good Samaritan review this code and tell me if there’s a better / cleaner way to write it?
  • This is my first attempt to write a basic program in Python
  • If you change the value of the operator, it should return a different value
x = 0
y = 1
z = 0

if x == 0 and y == 0 and z == 0:
    print('x, y and z are equal to zero')
    
if y > x:
    print('y is greater than x')
    if y > z:
        print('y is also greater than z')
    else:
        print('y is smaller than z')

if y < x:
    print('y is smaller than x')
    if y > z:
        print('y is also greater than z')
    else:
        print('y is smaller than z')

if z > x:
    print('z is greater than x')
    if z > y:
        print('z is greater than y')
    else:
        print('z is smaller than y')

if z < x:
    print('z is smaller than x')
    if z > y:
        print('z is greater than y')
    else:
        print('z is smaller than y')

if x < y:
    print('x is smaller than y')
    if x > z:
        print('x is also greater than z')
    else:
        print('x is smaller than z')

if x > y:
    print('x is greater than y')
    if x > z:
        print('x is greater than z')
    else:
        print('x is smaller than z')

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A better and cleaner way to write this code would be to use the if-elif statements instead of repeating the if statements multiple times. It would also be helpful to use a function to print the comparison messages instead of repeating the same print statements multiple times.

Here is an example of how the code could be rewritten:

def print_comparison(a, b, c):
    if a == b == c == 0:
        print('x, y and z are equal to zero')
    else:
        if a > b and a > c:
            print('x is greater than y and z')
        elif a < b and a < c:
            print('x is smaller than y and z')
        elif a > b and a < c:
            print('x is greater than y and smaller than z')
        elif a < b and a > c:
            print('x is smaller than y and greater than z')

x = 0
y = 1
z = 0

print_comparison(x, y, z)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading