这里的主要思想是您可以逐行迭代文件,将行拆分为可用的数据块,然后将正确的块传递给不同的函数。这将是一个大循环,但每个单独的计算都将在单独的函数中完成,因此有助于模块化。
现在,函数有很多方法,以及如何处理输出和打印:您可以避免在函数内部打印;您可以返回整个答案字符串;您可以只返回计算值而不是文本字符串;你可以完全在外面处理琴弦;等等。我想你明白了。
我将根据您的喜好保留该级别的自定义。我不想让代码过于复杂,所以我保持尽可能简单和合理的可读性,有时会牺牲一些更 Python 的方式。
# Here the functions that will be used later in the main loop
# These functions will calculate the answer and produce a string
# Then they will print it, and also return it
def make_lowercase(s):
answer = s.lower()
print(answer)
return answer
def has_vowels(word):
# For each vowel, see if it is found in the word
# We test in lowercase for both
answer = 'Does not contain vowels'
for vowel in 'aeiou':
if vowel in word.lower():
answer = 'Contains vowels'
break
print(answer)
return answer
def calculate_sphere_volume(radius):
# Remember to convert radius from string to number
import math
volume = 4.0/3.0 * math.pi * float(radius)**3
answer = "The volume of the sphere with radius {} is {}".format(radius, volume)
print(answer)
return answer
def check_possible_triangle(a1, b1, c1):
# Remember to convert from string to number
a = float(a1)
b = float(b1)
c = float(c1)
answer = '{}, {}, {} can make a triangle'.format(a1, b1, c1)
if (a + b <= c) or (a + c <= b) or (b + c <= a):
answer = '{}, {}, {} cannot make a triangle'.format(a1, b1, c1)
print(answer)
return answer
def calculate_average(a1, b1, c1):
# Remember to convert from string to number
a = float(a1)
b = float(b1)
c = float(c1)
average = (a + b + c) / 3
answer = 'The average of {}, {}, {} is {}'.format(a1, b1, c1, average)
print(answer)
return answer
with open('Lab5_Data.txt', 'r') as my_file:
for line in my_file:
# if you split each line, you get the individual elements
# you can then group them appropriately, like so:
# word: will contain the 5 letter string
# radius: will be the first number, to be used for the sphere
# a,b,c will be the three numbers to check for triangle
# Important: THESE ARE ALL STRINGS!
word, radius, a, b, c = line.split()
# Now you can just use functions to calculate and print the results.
# You could eliminate the prints from each function, and only use the
# return results that will be combined in the end.
# Lowercase:
ans1 = make_lowercase(word)
# Does this word have vowels?
ans2 = has_vowels(word)
# Calculate the sphere volume
ans3 = calculate_sphere_volume(radius)
# Check the triangle
ans4 = check_possible_triangle(a, b, c)
# Calculate average
ans5 = calculate_average(a, b, c)
# Now let's combine in a single line
full_answer = '{} {} {} {} {}'.format(ans1, ans2, ans3, ans4, ans5)
print(full_answer)