【问题标题】:If, elif, print based on three variables of an input in pythonif,elif,基于python中输入的三个变量打印
【发布时间】:2018-03-03 08:47:40
【问题描述】:

帮助!我被这个python脚本困住了。所以基本上我希望我的程序在从用户那里收到所有三个变量的输入时运行代码的第一部分。

我试图基本上有如果有 .在 a 中,在 b 中的破折号和 .然后在 c 中运行这些打印语句。否则,请执行以下操作。注意:第一个代码的打印语句与其他代码不同。我希望它基于 a、b、c 都具有输入来运行代码的第一部分。感谢帮助

代码

a = raw_input("Enter ip address: ")
b = raw_input("Enter range: ")
c = raw_input("Enter network: ")

#should print ip adress, range, and network combined 
if '.' in a + '-' in b + '.' in c:
  ips = b.split('-')
  print 'config firewall address\n','edit "ip-' + str(a) + '"'
  print 'set subnet ' + str(a) + '/32'
  print 'next'
  print 'edit "ip-' + str(b) + '"'
  print ('set type iprange')
  print ('set start-ip '+ips[0])
  print 'set end-ip '+ips[1]
  print 'next'
  print 'edit "net-' + str(c) + '"'
  print 'set subnet ' + str(c) + ''
  print 'next'
  print 'end'

输出

其余代码根据用户输入运行。

#SHOULD print ip adress, range, and network combined
Enter ip address: 10.203.1.10
Enter range: 10.228.50.88-10.228.50.91
Enter network: 172.27.0.0/16
config firewall address
edit "ip-10.203.1.10"
set subnet 10.203.1.10/32
next
end

我不希望最后的输出是那样的。这是我想要的输出。

Enter ip address: 10.203.1.10
Enter range: 10.228.50.88-10.228.50.91
Enter network: 172.27.0.0/16
config firewall address
edit "ip-10.203.1.10"
set subnet 10.203.1.10/32
next
edit "ip-10.228.50.88-10.228.50.91"
set type iprange
set start-ip 10.228.50.88
set end-ip 10.228.50.91
next
edit "net-172.27.0.0/16"
set subnet 172.27.0.0/16
next
end

我需要做什么?

【问题讨论】:

  • 你的程序在运行吗?或者您手动给出了所需的输出?尝试使用if '.' in a and '-' in b and '.' in c 并且缩进也很混乱
  • 它正在运行,但不是我想要的。它打印输入,但我想基于 a、b、c 为真或知道它们包含句点或破折号来运行。

标签: python variables if-statement printing return


【解决方案1】:

如果要检查多个条件是否为真,而不是:

if '.' in a + '-' in b + '.' in c:

...你应该使用:

if all(['.' in a, '-' in b, '.' in c]):

...或...

if '.' in a and '-' in b and '.' in c:

您还需要确保正确缩进代码。

【讨论】:

  • 完美!这正是我想要完成的我只是不知道如何测试多个条件,因为我是 python 的初学者。我两周前才开始学习这门语言。