This commit is contained in:
winneratwin 2022-03-02 21:44:21 +00:00
parent 988d387625
commit 8f2ecd2268
Signed by: winneratwin
GPG Key ID: CDBC42F8803D689E
35 changed files with 684 additions and 0 deletions

3
week 5/Bubble_sort.md Normal file
View File

@ -0,0 +1,3 @@
files:
Bubble sorting_algorithm.ppt
bubble_sort_non-function_function_version.txt

View File

@ -0,0 +1,4 @@
Simple menu that calls a function
files:
menusample.py

5
week 5/Discount.md Normal file
View File

@ -0,0 +1,5 @@
Write a program for calculating the purchase price, taking into account the discount.
A 3% discount is provided if the purchase amount is more than £500,
and 5% - if the amount is more than £1000.

17
week 5/Discount.py Normal file
View File

@ -0,0 +1,17 @@
def int_input(text):
while True:
try:
user_input = int(input(text))
return user_input
except Exception:
print("error")
else:
break
total = int_input("enter total cost: ")
if total >1000:
total=total*0.95
elif total>500:
total=total*.97
print("final price: ",total)

View File

@ -0,0 +1,33 @@
Work in pairs
Play - guess the number. Here is the algorithm:
Welcome the player to the game and explain it.
Pick a random number between 1 and 100
ask the player for a guess
set the number of guesses to 1
while the player's guess does not equal the number
if the guess is greater than the number
tell the player to guess lower
otherwise
tell the player to guess higher
get a new guess from the player
increase the number of guesses by 1
congratulate the player on guessing the number
let the player know how many guesses it took
Develop the code for this program.
Test your solution

View File

@ -0,0 +1,7 @@
Limit the player to 6 guesses.
Adjust the algorithm.
Adjust the code
Test the revised version of the game

View File

@ -0,0 +1,3 @@
Here's a bigger challenge..........
Write the pseudocode for a program where the player and the computer trade places in the number guessing game. That is, the player picks a random number between 1 and 100 that the computer has to guess. Before you start, think about how you guess. If all goes well, try coding the game

View File

@ -0,0 +1,4 @@
"""
already did it:
https://github.com/winneratwin/numberguesser-using-functions
"""

View File

@ -0,0 +1,5 @@
2 programs to demonstrate the scope of local and global variables
files:
global_local.py
global_reach(1).py

View File

@ -0,0 +1,42 @@
# Global Reach
# Demonstrates global / local variables
def read_global():
print ("From inside the local scope of read_global(), value is:", value)
def local_variable():
value = -10
print ("From inside the local scope of local_variable(), value is:", value)
return value
def change_global():
global value
value += 100
print ("From inside the local scope of change_global(), value is:", value)
# main
# value is a global variable because we're in the global scope here
value = 10
print ("In the global scope, value has been set to:", value, "\n")
read_global()
print ("Back in the global scope, value is still:", value, "\n")
value =local_variable()
print ("Back in the global scope, value is still:", value, "\n")
change_global()
print ("Back in the global scope, value has now changed to:", value)
#raw_input("\n\nPress the enter key to exit.")

View File

@ -0,0 +1,40 @@
# Global Reach
# Demonstrates global variables
def read_global():
print ("From inside the local scope of read_global(), value is:", value)
def shadow_global():
value = -10
print ("From inside the local scope of shadow_global(), value is:", value)
def change_global():
global value
value = -10
print ("From inside the local scope of change_global(), value is:", value)
# main
# value is a global variable because we're in the global scope here
value = 10
print ("In the global scope, value has been set to:", value, "\n")
read_global()
print ("Back in the global scope, value is still:", value, "\n")
shadow_global()
print ("Back in the global scope, value is still:", value, "\n")
change_global()
print ("Back in the global scope, value has now changed to:", value)
#raw_input("\n\nPress the enter key to exit.")

View File

