dont know how to update score in python - python

So I'm in an intro to programming class and I need help updating the score in my "text based adventure game". What happens is you press enter, then a text appears (ex, you walk to the plane to find a monkey), then it says "Your score is 5". I want it so every time I press enter, the text appears and then my score goes up by 5. I spent a couple hours reading through my textbook and I don't know what to do. Everything is fine except the showScore function since it keeps printing my score as 5 after every step.
This is an example of the code:
def promptUser():
input("\n<Press Enter to continue...>\n")
def base():
print("You approach the base with friends")
def showScore():
x = 0
score = x + 5
print("Your score is now" ,score,)

I'm not a python programmer but I came across you post while doing some peer review for first timers questions and I thought I could help. Global Variables is what will solve your issue and based on this Python Global Variabl explaination the following should work for you.
score = 0
def promptUser():
input("\n<Press Enter to continue...>\n")
def shelter():
print("You approach the base with friends")
def showScore():
score = score + 5
print("Your score is now" ,score)
Currently you are defining your the variable 'x' within the showScore() function which means each time you call that function you are resetting x to zero before you add 5. In my solution, I define score as a Global variable so that each time you call the showScore() function it accepts simply adds 5 to score and then saves that in memory as the new score before displaying the score.
This may work for your current problem but in the real world it would be better to have a function that is dedicated to changing the score that is separate from the function that displays the score.
Hope this helps.

Try using:
def showScore():
score = 0
score = score + 5
print('Your score is now',score)

did you try putting score = 0 before the function then putting global score before score = score +5?

Related

Using returned outputs from one function in another in Python

new to Python - struggling with functions. - Image of code attached.
It inputs the name & scores just fine with the validation checks.
I need to use the scores input by the user and total them.
However, when I've tried to sum(score) it doesn't like it.
I can't work out how to sum the 4 total scores.
Please help :) Also would love any feedback on the style of coding etc.
Thanks in advance x
Image: Code in Python
I would rewrite the main function to be something like:
def GetStudentInput():
score = 0
for i in range (4):
print("Mrs Pearson's Class Test Score Data")
name = CheckStringInput("What's Your Name: ")
score += CheckNumericInput("What's Your Score: ")
print(score)
This eliminates the need for an extra function and avoids using a list since you don't appear to need the individual values elsewhere -- only the sum total.
In the absense of code for people to see, we have something like
def get_stuff():
for i in rnage(4):
name = input("Name?")
score = int(input("Score?"))
and another function
def TotalScore():
pass
How do we call total score?
Answer: Make sure we don't forget the user inputs and return them:
def get_stuff():
names = []
scores = []
for i in range(4):
names.append(input("Name?"))
scores.append(int(input("Score?")))
return names, scores
and take the scores in the summing function:
def TotalScore(scores):
return sum(scores)
This, of course, changes the calling code.
For example, you need to capture the returns when you call get_stuff:
names, scores = get_stuff()
total = TotalScores(scores)

Creating Decision Tree for Simple Game

