Python – if statements

Question:

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')
Asked By: Daikengo

||

Answers:

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)
Answered By: Joshua Kelly
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.