将用户输入作为参数和简单公式的输出结果。获取错误消息'not defined'



我正在编写一个简单的程序,它将用户输入作为其参数,并通过一个简单的公式运行这些参数,然后输出结果。但我认为我的语法有问题,我不明白是什么。

def P2(packets = input("Please enter nr of packets: "), switches = input("Please enter nr of switches: ")): 
delay = 1
time = (packets + (switches-1)) * delay
#print("The time it takes to send " % packets % " packets back-to-back over " % switches % " switches is: " % time)
print("The time it takes to send () packets back-to-back over () switches is: ()".format(packets, switches, time))
P2(packets, switches)

我收到错误消息:

Traceback (most recent call last):
File "C:/Users/amali/PycharmProjects/LearningPython/100PyEx1/P2Program.py", line 8, in <module>
P2(packets, switches)
NameError: name 'packets' is not defined

您需要在函数外部定义数据包和交换机,并使用它们调用函数:

def P2(packets, switches):
delay = 1
time = (packets + (switches-1)) * delay
#print("The time it takes to send " % packets % " packets back-to-back over " % switches % " switches is: " % time)
print("The time it takes to send %s packets back-to-back over %s switches is: %s" %(packets, switches, time))
p = input("Please enter nr of packets: ")
s = input("Please enter nr of switches: ")
P2(p, s)

编辑:

如果你不需要实际的变量,你可以做:

P2(input("Please enter nr of packets: "), input("Please enter nr of switches: "))

我认为这不太可读,但它有效...

最新更新