﻿

## Homework 8 (due 6/4) CSC 241

We finished talking about while loops and started on dictionaries. Next week, we'll see tuples and sets (6.1, 6.2), character encodings (6.3), randomness (6.4/6.5) and functions and variables (Chapter 7).

Submission: The homework is due by midnight (I will not accept late homeworks). You can submit your homework through d2l into the drop-box for this homework. Please prepare your homework as a single file containing all answers (e.g. doc, docx, or pdf, not a zip file).

When submitting programs, include the programs, together with screenshots of test-runs of your program (make sure screenshots are sized so the text is legible; resize and/or crop the images).

1. (Reading Assignment) (Re)read Sections 5.4-5.6, as well as Section 6.1 of the textbook.

2. (While, 25pt) Write a function stockgame() that implements a stock market game. You have an initial amount of money (in cash), say \$1000, and each share has an initial worth for \$50 when you start trading. Initially, you don't own any shares. In each round the system tells you what a share is worth, how much money you have, how many shares you own, and what they are worth (in total). You can issue three commands: stop, to stop the simulation, buy x to buy x shares, and sell x to sell x shares. The system needs to check whether the operation you request is legal (you cannot overspend or sell stocks you don't own). If your request is not legal, it'll ignore the request and warn you, otherwise it performs the trade you requested.

At the end of each stage of the game, the value of the stock changes by a certain amount; to simulate that change, we'll use the random module, specifically the function gauss in the random module; e.g. you can use the following:

change = gauss(1,5)

this means the average increase will be 1, with an expected deviation of +/- 5. Following is a test-run of the program. This is a more complex program than any you've every written. This is a pretty large-scale program. Do this in small steps:

a) [5pt] Set-up variables for all the relevant information.

b) [5pt] Write the basic loop promping the user for input. Add the ouput telling the user about the current state of affairs (share price, cash, stocks owned. Assume for the time that the share price stays flat at the initial value (\$50). Format values using '\${:2.f}'.format(value).

c) [10pt] Implement buy, sell, stop. First without restrictions. Then with the checks to make sure you don't overspend, or sell stocks you don't own.

d) [5pt] Add the random fluctuation of the share price to the loop. Output information about what happened to the share price (went up, went down). (Don't worry about the share price becoming negative.)

The following test-run was done with change = gauss(1,10) which leads to more extreme fluctuation.