@ -0,0 +1,6 @@
This program demonstrates the use of functions in a menu driven program
Task 1 - Modify this program to create a fourth function to display "Bye" message
files:
menuexample.py

View File

@ -0,0 +1,41 @@
def checkBalance(number):
print ("Showing balance for account number " + number)
def addMoney(existing, deposit):
new_balance = existing + deposit
return new_balance
### why tf was this not a function already
def main():
#main thread of menu
finished = False
while not finished:
choice = input ("Hit 1, 2, 3, 4 or 0 to quit >> ")
while not choice in ['1', '2', '3', '4', '0']:
choice = input("That was not a valid selection, try again >> ")
print ("You chose " + choice)
if choice == '1':
number = input ("Enter account number >> ")
checkBalance(number)
if choice == '2':
existing = input ("Enter current balance >> ")
existing = float(existing)
deposit = input ("Enter amount to be deposited >> ")
deposit = float (deposit)
newbalance = addMoney(existing, deposit)
print ("Your new balance is £" + str(newbalance))
if choice == '0':
finished = True
goodbye()
def goodbye():
print ("Goodbye!")
# did you know that if you included a python file it is
# actually run so if you don't use this to ensure that this
# file is the main thread then it would run when in a include statement
if __name__ == "__main__":
main()

View File

@ -0,0 +1,8 @@
One function receives a value
The next function returns a value
The last function both receives and returns a value
files:
receive_and_return.py

View File

@ -0,0 +1,4 @@
This program featured in the inventdotpython.com site demonstrates the use of user defined functions
files:
dragon.py

View File

@ -0,0 +1,45 @@
import random
import time
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and hungry, and will eat you on sight.')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()

View File

@ -0,0 +1,4 @@
files:
calculation.py
condloop.py
functions.py

7
week 5/Task 1.md Normal file
View File

@ -0,0 +1,7 @@
Analyse this code.
A function is called but no parameters are passed to or from the function.
Create a program which calls a function to print "Happy Birthday to You" 4 times
files:
noparameters.py

17
week 5/Task 1.py Normal file
View File

@ -0,0 +1,17 @@
#Demonstrates calling a function
#the function is first of all defined
def reuseme(var):
print (var)
#main
counter = 0
while counter < 4:
reuseme("Happy Birthday to You")
counter+=1

17
week 5/Task 2.md Normal file
View File

@ -0,0 +1,17 @@
Analyse this program.
A function is called and a parameter is passed to the function
Amend your Happy Birthday program created in Task 1 to pass a variable name to the function and print a message such as:
Happy Birthday to Sue!
Happy Birthday to Sue!
Happy Birthday to Sue!
Happy Birthday to Sue!
Happy Birthday to Sue!

17
week 5/Task 2.py Normal file
View File

@ -0,0 +1,17 @@
#Demonstrates calling a function
#the function is first of all defined
def reuseme(name):
print ("Happy Birthday to {}!".format(name))
#main
counter = 0
while counter < 4:
reuseme("Sue")
counter+=1

0
week 5/Task 4.md Normal file
View File

56
week 5/Task 4.py Normal file
View File

@ -0,0 +1,56 @@
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: pcum
#
# Created:
# Copyright: (c)
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import random
def displayIntro():
print ("Welcome to the football match prediction program")
def chooseTeam():
team = input("Please Enter the name of Team")
return team
def score():
score = random.randint(0,9)
return score
def printscore(team, teamscore):
print (str(team)+" "+str(teamscore))
def checkresult(team1score,team2score):
if team1score == team2score:
print ("Re-match required")
# main program
#this function introduces the program which predicts the results of football matches
displayIntro()
#chooseTeam is called up twice and each time returns
#the name of a football team
team1 = chooseTeam()
team2 = chooseTeam()
#function score is called up and passed the team variable
#a score (between 0 and 9) is randomly calculated for the team and returned
team1score = score()
team2score = score()
#function printscore is called up twice
printscore(team1, team1score)
printscore(team2, team2score)
#function to check to see if the result is a draw - if it is a re-match message is displayed
checkresult(team1score,team2score)

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@ -0,0 +1,8 @@
Python has lots of pre-made functions, that you can use right now, simply by 'calling' them. 'Calling' a function involves you giving a function input, and it will return a value as output.
You have already used the random functions to generate random numbers
Python also lets you create functions of your very own.
files:
Functions.ppt

