简体   繁体   中英

multiple conditions in if statement using 'and'

Problem statement : IP addresses of the following forms are considered special local addresses: 10. * . * . * and 192.168. * . * . The stars can stand for any values from 0 to 255. Write a program that asks the user to enter an IP address and prints out whether it is in one of these two forms

My code :

s=input('Enter the IP address :')
if s[0]==1 and s[1]==0 and s[2]=='.':
    print('It is a special IP address')
elif s[0]==1 and s[1]==9 and s[2]==2 and s[3]=='.' and s[4]==1 and s[5]==6 
and s[6]==8:
    print('It is a special IP address')
else:
    print('It is an ordinary IP address')    

startwith() is a good option to solve this problem. However, i am unable to figure out why the above code always gives the output as 'It is an ordinary IP address' regardless of what the input is.

  • Line(5) => and s[6]==8 is just and extension of elif statement.

Subscripting a string will return a string not an int , like you're comparing them to. You should use string literals in your conditions:

s=input('Enter the IP address :')
if s[0]=='1' and s[1]=='0' and s[2]=='.':
    print('It is a special IP address')
elif s[0]=='1' and s[1]=='9' and s[2]=='2' and s[3]=='.' and s[4]=='1' and s[5]=='6' and s[6]=='8':
    print('It is a special IP address')
else:
    print('It is an ordinary IP address')    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM