简体   繁体   English

if语句中使用“和”的多个条件

[英]multiple conditions in if statement using 'and'

Problem statement : IP addresses of the following forms are considered special local addresses: 10. * . 问题陈述:以下形式的IP地址被视为特殊的本地地址:10. *。 * . *。 * and 192.168. *和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 星号可以代表0到255之间的任何值。编写一个程序,要求用户输入IP地址并打印出它是否为以下两种形式之一

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. startwith()是解决此问题的好选择。 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. 但是,我无法弄清楚为什么上面的代码总是将输出作为“这是一个普通IP地址”,而不管输入是什么。

  • Line(5) => and s[6]==8 is just and extension of elif statement. Line(5)=>和s [6] == 8是justif和elif语句的扩展。

Subscripting a string will return a string not an int , like you're comparing them to. 下标字符串将返回一个字符串,而不是int ,就像您将它们进行比较一样。 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')    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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