gpt4 book ai didi

python - 如何在循环外部获取 for 循环中定义的变量? -Python

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:34 25 4
gpt4 key购买 nike

当我运行此 Python 代码时,我收到一个名称错误。但在这段代码中,我试图获取在 for 循环 (get) 中定义的变量以在循环外部使用。如何在 for 循环之外使用此变量 (get)

file = open("f:/py/price.txt", "r")

valRange = 0
cal = 0
totalCst = 0
itmCnt = 0
while (valRange < 10):
idNumber = int(input("Enter Id number: "))
for line in file:
if line.startswith(str(idNumber)):
get = line.split("=")[1]
break
quantity = int(input("Enter qantity: "))
cal = quantity * int(get)
totalCst += cal
itmCnt += quantity

print (totalCst)

最佳答案

只需在循环之前初始化变量即可。此外,break 命令不在 if 中。尝试:

file = open("f:/py/price.txt", "r")

valRange = 0
cal = 0
totalCst = 0
itmCnt = 0
while (valRange < 10):
idNumber = int(input("Enter Id number: "))
get = 0
for line in file:
if line.startswith(str(idNumber)):
get = line.split("=")[1]
break
quantity = int(input("Enter qantity: "))
cal = quantity * int(get)
totalCst += cal
itmCnt += quantity

print (totalCst)

关于python - 如何在循环外部获取 for 循环中定义的变量? -Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com