Skip to content

Instantly share code, notes, and snippets.

@battis
Created May 6, 2013 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save battis/5528312 to your computer and use it in GitHub Desktop.
Save battis/5528312 to your computer and use it in GitHub Desktop.
{
"metadata": {
"name": "CS1 Examples"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": "#Example Scripts\n\n###Checking for Odd/Even Numbers with modulos\nAn example of why the modulos operator can be quite handy!"
},
{
"cell_type": "code",
"collapsed": true,
"input": "# Python code # English translation\n\nx = int(input('Gimme a number: ')) # gimme a number\n\nremainder = x % 2 # store the remainder of that number\n # divided by 2 into remainder (the\n # single = means that this is an\n # assignment (the value of remainder\n # will be changed)\n\nif remainder == 1: # hey, is the value stored in remainder\n # equal to 1? The double == means that\n # this is a comparison, and the value\n # of remainder will not be changed\n # (This is what's known as a\n # 'branching conditional statement1 --\n # the code has two branches and you\n # choose which one to follow based on\n # a condition)\n \n print(x,'is odd') # if it is, print out that our number\n # is odd\n print('I would like a pony')\nelse: # if it isn't (equal to 1)...\n print(x,'is even') # ...print out that the number is even",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": "17 is odd\nI would like a pony\n"
}
],
"prompt_number": 3
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Single vs. Double Quotes\nOne theory, [as promulgated on Stack Overflow](http://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python)\n\n###Gettysburg Address madlib\nConvert the Gettysburg Address into a madlib (to demonstrate print() formatting)"
},
{
"cell_type": "code",
"collapsed": false,
"input": "speech = '''Four score and seven years ago our fathers brought forth on this continent, a new {1}, conceived in Liberty, and dedicated to the proposition that all men are created equal. \n\nNow we are engaged in a great civil {0}, testing whether that {1}, or any {1} so conceived and so dedicated, can long endure. We are met on a great battlefield of that {0}. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that {1} might live. It is altogether fitting and proper that we should do this. \n\nBut, in a larger sense, we cannot dedicate\u2014we cannot consecrate\u2014we cannot hallow\u2014this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us\u2014that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion\u2014that we here highly resolve that these dead shall not have died in vain\u2014that this {1}, under God, shall have a new birth of freedom\u2014 and that government of the people, by the people, for the people, shall not perish from the earth.'''\n\ndef gettysburgAddress(noun, noun2):\n print(speech.format(noun, noun2))\n\nrealOrMadLib = int(input('''Please choose between:\n 1) The real Gettysburg Address\n 2) A madlib Gettysburg Address\n'''))\n\nif (realOrMadLib == 1):\n gettysburgAddress('war', 'nation')\nelif (realOrMadLib == 2):\n gettysburgAddress(input('Give me a noun: '), input('Give me another noun: '))\nelif realOrMadLib == 42:\n print('What\\'s the meaning of life, the universe and everything?')\nelse:\n print('You didn\\'t choose something that I know how to do!')",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Annoying Younger Sibling\nA script to immitate a younger sidling who won't stop repeating you (and therefore behaves like a while loop)"
},
{
"cell_type": "code",
"collapsed": false,
"input": "# define a function that repeats back to the user\n# anything they type in, but the computer says\n# \"You said, _____\"\n\ndef littleSibling(littleSiblingSays):\n youSaid = input(littleSiblingSays)\n print('You said:', youSaid)\n return youSaid\n\n# Then call that function\n\nsafeWord = 'go'\nwhile safeWord != 'I\\'m going to tell mom':\n safeWord = littleSibling('nyah, nyah ')",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Calculating Fibonacci Numbers\nThis is an example of the power of defining a block of code as a function!"
},
{
"cell_type": "code",
"collapsed": false,
"input": "def fibonacci(n):\n ''' Calculate the nth fibonacci number recursively'''\n # catch the base cases (the first and second numbers in sequence)\n if n == 1:\n return 1\n elif n == 2:\n return 1\n else: # calculate each number based on the prior two numbers\n return fibonacci(n-2) + fibonacci(n-1)\n\ndef prettyNumber(number):\n '''Convert a number to a string representing the 'pretty' version of that\n number (1st, 2nd, 3rd, 4th, etc.)'''\n string = str(number); # convert to a string\n\n # examine the last digit of the number and format appropriately\n if number % 10 == 3:\n string = string + 'rd'\n elif number % 10 == 2:\n string = string + 'nd'\n elif number % 10 == 1:\n string = string + 'st'\n else:\n string = string + 'th'\n \n return string\n\nnumber = int(input('Enter a number: '))\nprint('The', prettyNumber(number), 'Fibonacci number is', fibonacci(number))\n",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Format a string using a dictionary\nA quick and easy way to apply multiple values to the format() function of string"
},
{
"cell_type": "code",
"collapsed": false,
"input": "\"\"\"A tiny English to Spanish dictionary is created,\nusing the Python dictionary type dict.\nThen the dictionary is used, briefly.\n\"\"\"\n\ndef createDictionary():\n '''Returns a tiny Spanish dictionary'''\n spanish = dict()\n spanish['hello'] = 'hola'\n spanish['yes'] = 'si'\n spanish['one'] = 'uno'\n spanish['two'] = 'dos'\n spanish['three'] = 'tres'\n spanish['red'] = 'rojo'\n spanish['black'] = 'negro'\n spanish['green'] = 'verde'\n spanish['blue'] = 'azul'\n return spanish\n\ndef main():\n dictionary = createDictionary()\n print('{0} {1} {2}'.format(dictionary['hello'], dictionary['three'], dictionary['red']))\n print('{hello} {three} {red}'.format(**dictionary))\n\nmain()",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Printing a diagonal line of stars\nThis is a handy example to that can be expanded to solve a number of the patterns in [Python Challenge: Patterns, Round 2](https://stmarksschool.instructure.com/courses/15/assignments/1393?module_item_id=33250)"
},
{
"cell_type": "code",
"collapsed": false,
"input": "starCount = list(range(3))\nfor star in starCount:\n spaceCount = list(range(star))\n for space in spaceCount:\n print(' ', sep='', end='')\n print('*')",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###What do 'sep' and 'end' really do?\nA quick demonstration of their utility (and how to make good use of it)"
},
{
"cell_type": "code",
"collapsed": false,
"input": "# this is us tweaking some settings\nprint('this','is','a','test', sep = '', end = '')\n\n# this is what \"normally\" happens\nprint('my','second','test', sep = ' ', end = '''\n''')\n\n# remember, the separator only matters, if you're printing more than one\n# thing in the same command\nprint('one', sep = 'KUMQUAT') # one\nprint('one', 'two', sep = 'PEACHES') # onePEACHEStwo",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Generate a list based on a user-input number\nHooking together user input and the lists that we've seen used to power for loops"
},
{
"cell_type": "code",
"collapsed": false,
"input": "myNumber = int(input('Gimme a number: '))\nmyList = list(range(myNumber))\nprint(myList)",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Computer Science Dictionary (compact version)\nThis is the version of the [Computer Science Dictionary challenge](https://stmarksschool.instructure.com/courses/15/assignments/1390?module_item_id=33247) that you might write if you were really confident in your code, and weren't worried about complicated debugging if it doesn't work."
},
{
"cell_type": "code",
"collapsed": false,
"input": "csDictionary = dict()\ncsDictionary['bandwidth'] = 'The amount of data that can be transmitted in a fixed amount of time.'\ncsDictionary['bios'] = 'Simple instructions to for booting up the computer'\n\nuserInput = 'yes'\nwhile userInput != 'stop':\n userInput = input('What word would you like me to define? ').lower()\n if userInput in csDictionary:\n print(userInput, ':', csDictionary[userInput])\n else:\n print('no idea what you\\'re talking about')",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Computer Science Dictionary (readable version)\nThis is the version of the [Computer Science Dictionary challenge](https://stmarksschool.instructure.com/courses/15/assignments/1390?module_item_id=33247) that you might write if you wanted to make sure that each part of the pprogram worked \u2014 and couldn't be broken \u2014 before moving on to the next part (defining each step as a separate function)."
},
{
"cell_type": "code",
"collapsed": false,
"input": "def makeDictionary\n '''define our computer science dictionary'''\n csDictionary = dict()\n csDictionary['bandwidth'] = 'The amount of data that can be transmitted in a fixed amount of time.'\n csDictionary['bios'] = 'Simple instructions to for booting up the computer'\n return csDictionary\n\ndef inTheDictionary(term, dictionary):\n if term in dictionary:\n return True\n else:\n return False\n\ndef lookup(dictionary):\n userInput = input('What word would you like me to define? ').lower()\n if inTheDictionary(userInput, dictionary):\n definition = userInput + ' is defined as: ' + dictionary[userInput]\n print(definition)\n else:\n print('no idea what you\\'re talking about')\n return userInput\n\ndef main():\n d = makeDictionary()\n userWantsMore = 'yes'\n while userWantsMore != 'stop':\n userWantsMore = lookup(d)\n\nmain()",
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment