def winheight(height):
try:
height = int(raw_input('Enter the height of the window in metres: '))
except ValueError:
print 'Please enter an integer'
winheight(height)
winlength(length)
def winlength(length):
try:
length = int(raw_input('Enter the length of the window in metres: '))
except ValueError:
print 'Please enter an integer'
winlength(length)
pricing(height, length)
def pricing(height, length):
height_length = height * length
price = int(height_length) * 100
total = int(price) + 50
print int(total)
winheight(height)
这是我正在尝试的代码,用于完成窗户更换业务的课程任务,每平方米的价格为100美元+初始价格为50美元
但是,每当我尝试运行此代码时,都会收到错误消息:
第31行,在 winheight(height)名称错误:未定义名称“ height”
我需要全局定义高度和长度,以便可以将其用作最终成本,我不确定如何解决此问题,我们将不胜感激
答案 0 :(得分:0)
def addNew():
appendBase = open('dBase.cfg','a')
uname = input('Username: ')
pword = input('Password: ')
appendBase.write(uname+','+pword+'\n')
print('\nAdded new profile: \n'+uname+','+pword)
appendBase.close()
确实没有定义。您在函数中定义的height
变量是 local 变量。函数调用结束后,它将停止存在。您可以返回它,也可以使用全局变量(但不要使用全局变量)
height
并通过 def get_height():
while True:
try:
height = input()
except ValueError:
continue
else:
return height
从主脚本中调用它(类似于height = get_height()
,然后调用length)
。
其他一些注意事项:
pricing(height, length)
,请使用while循环,而不要递归调用该函数(因为先前的函数堆栈处于打开状态)input()
变量并重新分配height
。传递给height的值是副本,因此原件不会更改。答案 1 :(得分:0)
您的代码应如下所示:
def winheight(): #define window-height-getting function
while True:
try:
height = int(raw_input("Enter the height of the window in metres: ")) #get user input for window height
return height
except ValueError: #catch improper inputs
print "Please enter an integer"
def winlength(): #define window-length-getting function
while True:
try:
length = int(raw_input("Enter the length of the window in metres: ")) #get user input for window length
return length
except ValueError: #catch improper inputs
print "Please enter an integer"
def pricing(height, length): #define price-calculating function
area = height * length #math to determine total price
price = area * 100
total = price + 50
return total
user_height = winheight() #get window height from user
user_length = winlength() #get window length from user
total_price = pricing(user_height, user_length) #calculate total price by passing user window height and length to the pricing function
print "The total price is: $" + str(total_price) #print result