Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# KTByte CS82/CS84 Assignment 0\n",
- "\n",
- "## Variables and Operators\n",
- "\n",
- "In this ungraded assignment, you will explore the basics of Python. This Jupyter Notebook is meant to be a quick introduction to Python; while this is by no means a comprehensive tutorial of the language, it should contain enough information for you to do most of the assignements in our class. We fully expect students to look up how to do things in Python that we haven't learned in class.\n",
- "\n",
- "First, run the code below by double-clicking on it and hit Shift+Enter."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 37,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "9001\n",
- "helloworld\n",
- "The length of a is: 7 and the content is: [2, 5, 7, 0, 8, 1, 9]\n"
- ]
- }
- ],
- "source": [
- "from __future__ import print_function\n",
- "\n",
- "# create int variable\n",
- "x = 9001\n",
- "print(x)\n",
- "\n",
- "# create strings\n",
- "s = \"hello\"\n",
- "t = \"world\"\n",
- "print(s + t)\n",
- "\n",
- "# create list\n",
- "a = [2, 5, 7, 0, 8, 1, 9]\n",
- "print(\"The length of a is: \", len(a), \" and the content is: \", a)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Python is a *dynamically-typed* language, meaning you can create variables without specifying what its data type is. In the above example, we created 1 int variable, 2 string variables and 1 list variable (we call them lists instead of arrays in Python.)\n",
- "\n",
- "You can query the type of a variable or a value using the `type()` function"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 38,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "<type 'int'>\n",
- "<type 'str'>\n",
- "<type 'list'>\n"
- ]
- }
- ],
- "source": [
- "print(type(x))\n",
- "print(type(s))\n",
- "print(type(a))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "On the other hand, Python is a somewhat *strongly-typed*, i.e. you still have to be mindful of data types when performing operations. If you attempt to use the following code to contenate to a string variables, you will get an error:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 39,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "ename": "TypeError",
- "evalue": "cannot concatenate 'str' and 'int' objects",
- "output_type": "error",
- "traceback": [
- "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
- "\u001b[0;32m<ipython-input-39-1f3cf10ef9d8>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# TODO: use the str(x) function to convert 66 to a string and try running this again\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0ms\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"Route \"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0ms\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m66\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;31mTypeError\u001b[0m: cannot concatenate 'str' and 'int' objects"
- ]
- }
- ],
- "source": [
- "# TODO: use the str(x) function to convert 66 to a string and try running this again\n",
- "s = \"Route \"\n",
- "s += 66 \n",
- "print(s)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Booleans, If Statements and Comparisons\n",
- "\n",
- "Python uses the keywords `True` and `False` for boolean values (note the upper case). It uses the keywords: `and`, `or` and `not` for boolean operators. Also, Python does not use curly braces. To create an if statement, you indent the block of code inside the if."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "clap\n",
- "huh\n"
- ]
- }
- ],
- "source": [
- "# TODO: change the values of happy and know_it to experiement with the code below\n",
- "happy = True\n",
- "know_it = True\n",
- "\n",
- "if happy and know_it:\n",
- " print(\"clap\")\n",
- "\n",
- "if happy or know_it:\n",
- " print(\"huh\")\n",
- " \n",
- "if not know_it:\n",
- " print(\"what\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Comparison operators look and work just about the way you expect in Java: `==`, `!=`, `<`, `<=`, `>`, `>=`"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "high\n"
- ]
- }
- ],
- "source": [
- "x = 10\n",
- "if x > 5:\n",
- " print(\"high\")\n",
- "else:\n",
- " print(\"low\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "However, unlike Java, Python actually allows you to chain number comparison:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 42,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "x is within range\n"
- ]
- }
- ],
- "source": [
- "x = 10\n",
- "if 0 < x < 20:\n",
- " print(\"x is within range\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Note that `==` performs a value copmarison in Python, even for Strings and other objects. For exmaple, the following code show how to compare two Strings in Python:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 41,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "yay\n"
- ]
- }
- ],
- "source": [
- "x = \"hello\"\n",
- "if x == 'hello': # Python allows using both \"\" and '' for Strings\n",
- " print(\"yay\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Another Example with lists:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 43,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "True\n"
- ]
- }
- ],
- "source": [
- "list1 = [1, 2, 3]\n",
- "list2 = [1, 2, 3]\n",
- "print(list1 == list2) # True, because the content of the 2 lists are the same"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If you want to compare whether two variables are referring to the same object, use the `is` operator:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 44,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "False\n"
- ]
- }
- ],
- "source": [
- "print(list1 is list2) # False, because they are 2 separate lists, albeit with same elements"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In Python, we use `None` to represent null value (i.e. the non-existance of an object). Also use `is` when comparing whether something is `None`"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 45,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "True\n",
- "False\n"
- ]
- }
- ],
- "source": [
- "a = None\n",
- "print(a is None)\n",
- "print(a is not None)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Tuple\n",
- "\n",
- "If you need to wrap two (or more) values into one value, we can use a tuple. A tuple is basically an ordered pair/triple/quadruple/..."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 46,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "hello\n",
- "123\n"
- ]
- }
- ],
- "source": [
- "t = (0, 'hello', 123)\n",
- "print(t[0])\n",
- "print(t[1])\n",
- "print(t[2])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "You can unroll a tuple like this:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 47,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "hello\n",
- "123\n"
- ]
- }
- ],
- "source": [
- "a, b, c = t\n",
- "print(a)\n",
- "print(b)\n",
- "print(c)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Tuples are very useful if you want to a function return multiple values (we'll get to that in a later section.) Tuples are similar to lists on the surface, and some list functions work with tuples as well. The biggest difference between the two is that tuples are *immutable*, meaning its value cannot be changed after it is created."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 48,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3\n"
- ]
- },
- {
- "ename": "TypeError",
- "evalue": "'tuple' object does not support item assignment",
- "output_type": "error",
- "traceback": [
- "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
- "\u001b[0;32m<ipython-input-48-123686a85b3b>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# length of the tuple\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m5\u001b[0m \u001b[0;31m# this will give you an error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
- "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
- ]
- }
- ],
- "source": [
- "print(len(t)) # length of the tuple\n",
- "t[1] = 5 # this will give you an error"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Lists\n",
- "\n",
- "List will be used extensively through this class. Lists are 0-indexing just like Java, and can hold values of different types:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 49,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[2, 'hello', 5, 6, True]\n",
- "2\n"
- ]
- }
- ],
- "source": [
- "a = [2, 'hello', 5, 6, True]\n",
- "print(a)\n",
- "print(a[0])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "List indexing can be done with negative numbers, `a[-1]` denotes the last element, `a[2]` the second last, and so on."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 50,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "True\n",
- "6\n"
- ]
- }
- ],
- "source": [
- "print(a[-1])\n",
- "print(a[-2])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Note that it is still possible to get an index out of range error in Python; the valid indices of a list is from -length to length-1."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here are a few list functions that are really handy:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 51,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "7\n",
- "32\n",
- "0\n",
- "9\n",
- "[0, 1, 2, 5, 7, 8, 9]\n"
- ]
- }
- ],
- "source": [
- "a = [2, 5, 7, 0, 8, 1, 9]\n",
- "print(len(a)) # number of elements in list a\n",
- "print(sum(a)) # sum of all elements in list a\n",
- "print(min(a)) # min element in list a\n",
- "print(max(a)) # max element is list a\n",
- "a.sort() # sorts the list\n",
- "print(a)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Loops\n",
- "\n",
- "Python has a very simple for-each loop that you will be using quite a lot:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 53,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1\n",
- "2\n",
- "3\n",
- "4\n",
- "5\n"
- ]
- }
- ],
- "source": [
- "for x in [1, 2, 3, 4, 5]:\n",
- " print(x)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "It has a `range()` function that supports generating a list of integers over a given range:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 58,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "1\n",
- "2\n",
- "3\n",
- "4\n",
- "5\n",
- "6\n",
- "7\n",
- "8\n",
- "9\n",
- "=========\n",
- "2\n",
- "3\n",
- "4\n"
- ]
- }
- ],
- "source": [
- "for x in range(10): # print 0 to 9\n",
- " print(x)\n",
- "print(\"=========\")\n",
- "for x in range(2, 5): # print 2 to 4\n",
- " print(x)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "It also has a `while` loop that works the same as in Java:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 62,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "10\n"
- ]
- }
- ],
- "source": [
- "# calculate base-2 log of x by counting how many times we can divide x by 2 before it reaches 1\n",
- "x = 1024\n",
- "count = 0\n",
- "while x > 1:\n",
- " count += 1\n",
- " x /= 2\n",
- "print(count)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Functions and List Comprehension\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 52,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]\n"
- ]
- }
- ],
- "source": [
- "def isPrime(x):\n",
- " for i in range(2, x):\n",
- " if x % i == 0:\n",
- " return False\n",
- " return True\n",
- "\n",
- "primes = [p for p in range(2,1000) if isPrime(p)]\n",
- "print(primes)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 60,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[3, 5, 6, 9, 10, 12, 18, 20, 21, 24, 25, 27, 33, 35, 36, 39, 40, 42, 48, 50, 51, 54, 55, 57, 63, 65, 66, 69, 70, 72, 78, 80, 81, 84, 85, 87, 93, 95, 96, 99]\n"
- ]
- }
- ],
- "source": [
- "fizzbuzz = [x for x in range(100) if (x % 3 == 0 or x % 5 == 0) and x % 15 != 0]\n",
- "print(fizzbuzz)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": true
- },
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- If statements, == vs is, boolean operators\n",
- "- functions, named params, optional params\n",
- "- Tuples, Lists, Maps\n",
- "- List comprehension\n"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 2",
- "language": "python",
- "name": "python2"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 2
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython2",
- "version": "2.7.11"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement