Lab 5 - Python


Objectives
  1. Working with Numbers: data type, operations.
  2. Review the following elements: for statements.

Work with Numbers

>>>x=6

>>>y=3

>>>type(x)

>>>type(y)

>>>y=3.5

Variables in Pyhton do not have a type, so it is okay to change the type of the value assigned to a variable.

>>>type(y)

>>>int(y)

>>>type(y)

Type conversion function does not change the type of the value stored in memory.

>>>z=round(y)

>>>print(x,y,z)

>>>print(x/z)

>>>print(x//z)

>>>print(int(x/z))

>>>print(x%z)

>>>print(x/y)

>>>print(x//y)

 

Exercise 1:

Recall the changeAdder example shown in lecture. We will do the reverse in this lab: given an amount in cents that is less than a dollar, determines the method of giving the amount using the fewest coins. The result should be given in the form shown below (pennies first, then nickels, dimes, and quarters, each on a separate line).

Enter the total amount in cents (< 100): 33
Here's the change that uses the fewest coins:
    pennies: 3
    nickels: 1
    dimes: 0
    quarters: 1

Your program should use the input function to get the total amount of change from the user, then perform the necessary computations and output the result as shown above. Your program does not need to handle problematic inputs; it may assume that the number entered by the user is a positive integer less than 100.

You may first use some examples to figure out the algorithm, i.e. if this problem were in your mathematics homework instead of computer science, what would you do? Then you can write pseudocode for the algorithm, and translate it to a Python program.


For Loops

for <variable> in <sequence>:

<statements>

Example:

i = 1
for j in [1,2,3,4,5]:
    i = i * j
print i
What does the program compute? Change it, so that the user decides at which number to stop.  

Exercise 2:

Write a simple Python program that prompts the user for inputs x and y and computes "x to the power of y". Assume that we've lost the ** function so you cannot use it. Also assume that both inputs (x and y) are integers.

Optional Exercise:

Draw a star triangle as below:

*****

****

***

**

*


CS105