Score function for a flashcard game in python - python

I am trying to add a very simple score function to an also very simple flashcard game and I can't make the game remember the value of the variable containing the score (it always resets it 0). The score is obviously relying on the honesty of the user (and that's fine) that has to press "Y" when guessing the word.
from random import *
def add_score():
pos_score = 0
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
pos_score += 1
print(pos_score)
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
def add_flashcard():
""" This function allows the user to add a new
word and related value to the glossary. It will
be activated when pressing the "a" button.
"""
key = input("Enter the new word: ")
value = input("Enter the definition: ")
glossary[key] = value
print("New entry added to glossary.")
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
add_score()
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
Some notes:
I am aware that right now only the positive score is implemented in the code, but I figured it would be better to proceed step by step and have that working first.

Problem
In your def add_score(), you initialise the variable to 0 every time. Also, it is a local variable, which means you can only reference it from within your function add_score(). This means that every time you exit that function, that variable is completely deleted.
Solution
You need to make that a global variable, that is, initialise it to 0 at the start of the game, and outside your function. Then inside your add_score you simply reference to the global variable and increase it without initialising it every time:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
global pos_score
pos_score += 1
print(pos_score)
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
add_score()
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
Note I skipped the irrelevant functions. However, usually changing the scope of variables like this is considered bad practice. What you should do is either have a class -- a bit overly complicated for this example -- or return a value to add from your add_score and add that value in the main loop. This would be the code:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
#global pos_score
#pos_score += 1
#print(pos_score)
return 1
return 0
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
def add_flashcard():
""" This function allows the user to add a new
word and related value to the glossary. It will
be activated when pressing the "a" button.
"""
key = input("Enter the new word: ")
value = input("Enter the definition: ")
glossary[key] = value
print("New entry added to glossary.")
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
pos_score += add_score()
print(pos_score)
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')

Related

Random dictionary searches which never returns same item twice

