You are on page 1of 1

Physics1220 Computing 1

Task Sheet 2
These exercises aim to:

1. Introduce methods for user input


2. Introduce the ideas of selection
a. Specifically to give you practice at writing Python programs involving
conditional (“if”) statements

Exercise 6: Computing Square-Roots


You have learned how to compute square-roots with the aid of Python’s math module. Now use
the text editor in Spyder to create a file named sqrt.py in your PythonExercises directory. In this
file, write a program that prompts the user to enter a number and then displays the square-root
of that number.

You can assume that the user always enters a non-negative numeric value. When testing your
program try providing a negative number or non-numeric input to see what happens.

Exercise 7: The Tutorial Group Problem


Suppose that a certain university department divides its students into tutorial groups. It is
obviously desirable that the groups are all the same size.

In a file named tutorials.py, write a program that prompts the user to enter two values: the first is
the number of students and the second number is the ideal size of tutorial groups. The program
should respond by displaying the total number of groups that would be formed, and the total
number of students who would be left out.

For example, if there were 100 students in groups of 4, there would be 25 groups and none left
over. If there were 100 students in groups of 6 there would be 16 groups and 4 students left over.
Obviously only whole numbers of students can be assigned to a tutorial group. You can assume
that the user always enters integers. Hint: You need to use the modulus operator, ‘%’.

Exercise 8: Selection Using if


In a file called names.py, create a program that

1. Reads in your given name as a string


2. Reads in your family name as a string
3. Compares the lengths of the two names and indicates which is longer

Note: You should use the Python function raw_input (which stores user input as a string) and will
also need Python’s built-in len function for this.

Summary
You have probably spotted some problems with these programs as you have gone along. What
happens if the user enters a string when your program expects a number? How does your square
root program handle a negative number? We will discuss how to handle situations like this
later…

You might also like