Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

python - What's making the difference here? I just dont get behind it

So i made this code to check if to integers can be devided without a rest, and its working. But I needed to make a change so it works. I really just want to understand why this little change completely inversed the outcome of my code. This is the working code

x = input("Erster Teiler")
y = input("Zweiter Teiler")

z = int(x)%int(y) 
z1 =int(y)%int(x)

if z == 0 or z1 == 0:
    print("teilbar")
else: 
    print("nicht teilbar")

my first attempt at this excercie is doing the exact oppossite. If i put in 2 numbers that you can not divide, it says they are divisable. I just want to know what makes the difference in these codes. As you can see all i did was changing the premise for my first if-condition.

x = input("Erster Teiler")
y = input("Zweiter Teiler")

z = int(x)%int(y) 
z1 =int(y)%int(x)

if z or z1 == 0:
    print("teilbar")
else:
    print("nicht teilbar")
question from:https://stackoverflow.com/questions/65938496/whats-making-the-difference-here-i-just-dont-get-behind-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out the section in python documentation on truth value testing

https://docs.python.org/3/library/stdtypes.html

Reproducing some of the documentation

Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.

  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

  • empty sequences and collections: '', (), [], {}, set(), range(0)

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

if z or z1 == 0:

is testing if z a numeric type any value other than 0 is evaluated to true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...