Practice Problems - CS 303e

Covered topics: functions, loops, conditional statements, the input and raw_input functions

1. Write a function called `minimum` that takes 3 integer arguments, and returns the smallest of the three. The function will be called by the main function below.

```def main():     print minimum(4, 2, 8)     print minimum(-50, 2, 111) main()```

Output:
2
-50

2. Write a `sum` function that takes 2 integer arguments, and returns the sum of the arguments. For example, the following statement should assign variable `x` to be 17:

```x = sum(12, 5) ```3. Write a function `sumThem` that takes two integers, and returns the sum of all integers between them. For example, the following statement should set x to be 9, since 9 = 2+3+4:
`x = sumThem(2, 4)  # should also work to set x = sumThem(4, 2)`

4. Write a program that asks the user repeatedly to enter a negative integer. The user can stop by entering 0 or a positive integer. Your program should then print the smallest negative integer entered by the user.

Sample Output:
Enter a negative integer (or 0 or positive to stop): -3
Enter a negative integer (0 or positive to stop): -10
Enter a negative integer (0 or positive to stop): 4
The smallest negative integer you entered was -10.

5. Write a program that reads a string from the user, and then prints every other character (starting with the first character) of the string to the screen, one per line.

Sample Output:
Please enter your string: Hello world, Elvis lives!
H
l
o
w
r
d

l
i

i
e
!

6. Write a conditional statement that reads an integer from the user, and does the following:
If the integer is larger than 100, print "great".
If the integer is 100, print "ONE HUNDRED".
If the integer is greater than 50 and less than 100, print "50 to 100"
If the integer is less than or equal to 50, print "ack"

Do not use individual if statements - use an if-elif structure.

7. What is the value of x after the following code is executed?

```x = 25 if x%3 > 1:     x = 7 elif x/4 > 3:     x = 5 else:     x = 3```

8. What is the value of x after the following code is executed?

```def  times(a, b, c):     if a > c:         return b     else:         return a def main():     x = times(3, 2 9) main()```

9. Use the range function to create the following lists:
a) [2, 4, 6, 8, 10]
b) [100, 97, 94, 91, 88]
c) [-5, -4, -3, -2, -1, 0]
d) [3, 8, 13, 18, 23, 28]

10. Write a function `stars` that takes a positive integer, and prints a box of asterisks which is nxn.  For example, the call `stars(3)` prints the following:

***
***
***