我正在使用python3,我有此代码向用户询问三个输入。然后我对它们进行计算。我想继续将计算结果添加到列表中。该怎么做?
...
if choice == '1': #my fist input x
while True:
x = int(input('Please insert the number of things you consider yourself a fan of'))
if x > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '2': #my second input y
while True:
y = int(input('Please insert the number of hobbies you like to do every month'))
if y % 4 == 0:
break
else:
print('Please insert a valid number')
elif choice == '3': #my third input z
while True:
z = int(input('Please insert the number of sports you like'))
if z > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '4': #the calculation part
import math
def square_root():
c=(42 * y ** 2)/(z + 1)
nerd_score=int(x*math.sqrt(c))
return nerd_score
print('your nerd score is', square_root())
我希望循环继续进行,并将每个结果添加到列表中。直到用户退出循环。
答案 0 :(得分:0)
据我了解,您要解决两个问题:
示例代码在这里:
def loop_calculation(choice):
# record results in list
results = []
# loop keep going, util user input choice 'x' which means exit
while choice != 'x':
if choice == '1': # my fist input x
while True:
x = int(input('Please insert the number of things you consider yourself a fan of'))
if x > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '2': # my second input y
while True:
y = int(input('Please insert the number of hobbies you like to do every month'))
if y % 4 == 0:
break
else:
print('Please insert a valid number')
elif choice == '3': # my third input z
while True:
z = int(input('Please insert the number of sports you like'))
if z > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '4': # the calculation part
import math
def square_root():
c = (42 * y ** 2) / (z + 1)
nerd_score = int(x * math.sqrt(c))
return nerd_score
result = square_root()
print('your nerd score is', result)
# add each result to list
results.append(result)
return results
希望它会对您有所帮助。