Python程序采用两个整数输入来查找偶数和奇数

时间:2018-08-28 17:57:47

标签: python

这是代码。当我输入偶数(第一个数字)说4,而奇数(第二个数字)说5时,它会打印“ 4和5是偶数”

num_1=int(input('first number ')) 
num_2=int(input('second number ')) 

if num_1%2==0 & num_2%2==0:
    print(num_1,'and',num_2,'are even')

elif num_1%2!=0 & num_2%2!=0:
    print(num_1,'and',num_2,'are odd')

elif num_1%2!=0 & num_2%2==0:
    print(num_1,'is odd and ',num_2,'is even')

elif num_1%2==0 & num_2%2!=0:
    print(num_1,'is even',num_2,'is odd')

else:
    print('invalid entry')

3 个答案:

答案 0 :(得分:2)

您非常接近! python中的&运算符与python中的'and'不同。 “和”测试两个条件在逻辑上均为真,而“&”是按位运算符,可以满足逻辑真,假和整数的条件,因为当“和”仅描绘逻辑时,它们可以按位组合。

num_1=int(input('first number '))
num_2=int(input('second number '))

if num_1%2==0 and num_2%2==0:
    print(num_1,'and',num_2,'are even')

elif num_1%2!=0 and num_2%2!=0:
    print(num_1,'and',num_2,'are odd')

elif num_1%2!=0 and num_2%2==0:
    print(num_1,'is odd and ',num_2,'is even')

elif num_1%2==0 and num_2%2!=0:
    print(num_1,'is even',num_2,'is odd')

else:
    print('invalid entry')

答案 1 :(得分:1)

您使用了错误的运算符:您使用了按位“与”代替逻辑“与”。按位“和”优先级较高,因此您的if语句的组织方式如下:

if (num_1 % 2) == ((0 & num_2) % 2) == 0:

&项更改为逻辑运算符and

答案 2 :(得分:0)

var parent_domain; jQuery(document).ready(function($){ $('#header2').hide(); $('#home-list li').on('click',function () { if($(this).attr('data-type')=='home') { if ($(this).attr('data-id') == 'ministry') { window.location.hash = "ministry"; loadAllMinistry('all.ministry.php'); $('#header2').find('.title').html(($(this).html())); } else { window.location.hash = "divisional"; parent_domain = $(this).attr('data-domain'); loadDivisionList('division.office.php',$(this).attr('data-domain')); $('#header2').find('.title').html(($(this).html())); } } }); }); function loadAllMinistry(fileName){ $.ajax({ type: 'POST', url: host+fileName, beforeSend: function () { $('#main-body').find('.home-view').hide(); $('#loading').show(); }, success: function (data) { $('#loading').hide(); $('#header1').hide(); $('#header2').show(); $('#main-body').find('#ministry-list').html(data); $('#ministry-list li').on('click',function () { if($(this).attr('data-type')=='ministry-list') { window.location.hash = "child-ministry"; loadMinistryChild('child.ministry.php',$(this).attr('data-id')); $('#header2').find('.title').html(($(this).html())); } }); } }); } 是按位运算符,而您需要的是逻辑运算符<header class="home-view" id="header2"> <div class="container-fluid text-center"> <div class="pull-left"> <a href='javascript:history.go(-1)'><img src="img/back.png" id="back"></a> </div> <span class="title">বাংলাদেশ</span> <div class="pull-right"> <a href="index.php"><img src="img/home.png" id="home"></a> </div> </div> </header> ,相当于Python中的&