21
week 5/calculation.py Normal file
View File

@ -0,0 +1,21 @@
def calculation():
input1 = input ("Put in the first number here ")
num1 = int(input1)
input2 = input ("Put in your second number here ")
num2 = int(input2)
command = input ("Type a to add and b to subtract")
if (command == "a"):
answer = num1 + num2
elif (command == "b"):
answer = num1 - num2
else:
answer = 0
print ("The result was " + str(answer))
print ("What would you like to do today?")
calculation()
reply = input("Would you like to do another, or hit q to quit")
while (reply != "q"):
calculation()
reply = input("Would you like to do another, or hit q to quit")
print ("Goodbye!")

13
week 5/condloop.py Normal file
View File

@ -0,0 +1,13 @@
print ("Hello, I am Marvin, your personal bot")
print ("What can I do for you today?")
finished = False
counter = 0
#this is a boolean flag that will tell us to carry on, or kill, the loop
while not finished:
counter = counter + 1
print ("This is the body of the loop")
print ("Do you want to add, subtract, multiply or divide?")
answer = input("Write your command here! bye makes it quit.")
if (answer == "bye"):
finished = True
print ("Goodbye! You took " + str(counter) + " tries to get it right.")

56
week 5/footballdemo.py Normal file
View File

@ -0,0 +1,56 @@
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: anon
#
# Created:
# Copyright: (c)
# Licence: all rights reserved
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import random
def displayIntro():
print ("Welcome to the football match prediction program")
def chooseTeam():
team = input("Please Enter the name of Team")
return team
def score():
score = random.randint(0,9)
return score
def printscore(team, teamscore):
print (str(team)+" "+str(teamscore))
def checkresult(team1score,team2score):
if team1score == team2score:
print ("Re-match required")
# main program
#this function introduces the program which predicts the results of football matches
displayIntro()
#chooseTeam is called up twice and each time returns
#the name of a football team
team1 = chooseTeam()
team2 = chooseTeam()
#function score is called up and passed the team variable
#a score (between 0 and 9) is randomly calculated for the team and returned
team1score = score()
team2score = score()
#function printscore is called up twice
printscore(team1, team1score)
printscore(team2, team2score)
#function to check to see if the result is a draw - if it is a re-match message is displayed
checkresult(team1score,team2score)

30
week 5/functions.py Normal file
View File

@ -0,0 +1,30 @@
def sample_function():
print ("this is a function")
print ("and this is some stuff that it does")
answer = input ("Enter some stuff here")
print ("you wrote " + answer)
#stub procedures
def deposit():
print ("Deposit goes here")
pass
def withdraw():
print ("Withdraw goes here")
pass
def check():
print ("Check balance here")
pass
#main thread
print ("Welcome to the Bank of Mum")
answer = input ("1 to deposit, 2 withdraw, 3 check balance, 0 to quit")
if (answer == "1"):
deposit()
elif (answer == "2"):
withdraw()
elif (answer == "3"):
check()
else:
print ("Goodbye!")

65
week 5/maths(1).py Normal file
View File

