我正在尝试创建一个爱情计算器,但是它抛出错误,未定义score_total,我尝试了很多事情,但它根本不起作用。我尝试全局定义它。
当我全局将其定义为score_total = 0时。它只是不从函数返回,而是将其值0保留在函数外部。我是初学者。
boy = input("Enter boy Name\n").casefold()
girl = input("Enter girl name\n").casefold()
#score_total=
vowel_a =0
vowel_b=0
boyl=None
girll=None
boyl=len(boy)
girll=len(girl)
#print(boyl)
cons_a =0
cons_b=0
for i in range(boyl):
if boy[i] is 'a' or 'e' or 'i' or 'o' or 'u':
vowel_a+=1
for i in range(girll):
if girl[i] is 'a' or 'e' or 'i' or 'o' or 'u':
vowel_b+=1
for i in range(len(boy)):
if boy[i] is 'z' or 'b' or 't' or 'h':
cons_a +=1
for i in range(len(girl)):
if girl [i] is 'z' or 'b' or 't' or 'h':
cons_b+=1
def calculation(a,b,score_total):
score_total = 1
if len(a) == len(b):
score_total += 20
elif len(a)!=len(b):
score_total += 7.4
if a[0] and b[0] is 'a' or 'b' or 'c' or 'd' or 'e':
score_total +=10
else:
score_total+=3.7
if a[0] and [b] is 'z' or 'b' or 't' or 'h':
score_total+=5
else:
score_total +=1.16
if vowel_a == vowel_b:
score_total +=12
else:
score_total +=3.67
if cons_a == cons_b:
score_total+=12
else:
score_total+=4.56
if a[0] is 'i' or 'v' or 'o' or 'l':
score_total+=7
else:
score_total+=5.6
#return int(score_total)
print(score_total)
#print(scor--
calculation(boy,girl,1)
if score_total < 50:
if score_total%2 ==0:
score_total+=30
elif score_total>100:
temp = score_total-100
score_total -= temp
else:
score_total+=24
import time
print("Calculating Result...........\n")
time.sleep(3)
print("Data processing...")
time.sleep(7)
print(f'The love between {boy} and {girl} is {score_total}%' )
答案 0 :(得分:1)
如果您要使用全局变量(可能不是最佳设计实践,但是,我不确定),您需要将“ global score_total”放在所有使用它的函数的顶部。例如:
def calculation(a,b,score_total):
global score_total
score_total = 1
if len(a) == len(b):
....
python函数中的变量位于与主程序不同的范围内,并且global关键字将其覆盖。
答案 1 :(得分:0)
在调用定义了score_total
的{{1}}函数之前,您正在打印变量calculation
。 score_total
函数还应将calculation
返回给调用方,在此应将返回值分配给score_total
。
在score_total
函数的结尾:
calculation
然后在呼叫者处
return int(score_total)