{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Introduction to Python, Part 2\n",
"This skill homework shows a few extensions to the previous homework on variables, lists, and functions, then covers some completely new territory.\n",
"\n",
"## More on Operators\n",
"Python, of course, has the traditional mathematical operators `+`, `-`, `*`, and `/` for addition, subtraction, multiplication and division. The one important note is that division with integers (since we are using python 3)\n",
"will always give a float. \n",
"\n",
"In the cell below try some integer division like\n",
"```\n",
"print(33/33)\n",
"print(33/2)\n",
"print(33/2)\n",
"```\n",
"\n",
"## Additional Mathematical Operators\n",
"\n",
"There are three additional math operators you should know.\n",
"\n",
"The remainder operator, `%`, does a division and returns the remainder. It works with both integer and float division. Try the following remainders:\n",
"```\n",
"print(255 % 16)\n",
"print(4.2%1.5)\n",
"```\n",
"\n",
"Next the power operator is `**`. (*Many languages use the `^`, but in python this is the bitwise XOR operator, so be careful!*) It raises the first number to the power of the second. If both operators are integers, it will return an integer if possible. Try the following:\n",
"\n",
"```\n",
"print(2**3)\n",
"print(3**2)\n",
"print(2**(-1))\n",
"print(1.2**1.2)\n",
"```\n",
"**Note: I usually do not put spaces around the power operator because it has higher precedence than the other mathematical operators.**\n",
"\n",
"Finally, the *integer division* or *floor division* operator is `//`. This acts like normal integer division if the operators are integers. The odd feature is that the answer is rounded *down*, even if the answer is negative. If either or both of the operands are floats, the answer will be a float round down. Try the following floor divisions:\n",
"```\n",
"print(3//2)\n",
"print(-3//2)\n",
"print(100.0//3.0)\n",
"```\n",
"\n",
"Look at the results to make sure you understand how these operators work."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.0\n",
"16.5\n",
"16.5\n"
]
}
],
"source": [
"print(33/33)\n",
"print(33/2)\n",
"print(33/2)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"15\n",
"1.2000000000000002\n"
]
}
],
"source": [
"print(255 % 16)\n",
"print(4.2%1.5)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"8\n",
"9\n",
"0.5\n",
"1.2445647472039776\n"
]
}
],
"source": [
"print(2**3)\n",
"print(3**2)\n",
"print(2**(-1))\n",
"print(1.2**1.2)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"-2\n",
"33.0\n"
]
}
],
"source": [
"print(3//2)\n",
"print(-3//2)\n",
"print(100.0//3.0)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## Compound Assignments Like `+=`\n",
"Like `C` and most modern languages, python supports *compound assignments*. These are statements that modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand:\n",
"\n",
"The following pairs of statements have the same result:\n",
"\n",
"`y += x` or `y = y + x`\n",
"\n",
"even\n",
"\n",
"`price *= units + 1` is the same as `price = price * (units+1)`\n",
"\n",
"In the code cell below, create some variables and try compound assignments on them. Here are my suggestions, but feel free to try your own.\n",
"```\n",
"x = 2\n",
"y = 3\n",
"y += x\n",
"x *= 1.6\n",
"y += x\n",
"print(x)\n",
"print(y)\n",
"```\n",
"\n",
"## Are You Remembering Tab Completion?\n",
"Keep trying tab completion. Once you get used to it, you will regret using a software development system that doesn't have it."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7\n",
"14\n",
"98\n"
]
}
],
"source": [
"r=7\n",
"print(r)\n",
"r += 7\n",
"print(r)\n",
"r *= 7\n",
"print(r)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Boolean Variables and Operators (`True` & `False`)\n",
"You often need to make true or false decisions in computer code. This is often done with *Boolean* or true-false expressions. In python the two values are `True` and `False`. Boolean variable can also be defined. In addition zero is `False` and a non-zero number is `True`\n",
"\n",
"Some Boolean operators are `not`, `and`, and `or`. Note that in python, these are spelled out. \n",
"\n",
"In the cell below create the variable `tr` with the value `True`, and the varaible `fa` with the value `False`. Then print out `not tr`, `tr and fr`, and `tr or fa`. Make sure you understand the results before moving on.\n",
"\n",
"My examples are\n",
"```\n",
"tr = True\n",
"fa = False\n",
"print(not tr)\n",
"print(not fa)\n",
"print(tr and fa)\n",
"print(tr or fa)\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n",
"True\n",
"False\n",
"True\n"
]
}
],
"source": [
"tr = True\n",
"fa = False\n",
"print(not tr)\n",
"print(not fa)\n",
"print(tr and fa)\n",
"print(tr or fa)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Comparison Operators `==`, `>`, etc.\n",
"Python has the usual comaprison operators `==` (for equal to), `!=` (not equal to), and the math-type comparisons `>=`, `>`, `<`, `<=`. All of these operators evaulate to either `True` or `False`. In the cell below try each of these by typing something like\n",
"```\n",
"print(3 < 2)\n",
"```\n",
"Make one example of each comparison operator."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n"
]
}
],
"source": [
"print(27>8)\n",
"print(17==18)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Flow control with `if`, `elif`, and `else`\n",
"The following is an example of an if statement:\n",
"```\n",
"answer = 3\n",
"if answer > 2:\n",
" print(\"Greater than 2\")\n",
" print(\"Go fish\")\n",
"print(\"Done\")\n",
"```\n",
"\n",
"Note the `:` after the `if` statement. This is required. Also note that the lines indented are only executed if the expression is true and the line dedented to the same position as the `if` statement is always executed. This is a reminder that indentation is very important in python.\n",
"\n",
"Go ahead and run the lines above in the code cell below."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Greater than 2\n",
"Go fish\n",
"Done\n"
]
}
],
"source": [
"answer = 3\n",
"if answer > 2:\n",
" print(\"Greater than 2\")\n",
" print(\"Go fish\")\n",
"print(\"Done\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## The `else` Statement\n",
"Many times you want to choose between two strategies. The `else` statement works like this:\n",
"```\n",
"answer = 5\n",
"if answer > 2:\n",
" print(\"Greater than the mystery number\")\n",
" print(\"Go fish\")\n",
"else:\n",
" print(\"Less than or equal to the mystery number\")\n",
" print(\"Try another guess\")\n",
"print(\"Done\")\n",
"```\n",
"Again, the block that is executed when the `if` experssion is false must be indented. Try this in the cell below. Rerun the cell with different values for `answer`."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Less than or equal to the mystery number\n",
"Try another guess\n",
"Done\n"
]
}
],
"source": [
"answer = 2\n",
"if answer > 2:\n",
" print(\"Greater than the mystery number\")\n",
" print(\"Go fish\")\n",
"else:\n",
" print(\"Less than or equal to the mystery number\")\n",
" print(\"Try another guess\")\n",
"print(\"Done\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Multiple Choices. The `elif` Statement\n",
"Finally if there are multiple branches you can use the `elif` statement which stands for *else if condition*. You can stack together multiple `elif` statements in after an `if` statement. Here is an example:\n",
"```\n",
"answer = 2\n",
"if answer > 2:\n",
" print(\"Guess is too big\")\n",
" print(\"Go fish\")\n",
"elif answer == 2:\n",
" print(\"Correct! Game Over!\")\n",
"else:\n",
" print(\"Guess is too small\")\n",
" print(\"Try another guess\")\n",
"print(\"Done\")\n",
"```\n",
"Enter this code and play the game using different guesses for `answer`."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Guess is too small\n",
"Try another guess\n",
"Done\n"
]
}
],
"source": [
"answer = -1\n",
"if answer > 2:\n",
" print(\"Guess is too big\")\n",
" print(\"Go fish\")\n",
"elif answer == 2:\n",
" print(\"Correct! Game Over!\")\n",
"else:\n",
" print(\"Guess is too small\")\n",
" print(\"Try another guess\")\n",
"print(\"Done\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Make This a Function\n",
"Many times I will develop code in a cell (usually more complicated than our guessing game), then when it is working make it into a function. In the cell below, write a function with one argument being the guess, then test your code by guessing answers that are too small, too big and just right. Define the answer as a global variable in the cell. You also want your function to return `True` when the guess is correct and `False` when the answer is wrong.\n",
"\n",
"I have given you an outline for the function. You have to fill it in and test it. \n",
"\n",
"BTW, the `#` symbol starts a comment. The `#` and anything after it in a line is ignored.\n",
"\n",
"**Note: The code in the cell below WILL NOT WORK. You have to fix it to make it run.**"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"your guess is correct\n"
]
}
],
"source": [
"answer =20 # set answer an integer number\n",
"\n",
"# next start the function definition\n",
"def game(guess):\n",
" # print the value guessed\n",
" print(\"Your guess is \", guess)\n",
"if answer>20:\n",
" print(\"Your guess is too big\")\n",
" print(\"Go fish\")\n",
"elif answer==20:\n",
" print (\"your guess is correct\")\n",
"else:\n",
" print(\"Try another guess\")\n",
" print(\"Done\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# `while` Loops\n",
"Many times your code has to loop until some ending condition is met. Now that you have your function `game`, here is how you can get input from the user, play the game, and quit when the answer is right. I also generate a random integer from 1 to 10.\n",
"\n",
"The code in the cell is not quite right. You should change it to correctly keep track of the number of guesses.\n",
"\n",
"**Note: this code uses the function `game` you fixed above.**"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"cocalc": {
"outputs": {
"1": {
"name": "input",
"opts": {
"password": false,
"prompt": "Enter your guess: "
},
"output_type": "stream",
"value": "20"
}
}
},
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Guess a number from 1 to 10\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": "Enter your guess: 20"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Your guess is 20\n",
"It took you 1 guesses to get it right!\n"
]
}
],
"source": [
"from random import randint\n",
"nGuesses = 1\n",
"answer = randint(1,10)\n",
"print(\"Guess a number from 1 to 10\")\n",
"yourGuess = int(input(\"Enter your guess: \"))\n",
"while game(yourGuess) == True:\n",
" yourGuess = int(input(\"Enter your guess: \"))\n",
"print(\"It took you\", nGuesses, \"guesses to get it right!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Other Topics\n",
"There are many other topics, but the material covered should get you started."
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Conclusion\n",
"This ends the second skills homework for python. This tour through operators and function should get you started. Feel free to contact me with any questions by e-mail.\n",
"\n",
"The next topics are libraries, arrays from the `numpy` library, and reading and writing data files."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 1,
"metadata": {
},
"output_type": "execute_result"
}
],
"source": [
"from IPython.core.display import HTML\n",
"def css_styling():\n",
" styles = open(\"custom.css\", \"r\").read()\n",
" return HTML(styles)\n",
"css_styling()"
]
}
],
"metadata": {
"anaconda-cloud": {
},
"kernelspec": {
"display_name": "Python 3 (system-wide)",
"language": "python",
"metadata": {
"cocalc": {
"description": "Python 3 programming language",
"priority": 100,
"url": "https://www.python.org/"
}
},
"name": "python3",
"resource_dir": "/ext/jupyter/kernels/python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}