I am currently a new student learning python. This is my first real experience doing much computer coding. For my project I must create a fill in the blank quiz with three different levels of difficulty. Once the user chooses a difficulty the game should print a different paragraph based on the difficulty. Each section of the game works fine but I am having trouble creating the "difficulty chooser." No matter the difficulty I choose, the game rolls through the easy, medium, and the hard level in order and then crashes.
Below I have included the introductory text and the difficulty chooser. I would love some help. I am sure there are really obvious things I don't see. Thank you!
def introduction():
print '''Welcome to Kevin's European Geography Quizzes.
Test your knowledge of European geography. \n'''
difficulty = raw_input('''Do you want to play an easy, medium, or hard game?
Please type the number 1 for easy, 2 for medium, or 3 for hard.\n''' )
game_chooser(difficulty)
def game_chooser(difficulty):
cursor = 0
difficulty_choice = [easy_game(), medium_game(), hard_game()]
#each element of the above list links to a procedure and starts one of the
#mini-games.
while cursor < len(difficulty_choice):
if difficulty != cursor:
cursor += 1
else:
difficulty_choice[cursor]
break
You can do with if else if you only want to print something but if you have separate code block for each level then define a function for each level and use this pattern :
You can define the function blocks and call them basis on user input something like:
# define the function blocks
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
# Now map the function to user input
difficulty_choice = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,
}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
difficulty_choice[user_input]()
Then invocation of function block will be:
difficulty_choice[num]()
Add a conditional for the input.
if difficulty == 'easy':
print("here is an easy game")
elif difficulty == 'medium':
print('here is a medium game')
elif difficulty == 'hard':
print('here is hard')
else:
print('Please enter valid input (easy, medium, hard)')
Under each if statement put your game code.
The reason your code goes through all the difficulties is because of this line:
difficulty_choice = [easy_game(), medium_game(), hard_game()]
When Python sees something like easy_game(), it calls the easy_game function and replaces it with the result. You don't want to call the function yet though, so you can take off the parenthesis to store just the function instead:
difficulty_choice = [easy_game, medium_game, hard_game]
This will mean you have to call the function after you take it out of the array.
As for the crash, when you use raw_input() you get a string back. That means when you type in the 1 to decide for an easy game, you get the character 1, which is represented by the number 49. That's why your code goes through everything and crashes: Your 1 is really a 49. In fact, if you type 1 < '1' into the interpreter, you'll get True back.
To fix that, you can pass the result of raw_input() to the int() function, which will parse it and give you the proper integer (or throw an exception if it can't be parsed). The last line of introduction would then look like game_chooser(int(difficulty)).
You could also skip most of the code of game_chooser by just indexing into the array (that's what they're for, after all):
def game_chooser(difficulty):
# the lack of parens here means you get the function itself, not what it returns
difficulty_choice = [easy_game, medium_game, hard_game]
#each element of the above list links to a procedure and starts one of the
#mini-games.
# note the parens to actually call the retrieved function now
difficulty_choice[difficulty]()

local variable 'output_file' referenced before, this code worked a few weeks ago, now it doesnt work how is that possible?

This thing is hard to post code and context inside of.
#This is a menu driven multiplication game. i am attemtping to save the high
#score in a file named multiplication_game.txt...
def single_player():
in_file = open('multiplication_game.txt', 'r')
highest_times_selection = int(in_file.readline())
print('\n____now lets see how u do on the times tables____')
correct = 0
missed = 0
times_selection = int(input(
'\nPlease enter a times time table integer to practice: '))
#This simple generates the multiplation questions and checks for right or
#wrong.
for number in range(0,11):
print(times_selection, 'x' , number, '=')
user_answer=int(input('answer: '))
correct_answer = times_selection * number
if user_answer == correct_answer:
correct+=1
else:
missed+=1
#This is where if its a perfect score and a high times table than the
#previous saved score it should be opened and the new score saved in the
#text document.
if missed == 0 and times_selection > highest_times_selection :
output_file = open('multiplication_game.txt', 'w')
name = input('You have the highest Score!!\n enter your name: ')
output_file.write(str(times_selection)+ '\n')
output_file.write(name + '\n')
else:
print('you missed ', missed, 'and got', correct,'correct\n')
output_file.close()
Try to define output_file = None before any assignment of it.
Tip: before your last if-else condition.
This looks like homework, so I don't want to give you the answer but rather lead you to it.
Take a look at your if/else for your high score table, and walk through your code twice, taking a different branch (different part of the if/else) each time you reach this spot. Write down the variable names on paper as you define them, starting over with a new sheet of paper each time you walk through. If you access a variable, check it off on your list. If you try to access a variable that's not on your list, it's the same as python saying local variable referenced before assignment -- you're trying to access it before you've defined it.
Hope this helps, both in figuring out your problem and learning how to debug in the future.

GPA Calculator for python and adding to a variable in a loop?

I have to make a GPA Calculator for my class. It has to take number grades and convert them to our school's scale. It also has to determine if the class is AP or Honors. AP adds +1 the weight and Honors add +.5 to the weight. Our scale is simple if the class is CP or Career which is just F=0 D=1 C=2 B=3 A=4. I know the final GPA isnt calculated right yet but I cant figure out how to add points the variable points when the grade is input. What am I doing wrong?
apClass= int(input('How many AP classes are you taking?'))
honClass= int(input('\nHow many Honors classes are you taking?'))
g1=int(input('\nWhat is your first grade?'))
g2=int(input('\nWhat is your second grade?'))
g3=int(input('\nWhat is your third grade?'))
g4=int(input('\nWhat is your fourth grade?'))
points=(apClass*1)+(honClass*.5)
def GetGrades (g1,g2,g3,g4):
if [g1,g2,g3,g4] < 90:
points += 4.0
elif [g1,g2,g3,g4] >90>80:
points += 3.0
elif [g1,g2,g3,g4] >70>80:
points += 2.0
elif [g1,g2,g3,g4] >60>70:
points += 1.0
elif [g1,g2,g3,g4] < 60:
points += 0.0
else:
return('invalid grade')
print (points)
Ok so this is my solution to the question:
class CalcGPA:
def __init__(self):
self.g1 = float(input("Please enter grade 1: "))
self.g2 = float(input("Please enter grade 2: "))
self.g3 = float(input("Please enter grade 3: "))
self.g4 = float(input("Please enter grade 4: "))
self.ap = float(input("Please enter total AP classes: "))
self.hn = float(input("Please enter total Honors classes: "))
self.weight = self.ap + (self.hn * 0.5)
self.grades_list = [self.g1, self.g2, self.g3, self.g4]
self.gpa_list = []
self.gpa = 0
def conv_grades(self):
for i in self.grades_list:
if i >= 90:
self.gpa_list.append(4)
elif 80 <= i <= 89:
self.gpa_list.append(3)
elif 70 <= i <= 79:
self.gpa_list.append(2)
elif 60 <= i <= 69:
self.gpa_list.append(1)
else:
self.gpa_list.append(0)
self.gpa = (sum(self.gpa_list) + self.weight) / len(self.gpa_list)
def show_gpa(self):
print("Your current GPA as calculated is: {}".format(self.gpa))
Lets break it down so you understand whats going on here and can gleam why you are having some issues. Firstly, we are doing this as Object Oriented Programming because I assume you will have multiple objects (I.E. students needing to calculate their grades). This allows you to encapsulate the data into a reusable structure. While I'm sure my version could be greatly improved, this is what I whipped up in 10 mins. So at first we define our class, and then define init. This initializes our beginning prompts and variables needed to run the program you are trying to create.
As you can see, I have 4 grades, ap classes and hn classes taken and stored as floats. Now this is where you weren't too clear on things. The weight that these classes add to the overall GPA is 1 for AP and 0.5 for Honors(hn). So if it is 1 point for AP I see no reason to multiply anything really as its already a whole number. With the 0.5 adding into the mix, we would multiply by 0.5 so we get half a point or each class that was honors. Add these two numbers together and you get your final weight that these classes will affect our gpa at the end.
I then stored the grades that were given to us in a simple list to be iterated through later. I initialized an empty list for our gpa values that we are going to calculate as well as setting our final gpa to 0 for now.
Next we define our first method as conv_grades(). As you can see, we use a simple for loop to iterate through our list at each item location in that list. Then we use If Elif statements to return the values we need to properly calculate our gpa values. This appends the values, each time the loop is run into the gpa_list we created under the initialization.
From here it is simple math to calculate a gpa. Now you werent too clear on this part either, but im assuming here that you will want to sum your gpa values up and divide them by the total number of classes/grades submitted. I.E. get the avg of your gpa scores to calculate a real gpa. To do this, we take the sum of the gpa_list and then add the weight to it. After that, we divide by the len() of the list so its scalable in the future if you want to have larger lists of grades (though of course you will need to change your code some to allow for more inputs from users than what is statically available now.) By doing this we return our gpa value.
At this point you could simply just print it out, but I decided for fun to just make another method to print out our gpa. This is the show_gpa() method at the bottom.
Now if you are unfamiliar with how to run code like this as it is not linear, you will need to import it into your python interpreter.
import "whatever you named this file(for demo im calling this gpa.py"
Now to create an instance(object) we call:
student_1 = gpa.CalcGPA() # Notice the gpa first, this denotes the filename we just imported
By doing this, it will start to ask you for all the variables we setup under the init() function. Enter those in.
Now at this point we have our object created, and our number plugged in. to calculate the gpa simply type:
student_1.conv_grades()
This will not output anything to your screen though, to show the gpa simply type out:
student_1.show_gpa()
That's it! Now hopefully this shows you how I at least would have gone about doing it, and hopefully you can see where you went wrong in your code outside of what others have already told you. Hope this helps you some.
P.S. With a program that accepts user input, you will want some kind of error handling and checking to make sure they are not trying input illegal characters. I think that is outside the scope of whats being asked of you, but I just wanted to point that out so I don't get flamed for it.

How do I keep track of score increments in Python?

I am writing a simple game program in Python where a user is prompted to select from "healthy" and "unhealthy" items in a grocery store. Each time the user selects a healthy item their "Health Score (initially 100) goes up. Each time they select from the unhealthy items their score goes down.
My code adds and subtracts from the initial Health Score of 100, but doesn't keep track of the most updated score after each selection. I want to give the user their new total after each transaction (new_hscore) and their grand total at the end (final_score), but I'm not sure how to do that.
Is it done with lists? Do I use .append? Any help would be greatly appreciated! Thanks in advance!
Here is my code: http://pastebin.com/TvyURsMb
You can see right away what I'm trying to do when you scroll down to the "def inner():" function.
EDIT: I got it working! Thank you all who contributed. I learned a lot. My final 'score-keeping' working code is here: http://pastebin.com/BVVJAnKa
You can do something simple like this:
hp_history = [10]
def initial_health():
return hp_history[0]
def cur_health():
return hp_history[-1]
def affect_health(delta):
hp_history.append(cur_health() + delta)
return cur_health()
Demonstration:
>>> cur_health()
10
>>> affect_health(20)
30
>>> affect_health(-5)
25
>>> affect_health(17)
42
>>> cur_health()
42
>>> print hp_history
[10, 30, 25, 42]
You can't store module level variables like that. Any attempt to write to that variable will create a local variable. Examine the behavior of this script:
s = 0
def f():
s = 10
print s
f()
print s
Output:
10
0
Instead you should be moving towards an object-oriented approach. Start placing your code in a class:
class HeathlyGame():
def __init__(self):
self.init_hscore = 100
self.final_score = 0
# Beginning. Proceed or quit game.
def start(self):
print "Your shopping habits will either help you live longer or they will help you die sooner. No kidding! Wanna find out which one of the two in your case?", yn
find_out = raw_input(select).upper()
...
game = HeathlyGame()
game.start()
This will allow you to create multiple versions of the game in memory at once, and each can store their own copy of the score.
For more on classes, try this link: http://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes
The problem seems to be you are always starting at init_hp, forgetting your cur_hp doing
init_hp = 10
while True:
food = choose_food()
if "cereal" in food:
cur_hp = init_hp - 5
# ..
But you need:
init_hp = 10
cur_hp = init_hp
while True:
food = choose_food()
if "cereal" in food:
cur_hp -= 5
# ..
You can use a generator!
A generator is basically a function that keeps track of the state of its objects even after you leave the function and call it again. Instead of using 'return' and the end, you use 'yield'. Try something like this:
def HealthScore(add):
score = 100
while 1:
score += add
yield score
if you call HealthScore(-5), it will return 95. If you then call HealthScore(5), it will return 100.

Categories