# Writing Functions in Python

• Print
This chapter is from the book

## How It Works

In this chapter, we’re still dealing with programs that are relatively short and translate into simple pseudocode.

`Prompt the user for the values of a, b, and c.Apply the quadratic formula to get x1 and x2.Print the values of x1 and x2.`

Because a, b, and c all need to refer to numeric data, the program applies a float conversion combined with the built-in input function. If these numbers are not converted to float format, you won’t be able to do math with them.

`    a = float(input(’Enter value for a: ’))    b = float(input(’Enter value for b: ’))    c = float(input(’Enter value for c: ’))`

Next, the quadratic formula is applied to get the two solutions for x. Remember that the operation ** 0.5 has the same effect as taking the square root.

`    determ = (b * b – 4 * a * c) ** 0.5    x1 = (-b + determ) / (2 * a)    x2 = (-b - determ) / (2 * a)`

Finally, the program displays the output, featuring x1 and x2.

`    print(’The answers are’, x1, ’and’, x2)`

EXERCISES

Exercise 3.2.1. In Example 3.2, instead of using the prompt messages “Enter the value of a,” etc., prompt the user with the following messages:

“Enter the value of the x-square coefficient.”

“Enter the value of the x coefficient.”

“Enter the value of the constant.”

Do you have to change the variable names as a result? Note that the user never sees the names of variables inside the code, unless you deliberately print those names.

Exercise 3.2.2. Modify Example 3.2 so that it restricts input to integer values.

Exercise 3.2.3. Write a program to calculate the area of a right triangle, based on height and width inputs. Apply the triangle area formula: A = w * h * 0.5. Prompt for width and height separately and print a nice message on the display saying, “The area of the triangle is….”

Exercise 3.2.4. Do the same for producing the volume of a sphere based on the radius of the sphere. I’ll invite you to look up the formula for volume of a sphere. For the value pi, you can insert the following statement into your program:

`pi = 3.14159265`