Is there a way when asking the program to chose a random entry from a dictionary of key-value entries is there a way that once every entry has been picked once the program will let the user know that all entries have been picked and then stop, ultimately only allowing each entry to be picked once so, if there are only 3 entries the program will only run 3 times and if there are 100 entries it will run 100 times and so on? New to python coding so please bear with me.
from random import *
def show_keys():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(keys))
print('Define: ', random_key)
input('Press return to see the definition')
print(keys [random_key])
# Set up the keys
keys = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
# The loop
exit = False
while not exit:
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_keys()
else:
print('You need to enter either q or s.')
You can get the keys from the dictionary, select random elements from that list, get the dictionary entry and remove the key from the list subsequently.
import random
dictionary = {
'one': '1',
'two': '2',
'three': '3'
}
# getting list of keys from dictionary
keys = list(dictionary.keys())
print(keys)
# picking random elemt from list
elem = random.choice(keys)
print(elem, dictionary.get(elem))
# remove an element from a list
keys.remove(elem)
print(keys)
Use a set to collect which keys you aready asked for.
Provide the set and the dict to the function that asks for a definition so it can add a new key to it - do not use globals.
Loop until either no more guesses possible (len(already)==len(data)) and handle that case or until user wants to quit:
from random import choice # do not import ALL - just what you need
def show_keys(d,a): # provide data and already used key set
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
d : your dict of keys and definitions
a : a set of already used keys
"""
# choice only for those keys that are not yet used
random_key = choice( [k for k in d if k not in a] )
print('Define: ', random_key)
input('Press return to see the definition')
print(d [random_key])
# add used key to a - you could ask (y/n) if the definition was correct
# and only then add the key - if wrong it has a chance of being asked again
a.add(random_key)
# Set up the data with keys and defs
data = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
# set up already seen keys
already = set()
# The loop
while True: # loop until break
# nothing more to guess
if len(already)==len(data):
y = input("Game over. Play again? [y, ]").lower()
if y=="y":
# reset set of seen stuff to empty set()
already = set()
else:
break
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
break
elif user_input == 's':
# provide data and already to the function, don't use globals
show_keys(data,already)
else:
print('You need to enter either q or s.')
Alternativly: create a shuffled list and use that:
from random import shuffle
data = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
already = set()
shuffled = list(data.items())
shuffle(shuffled)
# The loop
while shuffled:
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
break
elif user_input == 's':
key,value = shuffled.pop()
print('Define: ', key)
input('Press return to see the definition')
print(value)
else:
print('You need to enter either q or s.')

why does this python while loop not work in the program?

I'm trying to run the program in the following article:
https://blockgeeks.com/guides/python-blockchain-2/
I've copied all of the code into my Spyder IDE. When i run it there's a while loop which starts up asking the user to choose a number from the list of options it prints.
After selecting a number the program should perform the requested action. When i select it though it just loops back to the start of the while loop.
It appears to be ignoring the rest of the code in the while loop (the if statement part).
Confusingly if i take the parts of the code from the program which are used in the while loop and run them separately they work i.e if i run the below code and select the number 1 for my choice it will run the code in the if statement.
Why would the if statement run here but not in the main program?
#function 1:
def get_user_choice():
user_input = input("enter a number: ")
return user_input
#function 2:
def get_transaction_value():
tx_recipient = input('Enter the recipient of the transaction: ')
tx_amount = float(input('Enter your transaction amount '))
return tx_recipient, tx_amount
while True:
print("Choose an option")
print('Choose 1 for adding a new transaction')
print('Choose 2 for mining a new block')
print('Choose 3 for printing the blockchain')
print('Choose anything else if you want to quit')
user_choice = get_user_choice()
if user_choice == '1':
tx_data = get_transaction_value()
print(tx_data)
Update:
Sorry i realise i may not have been very clear what the problem is.
The above code is part of the code from the entire program and runs as expected in isolation from the main program.
The below code is the entire program from the article in the link. It includes all of the code in the program. If i run this main program the while loop doesn't use the if statement. It appears to just be breaking straight out of the loop after i select 1, 2 or 3 (any other number should break out of the loop anyway).
Here's a link for a screen shot showing what the console looks like after i have selected the number 1 for the option.
https://ibb.co/RNy2r0m
# Section 1
import hashlib
import json
reward = 10.0
genesis_block = {
'previous_hash': '',
'index': 0,
'transaction': [],
'nonce': 23
}
blockchain = [genesis_block]
open_transactions = []
owner = 'Blockgeeks'
def hash_block(block):
return hashlib.sha256(json.dumps(block).encode()).hexdigest()
# Section 2
def valid_proof(transactions, last_hash, nonce):
guess = (str(transactions) + str(last_hash) + str(nonce)).encode()
guess_hash = hashlib.sha256(guess).hexdigest()
print(guess_hash)
return guess_hash[0:2] == '00'
def pow():
last_block = blockchain[-1]
last_hash = hash_block(last_block)
nonce = 0
while not valid_proof(open_transactions, last_hash, nonce):
nonce += 1
return nonce
# Section 3
def get_last_value():
""" extracting the last element of the blockchain list """
return(blockchain[-1])
def add_value(recipient, sender=owner, amount=1.0):
transaction = {'sender': sender,
'recipient': recipient,
'amount': amount}
open_transactions.append(transaction)
# Section 4
def mine_block():
last_block = blockchain[-1]
hashed_block = hash_block(last_block)
nonce = pow()
reward_transaction = {
'sender': 'MINING',
'recipient': owner,
'amount': reward
}
open_transactions.append(reward_transaction)
block = {
'previous_hash': hashed_block,
'index': len(blockchain),
'transaction': open_transactions,
'nonce': nonce
}
blockchain.append(block)
# Section 5
def get_transaction_value():
tx_recipient = input('Enter the recipient of the transaction: ')
tx_amount = float(input('Enter your transaction amount '))
return tx_recipient, tx_amount
def get_user_choice():
user_input = input("Please give your choice here: ")
return user_input
# Section 6
def print_block():
for block in blockchain:
print("Here is your block")
print(block)
# Section 7
while True:
print("Choose an option")
print('Choose 1 for adding a new transaction')
print('Choose 2 for mining a new block')
print('Choose 3 for printing the blockchain')
print('Choose anything else if you want to quit')
user_choice = get_user_choice()
if user_choice == 1:
tx_data = get_transaction_value()
recipient, amount = tx_data
add_value(recipient, amount=amount)
print(open_transactions)
elif user_choice == 2:
mine_block()
elif user_choice == 3:
print_block()
else:
break
[1]: https://i.stack.imgur.com/FIrn7.png
When comparing values, Python takes a stronger route regarding data types than some other languages. That means no string in Python will equal a number.
Or in other terms "1" == 1 will be False.
That means you have to consider that in Python 3 you will receive a string from input() (not necessarily so in Python 2).
You can either compare this directly to another string:
user_choice = input()
if user_choice == "1":
print("You chose item 1")
Or you can convert it into a number first and compare it to a number:
user_choice = int(input())
if user_choice == 1:
print("You chose item 1")
Note that in the former case it might not be robust if the user enters extra spaces and in the latter case it will fail very loudly with an exception if the user doesn't enter an integer (or even nothing at all).
Both ways can be handled with extra code if necessary. In the former case, you can strip whitespace with user_input = input().strip() and in the latter case you can catch the exception with a try ... except ... block.
You have only handled the case for user_choice == '1'. If you enter anything other than 1, the program will return control to the beginning of the while loop.
I'll suggest you use a debugger to see what user_choice is before the if condition. If not, just use prints.
print("user_choice: {}, type: {}".format(user_choice, type(user_choice))

making tic tac toe, code is complete without error messages but wont run?

This is my first project, I used a lot of resources from others with the same project and this is what I have come up with. I am using Jupyter notebook. I am not getting any more error messages in my code, but for some reason I can't get it to run? Also, any advice or improvements in my code would also be appreciated.
I've tried to just call the tic_tac_toe() command but nothing comes up and I'm not sure why.
def tic_tac_toe():
brd = [None] + list(range(1,10))
end = False
winner = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9), (3,5,7))
from IPython.display import clear_output
def show_board():
print(brd[1]+'|'+brd[2]+'|'+brd[3])
print(brd[4]+'|'+brd[5]+'|'+brd[6])
print(brd[7]+'|'+brd[8]+'|'+brd[9])
print()
def player_input():
marker = ''
while marker != 'x' and marker != 'o':
marker = input('Do you want to be x or o?: ')
player1 = marker
if player1 == 'x':
player2 ='o'
else:
player2 = 'x'
player_markers = [player1,player2]
def choose_number():
while True:
try:
val = int(input())
if val in brd:
return val
else:
print('\n Please choose another number')
except ValueError:
print('\n Please choose another number')
def game_over():
for a, b, c in winner:
if brd[a] == brd[b] == brd[c]:
print("{0} wins!\n".format(board[a]))
print("Congrats\n")
return True
if 9 == sum((pos == 'x' or pos == 'o') for pos in board):
print("The game ends in a tie\n")
return True
for player in 'x' or 'o' * 9:
draw()
if is_game_over():
break
print("{0} pick your move".format(player))
brd[choose_number()] = player
print()
while True:
tac_tac_toe()
if input("Play again (y/n)\n") != "y":
break
I'm not sure why it is not running normally.
There's a couple things wrong with your code here. Your indentation for one. Also wondering why your functions are all in another function. You also create a bunch of functions but never call most of them. And have some functions that do not seem to exist. There are also a lot of logic errors here and there.
Try this instead:
# numpy is a package that has a lot of helpful functions and lets you manipulate
# numbers and arrays in many more useful ways than the standard Python list allows you to
import numpy as np
def show_board(brd):
print(brd[0]+'|'+brd[1]+'|'+brd[2])
print(brd[3]+'|'+brd[4]+'|'+brd[5])
print(brd[6]+'|'+brd[7]+'|'+brd[8])
print()
def player_input():
marker = ''
while marker != 'x' and marker != 'o':
marker = input('Do you want to be x or o?: ')
player1 = marker
if player1 == 'x':
player2 ='o'
else:
player2 = 'x'
player_markers = [player1,player2]
return player_markers
def choose_number(brd):
while True:
try:
val = int(input())
if brd[val-1] == "_":
return val
else:
print('\nNumber already taken. Please choose another number:')
except ValueError:
print('\nYou did not enter a number. Please enter a valid number:')
def is_game_over(winner, brd):
for a, b, c in winner:
if brd[a] != "_" and (brd[a] == brd[b] == brd[c]):
print("{} wins!\n".format(brd[a]))
print("Congrats\n")
return True
if 9 == sum((pos == 'x' or pos == 'o') for pos in brd):
print("The game ends in a tie\n")
return True
# I split this function in two because the "is_game_over" code was included here
# instead of being by itself.
def game_over(winner, brd, player_markers):
last = 0
# The first player is the one stored in "player_markers[0]"
player = player_markers[0]
# There are nine turns so that is what this is for. It has nothing to do with
# 'x' or 'o'. And one more turn is added for the "is_game_over" to work in
# case of a tie.
for i in range(10):
if is_game_over(winner, brd):
break
print()
print("{0} pick your move [1-9]:".format(player))
brd[choose_number(brd)-1] = player
show_board(brd)
# This is added to change from one player to another
# by checking who was the last one (look up ternary operators)
player = player_markers[1] if last==0 else player_markers[0]
last = 1 if last==0 else 0
def tic_tac_toe():
brd = ["_"] * 9
end = False
winner = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))
winner = np.array([list(elem) for elem in winner]) - 1
player_markers = player_input()
show_board(brd)
game_over(winner, brd, player_markers)
while True:
tic_tac_toe()
if input("Play again (y/n)\n") != "y":
break

How to pull a variable from one function to another

def letterChoice():
playerLetter = input('Please choose X or O.').upper()
if playerLetter in ['X','O']:
print('The game will now begin.')
while playerLetter not in ['X','O']:
playerLetter = input('Choose X or O.').upper()
if playerLetter == 'X':
computerLetter = 'O'
else:
computerLetter = 'X'
turnChooser()
def turnChooser():
choice = input("Would you like to go first, second or decide by coin toss?(enter 1, 2 or c) ")
while choice not in ["1","2","c"]:
choice = input("Please enter 1, 2 or c. ")
if choice == 1:
print("G")
cur_turn = letterChoice.playerLetter()
elif choice == 2:
print("H")
else:
print("P")
moveTaker()
I can't figure out how I'm supposed to inherit playerLetter into turnChooser(), I've tried putting playerLetter into the brackets of each function but they don't pass and create an argument error and the print("G") and so on are simply there to see if the code works but whenever I enter 1 or 2 "P" is outputted.
You need to define function Attributes for playerLatter
For EX:
def foo():
foo.playerletter=input('Please choose X or O.').upper()
>>> foo()
Please choose X or O.x
>>> foo.playerLetter
'X'
Accessing from another function
def bar():
variable=foo.playerLetter
print(variable)
>>> bar()
X
>>>
You can always check what Attributes are available for a given function
>>> [i for i in dir(foo) if not i.startswith('_')]
['playerLetter']
>>>
Edit turnchooser() to turnchooser(var), then when calling the function pass the letter to the function like this:
def LetterChoice():
Code...
turnchooser(playerletter)
And,
def turnchooser(var):
Code...
The letter will be placed in a variable called var, which means your code will use the letter as var not playerletter.
Of Course you can change the names to whatever you like.
You could add as many variables to the function however they all should have something assigned to them, aka you can't call the previous function like so:
turnchooser()
Unless you assign it a default value:
def turnchooser(var = 'x')
This way whenever the function is called the value of "var" is x unless stated otherwise.
Note that if you want to pass it from one function to another, u either have to assign the letter to a variable then call the function outside the "LetterChoice" or call it in the definition of "LetterChoice"
Within the function that has the variable in it type:
global variableName
Obviously change variableName to whatever the variable is actually called. Hope this helps!
Tommy
You should try using classes: Python documentation
This should be the code:
class Game:
def __init__(self):
self.cur_turn = ''
self.choise = ''
self.playerLetter = ''
self.computerLetter = ''
def letterChoice(self):
while True:
self.playerLetter = input('Please choose X or O.').upper()
if self.playerLetter in ['X','O']:
print('The game will now begin.')
if playerLetter == 'X':
self.computerLetter = 'O'
else:
self.computerLetter = 'X'
break
else:
print ('Please enter only X or O')
def turnChooser(self):
while True:
self.choice = input("Would you like to go first, second or decide by coin toss? (enter 1, 2 or c) ")
if self.choice in ["1","2","c"]:
if self.choice == 1:
print("G")
self.cur_turn = self.playerLetter()
elif self.choice == 2:
print("H")
else:
print("P")
break
else:
print ('Please enter 1, 2 or c')
game = Game()
game.letterChoice()
game.turnChooser()
# If you want to read any of the variables in Game just write 'self.VARIABLE_NAME'

Problems transferring information from one part of a function to another

While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:

Categories