Presentation is loading. Please wait.

Presentation is loading. Please wait.

Greater Miami valley computer science circle

Similar presentations


Presentation on theme: "Greater Miami valley computer science circle"— Presentation transcript:

1 Greater Miami valley computer science circle
Introduction to Python

2 Online sites for python
Doc site:

3 Algorithm design What is an Algorithm? “Algorithms are not a special type of operation, necessarily. They are conceptual, a set of steps that you take in code to reach a specific goal.” A thought process in common language. Like a cooking recipe but for a computer program. Recipes tell you how to accomplish a task by performing a number of steps. For example, to bake a cake the steps are: preheat the oven; mix flour, sugar, and eggs throughly; pour into a baking pan; and so forth. The goal of the algorithm is to help us complete the job more efficiently. *Pseudo-code is an informal language that helps programmers develop algorithms. (more math view)

4 Algorithm design However, “algorithm” is a technical term with a more specific meaning than “recipe”, and calling something an algorithm means that the following properties are all true: Unambiguous description that makes it clear what is to be implemented. Example: “Bake until done”, what does done mean. “Bake until the cheese begins to bubble” Defined set of inputs and a defined set of outputs Guaranteed to terminate and produce a result (finite) Most are guaranteed to produce the correct result If requirements on imputs are imposed they must be met (called preconditions) ex: only positive numbers

5 Algorithm design Now lets redo the cake following algorithm designs more technical rules preheat the oven mix flour, sugar, and eggs thoroughly pour into a baking pan Put pan in oven Take pan out when done SO what should we change, how do we make them more specific, finite, limited………

6 Algorithm design Preheat the oven to 400 degrees Fahrenheit
Preconditions: 4 cups flour, 1 cup sugar, 2large eggs, 4oz cocoa powder, 2 cups water Mix flour, sugar, eggs, cocoa, water thoroughly in a large mixing bowl Once mixture is smooth(no lumps), pour into a 9x12 baking pan Put pan in oven on the middle rack Bake for 30minutes, test center with a toothpick, if clean Take pan out. If toothpick is not clean, bake 5minutes more and test, repeat until clean. When clean take pan out of oven and set on stove top to cool. Does this meet the rules, is it clear? BTW don’t try at home it will taste awful.

7 Python code Basics Variables, strings, integers, input(), print(), Boolean, comparison operators Blocking and indentation While (loop), if then else Converting values int(), float(), str()

8 Game Theory Lets do some pseudo-code for this Prisoners Dilemna

9 Prisoner’s Dilemna Pseudo-code Get Prisoner1choice = “xxxx”
Get Prisoner2choice = “yyyy” Check table for results of choice If Prisoner1choice = “Confess” and Prisoner2choice = “Confess” then Result = “Both receive 3 years” Else check if Prisoner1choice = “Confess” and Prisoner2choice = “Deny” then Result = “Prisoner1 gets 1year, Prisoner2 gets 10years” Else check if Prisoner1choice = “Deny” and Prisoner2choice = “Confess” then Result = “Prisoner1 gets 10years, Prisoner2 gets 1year” Else only remaining result is Prisoner1choice = “Deny” and Prisoner2choice = “Deny” then Result = “Both Prisoners receive 2 years”

10 Prisoner’s dilemma python code
#Lets get Prisoners choices and make sure they respond correctly import sys prisoner1choice = “” prisoner2choice = “” while prisoner1choice != “confess” and prisoner1choice != “deny”: print(“Hello Prisoner1. Do you wish to confess to the crime, If so we will cut you a break on time served – confess or deny”) prisoner1choice = input() while prisoner2choice != “confess” and prisoner2choice != “deny”: print(“Hello Criminal 2. Do you wish to confess to the crime, if so we will cut you a break on time served confess or deny”) prisoner2choice = input()

