본문 바로가기
파이썬

파이썬 Write a program to find sum of two numbers using functions and calculate their average?

by º기록 2020. 10. 17.
반응형

나는 질문을 이해하지만 확실하지 않은 것은 "기능 사용"이라고 말하는 부분입니다. 여기에 내 코드가 있으며 허용 가능한지 궁금합니다.

x= int(input("Enter first number:"))
y= int(input("Enter second number:"))
sum=x+y
average=sum/2
print("Sum of the given two numbers is:", sum)
print("Average of the given numbers is:", average)

 

해결 방법

 

함수는 재사용 가능한 프로그램입니다. 따라서 나중에 어디에서나 사용할 수 있도록 함수를 작성해야합니다. 어떤 것에 대한 평균 비율을 계산해야한다고 가정하고, 평균 값을 얻기 위해 (인쇄하지 않고) avg 함수가 필요하고 비율을 얻기 위해 시간으로 나눕니다. 그러나 코드는 합계와 평균 값을 불필요하게 인쇄합니다. 따라서 함수의 값을 계산하여 인쇄하는 대신 반환하는 것이 좋습니다.

Another point, you are using variables num1 and a interchangeably. There is no need to use both of them. You can directly use a in the input statement. Similarly, for num2 and b, use b directly.

And, if you are using python 3.x, you can use // operator to get the division result as an integer (rounded down to nearest whole number).

따라서 코드는 다음과 같이 수정할 수 있습니다.

def sum(x,y):
    return x+y

def avg(x,y):
    return sum(x,y)//2

a= int(input("Enter first number:"))
b= int(input("Enter second number:"))

print("Sum of the given two numbers is: ", sum(a,b))
print("Average of the given numbers is: ", avg(a,b))

 

참조 페이지 https://stackoverflow.com/questions/45529502

 

 

반응형

댓글