分页: 1 / 1

python小问题

发表于 : 2016-10-10 18:27
九天星

代码: 全选

#!/usr/bin/env python
i = 100
while i <= 255
    print i
    i = i + 1
问一:这个语法错在哪里?

问二:如果我要将 i = 后面的赋值为IP地址,比如值为192.168.1.100,只有最后的100变动,用这个语句应该如何完成?

Re: python小问题

发表于 : 2016-10-10 18:30
vickycq
九天星 写了:while i <= 255
此行末缺少冒号
九天星 写了:如果我要将 i = 后面的赋值为IP地址,比如值为192.168.1.100,只有最后的100变动

代码: 全选

for i in range(100,256):
    print "192.168.1.%d" % i

Re: python小问题

发表于 : 2016-10-10 18:37
onlylove
貌似楼上回答了一个,至于另一个,我突然想问,你用192.168.1.i有问题么,一定要用i代表一个ip么?

Re: python小问题

发表于 : 2016-10-10 19:16
九天星
onlylove 写了:貌似楼上回答了一个,至于另一个,我突然想问,你用192.168.1.i有问题么,一定要用i代表一个ip么?

好像不行

Re: python小问题

发表于 : 2016-10-10 20:41
vickycq
九天星 写了:好像不行

代码: 全选

import netaddr
ip = netaddr.IPAddress("192.168.1.100")
subnet = netaddr.IPNetwork('192.168.1.0/24')
while ip in subnet:
    print ip
    ip = ip + 1
先安装 netaddr 库: pip install netaddr
完整用法参考 https://pythonhosted.org/netaddr/index.html

Re: python小问题

发表于 : 2016-10-10 23:40
九天星

代码: 全选

#!/usr/bin/python
j = "192.168.1."
i = 100
while i <= 255:
    print j + str(i)
    i = i + 1
这个方式可以满足,只是,IP地址变成了字符串,IP地址是字符串吗??? :em04 :em04

Re: python小问题

发表于 : 2016-10-11 11:32
astolia
ipv4地址的点分十进制表示不是字符串是什么??? :em04 :em04

Re: python小问题

发表于 : 2016-10-11 14:46
九天星

代码: 全选

#!/usr/bin/python
#coding:utf-8
#润年判断小程序
year = int(raw_input("enter year:"))
if(year % 400 == 0):
	print ("%d is leapyear" % year)
elif(year % 4 == 0 and year % 100 != 0):
	print ("%d is leapyear" % year)
else:
	print ("%d is not leapyear" % year)
#号是注释符号,但在第二行,似乎#coding:utf-8不只是注释符这么简单对不对?

Re: python小问题

发表于 : 2016-10-11 15:05
astolia