@ -0,0 +1,65 @@
#open the previous hiscore file and read it in
with open ("highscores.txt", "r")as file:
highscore = file.read()
highscore = int(highscore)
print ("The previous highscore was " + str(highscore))
score = 0
print ("Welcome to the Maths quiz!")
print ("Here comes the first question!")
print ("Your score is currently " + str(score))
print ("The current highscore is " + str(highscore))
#first question
print ("What is the value of 2 x 2 x 2?")
answer = int(input("Type your answer here >> "))
if answer == 8:
score = score + 1
print ("Woo hoo! That was correct!")
print ("Your score is now " + str(score))
else:
print ("Boo hiss ... the answer was 8 :( ")
print ("Your score is now " + str(score))
#second question
print ("What is the square root of 121?")
answer = int(input("Type your answer here >> "))
if answer == 11:
score = score + 1
print ("Woo hoo! That was correct!")
print ("Your score is now " + str(score))
else:
print ("Boo hiss ... the answer was 11 :( ")
print ("Your score is now " + str(score))
#third question
print ("If you divide 23 by 5, what is the remainder?")
answer = int(input("Type your answer here >> "))
if answer == 3:
score = score + 1
print ("Woo hoo! That was correct!")
print ("Your score is now " + str(score))
else:
print ("Boo hiss ... the answer was 3 :( ")
print ("Your score is now " + str(score))
#fourth question
print ("What is the binary value 1101 in decimal?")
answer = int(input("Type your answer here >> "))
if answer == 13:
score = score + 1
print ("Woo hoo! That was correct!")
print ("Your score is now " + str(score))
else:
print ("Boo hiss ... the answer was 13 :( ")
print ("Your score is now " + str(score))
if score > highscore:
highscore = score
print ("Your score was " + str(score))
print ("The current highscore is " + str(score))
with open ("highscores.txt", "w")as file:
file.write(str(highscore))

32
week 5/menuexample.py Normal file
View File

@ -0,0 +1,32 @@
#Caroline Norton
#19 January 2010
import sys
#function to print a classcode
def printclass():
print "B4DD-F091A"
#function to print a name
def printmyname(myname):
print myname
#function to print hello
def printhello():
print "hello"
#start of main program (top level algorithm)
answer=0
while answer !="4": #controls menu
print """Menu
1) 1:Print myname
2) 2:Print classcode #choices in menu
3) 3:Print hello
4) 4:Exit"""
answer = raw_input("Make a selection> ") # user input
if answer == "1":printmyname("fred") # calls function
if answer == "2": printclass()
if answer == "3": printhello()
if answer == "4": print "Bye"

30
week 5/menusample.py Normal file
View File

@ -0,0 +1,30 @@
def checkBalance(number):
print ("Showing balance for account number " + number)
def addMoney(existing, deposit):
new_balance = existing + deposit
return new_balance
#main thread of menu
finished = False
while not finished:
choice = input ("Hit 1, 2, 3, 4 or 0 to quit >> ")
while not choice in ['1', '2', '3', '4', '0']:
choice = input("That was not a valid selection, try again >> ")
print ("You chose " + choice)
if choice == '1':
number = input ("Enter account number >> ")
checkBalance(number)
if choice == '2':
existing = input ("Enter current balance >> ")
existing = float(existing)
deposit = input ("Enter amount to be deposited >> ")
deposit = float (deposit)
newbalance = addMoney(existing, deposit)
print ("Your new balance is £" + str(newbalance))
if choice == '0':
finished = True
print ("Goodbye!")

17
week 5/noparameters.py Normal file
View File

@ -0,0 +1,17 @@
#Demonstrates calling a function
#the function is first of all defined
def reuseme():
print ("Hip Hip Horray")
#main
counter = 0
while counter < 5:
reuseme()
counter+=1

View File

@ -0,0 +1,27 @@
# Receive and Return
# Demonstrates parameters and return values
def display(message):
print message
def give_me_five():
five = 5
return five
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response
# main
display("Here's a message for you.\n")
number = give_me_five()
print "Here's what I got from give_me_five():", number
answer = ask_yes_no("\nPlease enter 'y' or 'n': ")
print "Thanks for entering:", answer
raw_input("\n\nPress the enter key to exit.")