11 Prisoner’s dilemma python code
Flow Control based on Diagram If prisoner1choice == “confess” and prisoner2choice == “confess”: print(“Prisoner 1 and 2 both get 3 years”) elif prisoner1choice == “confess” and prisoner2choice == “deny”: print(“Prisoner 1 gets 1 year and Prisoner 2 gets 10 years”) elif prisoner1choice == “deny” and prisoner2choice == “confess”: print(“Prisoner 1 gets 10 years and Prisoner 2 gets 1 year”) else: print(“Prisoner 1 gets 2 years and Prisoner 2 gets 2 years”)

12 Hangman discussion Discussion: Pics of Hangman (asci art)
words to choose from function random picker, function displayboard, function getguess function play again Main code to initialize variables and call functions Loop through guesses until win or lose Get guess, check guess, display hangman with correct/wrong Check game is done (win / lose)

13 Hangman with python Code topics covered · Multi-line Strings · Methods
·        Lists ·        The append() and reverse() list methods ·        The lower(), upper(), split(), startswith(), and endswith() string methods ·        The in and not in operators ·        The range() and list() functions ·        del statements ·        for loops ·        elif statements

14 Hangman with python Import random Hangmanpics = [‘’’ +-------+ | | |
| | | =========‘’’,’’’ | =========‘’’] Words = ‘ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider’.split()

15 Hangman with Python Def getRandomWord(wordlist):
#this function returns a random string from the passed list of strings wordIndex = random.randint(0,len(wordlist) – 1) return wordlist[wordIndex] Def displayBoard(Hangmanpics, missedletters, correctletters, secretword): print(Hangmanpics[len(missedLetters)]) print() print(‘Missed letters:’, end=‘ ‘) for letter in missedletters: print(letter, end=‘ ‘) blanks = ‘_’ * len(secretword) for I in range(len(secretword)): #replace blanks with correctly guessed letters if secretword[i] in correctletters: blanks = blanks[:i] + secretword[i] + blanks[i+1:] for letter in blanks: #show the secret word with spaces in between each letter

16 Hangman with Python Def getGuess(alreadyguessed):
#returns the letter the player entered. This functions makes sure the player entered a single letter and not something else. while True: print(‘Guess a letter.’) guess = input() guess = guess.lower() if len(guess) != 1: print(‘Please enter a single letter.’) elif guess in alreadyGuessed: print(‘You have already guessed that letter. Choose again.’) elif guess not in ‘abcdefghijklmnopqrstuvwxyz’: print(‘Please enter a Letter in the alphabet.’) else: return guess

17 Hangman with Python Def playagain():
#this function returns true if the player wants to play again, otherwise it returns false. print(‘Do you want to play again? (yes or no)’) return input().lower().startswith(‘y’) Print(‘H A N G M A N’) Missedletters = ‘’ Correctletters = ‘’ Secretword = getRandomWord(words) Gameisdone = False While True: displayboard(hangmanpics, missedletters, correctletters, secretword) #let the player type in a letter guess = getguess(missedletters + correctletters) if guess is secretword: correctletters = correctletters + guess #check if the player has won foundallletters = True

18 HangMan with python for I in range(len(secretword)):
if secretword[i] not in correctletters: foundallletters = False break if foundallletters: print(‘Yes! The secret word is “’ + secretword + ‘”! You have won!’) gameisdone = True else: missedletters = missedletters + guess #check if player has guessed too many times and lost if len(missedletters) == len(hangmanpics) – 1; displayboard(hangmanpics, missedletters, correctletters, secretword) print(‘You have run out of guesses!\nAfter ‘ + str(len(missedletters)) + ‘missed guesses and ‘ + str(len(correctletters)) + ‘correct guesses, the word was “’ + secretword + ‘”’)

19 Hangman with python #ask the player if they want to play again bt only if the game is done). if gameisDone: if playagain(): missedletters = ‘’ correctletters = ‘’ gameisdone = False secretword = getRandomWord(words) else: break


Download ppt "Greater Miami valley computer science circle"

Similar presentations


Ads by Google