How to change the value of a variable - python

I'm having a bit of trouble with changing a variable value (canteen) to make it so that it runs from 3 to 0. I'm not sure why the value of canteen does not go to less than 2 every time I hit the "1" key. How do I make it so that the value of canteen becomes zero when the player hits the "1" key 3 times?
# Global Variables
km_travelled = 0
thirst = 0
camel_tiredness = 0
natives_travelled = -20 # Player always starts 20 km away from player once player reaches checkpoint
def introduction():
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert")
print("The natives want their camel back and are chasing you down! Survive ")
print("your desert trek and out run the natives \n \n")
def choices():
print("1. Drink from your canteen.")
print("2. Ahead at moderate speed.")
print("3. Ahead at full speed.")
print("4. Stop for the night.")
print("5. Status check.")
print("9. Quit \n")
def questions(answer):
canteen = 3
if "9" in answer:
print("GAME EXIT.")
done = True
elif "1" in answer:
print("You drank from the canteen")
canteen = canteen - 1
print(canteen)
def main():
# Global variables
done = False
# Go through once
introduction()
while not done:
choices()
answer = input("What is your choice? ")
questions(answer)
if __name__ == '__main__':
main()

The canteen variable is locally scoped, to the questions function. And each time you run that function, it is reinitialised to the value 3. Since the if statement is only executed once inside the function, it will never go lower than 2.
One simple way to solve this - even though it's not good practice - is to have canteen as a global variable. Put canteen = 3 outside any function, alongside the rest of your globa variables. Remove that statement from the questions function, and replace it with global canteen so that Python knows you are referring to the global variable when you alter it within the function.
Note that you will have a similar problem with the done variable, and can consider making this global too.
And finally, as I hinted at, global variables are bad to have in any program that isn't extremely simple - because they can be affected by everything in the program, and therefore make it very hard to figure out what is going on. There are a number of alternative ways to approach constructing complex programs which avoid global variables, which I would encourage you to look at. Using classes (which hold state internally, rather than globally) is one such way which is well-supported in Python.

Since while statement evaluates to true, the value 3 is assigned to the variable canteen after every choice. You can replace canteen = 3 with global canteen and assign the variable canteen outside it's function.
If you want to avoid using global, you can use a dictionary like this example:
def questions(answer, canteen):
if "9" in answer:
print("GAME EXIT.")
done = True
elif "1" in answer:
print("You drank from the canteen")
canteen['c'] = canteen['c'] - 1
print(canteen['c'])
def main():
# Global variables
done = False
canteen = {'c': 3}
# Go through once
introduction()
while not done:
choices()
answer = input("What is your choice? ")
questions(answer, canteen)

It is because you're defining canteen = 3 at the beginning of your questions() loop. You should define it once, with your global variables.
# Global Variables
km_travelled = 0
thirst = 0
camel_tiredness = 0
natives_travelled = -20 # Player always starts 20 km away from player once player reaches checkpoint
canteen = 3 # Define it here, as a global variable
### Truncated ###
def questions(answer):
# canteen = 3 # Don't define here
global canteen # but refer to the top one here
if "9" in answer:
print("GAME EXIT.")
done = True
elif "1" in answer:
print("You drank from the canteen")
canteen = canteen - 1
print(canteen)
def main():
# Global variables
done = False
# Go through once
introduction()
while not done:
choices()
answer = input("What is your choice? ")
questions(answer)
if __name__ == '__main__':
main()

Related

Variable declared but error of not defined shows up in python

In a nutshell:
At the end of my program, there is a need to compare two integers whose results are inside the function itself. When I execute, I get undefined variable error.
Actually:
I am creating a hand cricket python script which we usually play as a duo. At last both the scores of the opponents are compared and the greatest wins.
The operation with the variables are inside of a function, but when called outside the function, undefined variable error shows up. Help please?
import random
while True:
pc_b_or_b = 0 #PC probability
#User Bowling module
def Bowl():
bat_PC = 0
User_bowl = 0
scoreofpc = 0
ScorePC = 0
while True:
bat_PC = random.randrange(1,11) #Random int gen
User_bowl = int(input("Your turn to bowl: ")) #int from user
if User_bowl<1 or User_bowl>10: #Fool proofing user must not keep less than 1 or gr8 than 10
print("Wrong number")
continue
if User_bowl == bat_PC: # Check if user == pc and out
print()
print("PC Out!")
print("PC Score:",scoreofpc)
break
else: #Continuation
print("Escape for PC. PC kept",bat_PC)
scoreofpc += bat_PC
print("Score:",scoreofpc)
ScorePC = scoreofpc
#User batting module
def User_Batting():
a = 0
score = 0
ManScore = 0
while True:
b = random.randrange(1,11) #Same as above but User is batting and pc randome int gen
a = int(input("Your turn to bat: ")) #But here if user int == pc then out for user
if a<1 or a>10:
print("Wrong number")
continue
if a==b:
print()
print("Out")
print("Score:",score)
break
else:
print("Escape! PC =",b)
score +=a
print("Score:",score)
ManScore = score
Actually Some more code comes here I've reduced to just these as said by StackOverflow
Main problem here, variable not defined, all other modules working perfectly
ScorePC1 = ScorePC
ManScore2 = ManScore
if ScorePC1 > ManScore2:
print("PC won the match by scoring",Score_of_PC)
elif ScorePC1 < ManScore2:
print("You won the match by scoring",User_Score)
else:
print("Your Score and PC score matched!")
quitter = input("Do you wanna Quit? Y/N? ")
if quitter == "yes" or quitter == "y" or quitter == "Y":
print("Thank You for playing!")
print("Script created by ***Techno-Sachin***")
quit()
elif quitter == "n" or quitter == "no" or quitter == "N":
print("Playing again..")
continue
else:
print("It's a wrong input. Try again")
Expectaion:
At last it is expected to print the statements inside if ScorePC1 and ManScore2 comparisons.
Error:
The output is Big, but cut out to focus on the problem itself>
PC Out! PC Score: 38 Traceback (most recent call last): File
"C:\Users\E.sachin\Documents\HTML5\Python Scripts\Hand_cricket20.py",
line 164, in
ScorePC1 = ScorePC NameError: name 'ScorePC' is not defined
Try replacing this - ScorePC1 = ScorePC with global ScorePC1 then use it as normal by referencing it's name ScorePC anywhere.
using global keyword before a varible name makes the variables's scope global and therefore enables the access to it from outside or inside a function.
also put the same inside the function definition like
def Bowl():
global ScorePC1
use it for both of your variables ScorePC1 and ManScore
You should always return values from your function. In this case you could return scoreofpc and score from the two functions. Your code would look like this:
def bowl():
#your code
return scoreofpc
def user_batting():
#your code
return score
Score1 = bowl()
Manscore = user_batting()
Alternatively, you could use Global Variables. But they are not advisable, infact, they're evil.
The variable ScorePC is declared inside the function Bowl() , by doing so the scope of the variable is within the Bowl() meaning it cannot be accessed from outside of the function. If you want to access it outside of the function declare it outside, which is not a good design. The better design is to return the value from the function like #irfanuddin answer.
I did some modifications also.
import random
def Bowl():
global ScorePC
bat_PC = 0
User_bowl = 0
scoreofpc = 0
ScorePC = 0
while True:
bat_PC = random.randrange(1,11) #Random int gen
User_bowl = int(input("Your turn to bowl: ")) #int from user
if User_bowl<1 or User_bowl>10: #Fool proofing user must not keep
less than 1 or gr8 than 10
print("Wrong number")
continue
if User_bowl == bat_PC: # Check if user == pc and out
print()
print("PC Out!")
print("PC Score:",scoreofpc)
break
else: #Continuation
print("Escape for PC. PC kept",bat_PC)
scoreofpc += bat_PC
print("Score:",scoreofpc)
ScorePC = scoreofpc
#User batting module
def User_Batting():
a = 0
score = 0
ManScore = 0
while True:
b = random.randrange(1,11) #Same as above but User is batting
and pc randome int gen
a = int(input("Your turn to bat: ")) #But here if user int == pc then out
for user
if a<1 or a>10:
print("Wrong number")
continue
if a==b:
print()
print("Out")
print("Score:",score)
break
else:
print("Escape! PC =",b)
score +=a
print("Score:",score)
ManScore = score
# Main probem here, variable not defined
# All other modules wotking perfectly
ScorePC1 = ScorePC
ManScore2 = ManScore
if ScorePC1 > ManScore2:
print("PC won the match by scoring",ScorePC1)
elif ScorePC1 < ManScore2:
print("You won the match by scoring", ManScore2)
else:
print("Your Score and PC score matched!")
quitter = input("Do you wanna Quit? Y/N? ")
if quitter == "yes" or quitter == "y" or quitter == "Y":
print("Thank You for playing!")
print("Script created by ***Techno-Sachin***")
exit()
elif quitter == "n" or quitter == "no" or quitter == "N":
print("Playing again..")
play()
else:
print("It's a wrong input. Try again")
def play():
Bowl()
User_Batting()
play()
If the reduced code is inside the main function,then the problem is that ScorePcvariable is not defined because it is a local variable inside the Bowl() function because you initialized it there.You cant access its name in the main() function.
To fix this you can either return it from Bowl() to the ScorePc or set it to be global as Himanshu said.
def Bowl():
#code..
return ScorePc
def main():
ScorePc=Bowl()#this will store the returned value to ScorePc
or
def Bowl():
global ScorePc
You should probably read more about this to understand better how it works.
Here are some links:
geeksforgeeks
python documentation
You have defined ScorePC and ManScore inside functions which turns out they are only usable inside that function unless you do one of the two things.
You can make the variable a function attribute.
Example:
def Bowl():
Bowl.ScorePC = 0
def User_Batting():
User_Batting.ManScore = 0
You can make the variable global.
Example:
def Bowl():
global ScorePC
ScorePC = 0
def User_Batting():
global ManScore
ManScore = 0
If you want to use them in other files. You have to import the file there where you want to use.
Here you will find some good examples:
Using global variables between files?
This can be done by using global keyword in the function. See below for your reference
def Bowl():
global ScorePc
....
def User_Batting():
global ManScore
....
But, I would suggest returning the value from the function. if your function is carrying multiple values, then do return as an array.

correct answer tracker in python

I have been trying to figure out how to add a score counter for the mini quiz that I made. I've tried different things and even tried to look up how to do it but I just cannot figure it out for what ever reason. Please help!
This is the code:
score = 0
def question1():
print("1. Who hit the walk-off home run to extend the A's AL-record win streak to 20 games in 2002?"
"A. Kevin Millar"
"B. Scott Hatteberg"
"C. Sammy Sosa"
"D. Josh Donaldson")
a = input("Please enter your answer in a lower case letter:")
if a == 'C':
print('You are smart!')
score += 1
else:
print('Better luck next time!')
return
def question2():
print("2. Who was the last Tigers pitcher to throw a no-hitter?")
b = input("What is your final answer:")
if b == 'Justin Verlander':
print('I am impressed whith how smart you are')
score += 1
else:
print("Are you even trying")
return
def Quiz():
question1()
question2()
You need to declare score as global inside your functions.
def question2():
# declare that you're using the global variable score
global score
print("2. Who was the last Tigers pitcher to throw a no-hitter?")
b = input("What is your final answer:")
if b == 'Justin Verlander':
print('I am impressed whith how smart you are')
score += 1
else:
print("Are you even trying")
return
If you don't tell the interpreter that you're using the global variable, it assumes that you're referring to a score variable that was declared in the scope of the function.
As Allie Filter wrote, declaring score as global is one possibility. You can also take OOP inspired approach and create a class Test with question as a method and score as a class variable.
class Test:
score = 0
def question1(self):
print("1. Who hit the walk-off home run to extend the A's AL-record win streak to 20 games in 2002?"
"A. Kevin Millar"
"B. Scott Hatteberg"
"C. Sammy Sosa"
"D. Josh Donaldson")
a = input("Please enter your answer in a lower case letter:")
if a == 'C':
print('You are smart!')
self.score += 1
else:
print('Better luck next time!')
return True
def question2(self):
...
...
def take_quiz(self):
self.question1()
self.question2()
return self.score
You can run your test by creating an instance of Test and calling method take_quiz() on it.
Some basics of OOP can be found here and in documentation.

why does it say "level" is not defined

I am making trying to make a text base game and I want to make a level selection
print ("You and your crew are pinned in the remains of a church on the top floor, with two wounded. Being fired at by German machine guns, matters will soon only get worse as you see German reinforcements on their way. Find a way to escape with your 9 man crew with minimal casualties.")
#Start up Menu
print ("Before you start the game ensure that you are playing in fullscreen to enhance your gaming experience")
print("")
print ("")
time.sleep(1)
print ("Menu")
print ('Instructions: In this game you will be given a series of paths. Using your best judgment you will choose the best path by using the "1" or "2" number keys, followed by pressing the "enter" button')
print ('If the wrong path is selected, there will be consequences of either death, or a lower final score.')
print ('Death will end the game, and you will be forced to start from the beginning of the level.')
time.sleep(1)
print ('If you will like to restart, press "r"')
print ('If you will like to quit, press "q"')
print ('If you want to play level 1, press "a"')
print ('If you want to play level 2, press "s"')
print ('you cannot restart or quit at this time')
print ('')
print ('')
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
over here, why does it say "level is not defined? and how can I fix it so the program works?
levelselection()
if level == "1":
print ("good job!")
First of all , level is a local variable to your function levelselection .
After that you are returning level variable but not saving it to some other variable.
Do like this -
levelselected = levelselection()
if levelselected == "1":
print ("good job!")
I would suggest you to read about python variables scope, this is a good source.
Explanation:
As level is initialized within the function levelselection you won't have access to the variable outside the function.
Solution:
1.You can fix this with defining level in a global scope.
2.Also, you can return level from the function as you did, but you will need to catch this return value, for example:
level = levelselection()
if level == "1":
print ("good job!")
you forgot to indent the return level. So in your current code, the return doesn't belong to the levelselection()function.
Try this:
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
level = levelselection()
if level == "1":
print("good job!")

Scoring in Python game does not work

I am new to Python, trying to pick up the language outside of my school courses. This Rock Paper Scissors game I am working on functions correctly, although the score output does not show anything. Here is the code...
#!/usr/bin/env python2
# Extra modules used
import random
import time
# Set each move to a specific number
# Once a selection is made by the player,
# it will be equated to that specific variable.
rock = 1
paper = 2
scissors = 3
# Text representation of each move
names = { rock: "Rock", paper: "Paper", scissors: "Scissors" }
# Game Rules
rules = { rock: scissors, paper: rock, scissors: paper }
# Declare variables to be used to track scoring
player_score = 0
computer_score = 0
# Function to print a greeting and start
# a loop to allow the player to continue
#playing as many times as they wish
def start():
print ("Let's play a game of Rock, Paper, Scissors.")
while game():
pass # Allows the loop to stop when player is done
scores() # Call function when done playing
def game():
# Call move function to determine player move
player = move()
# Get computer move as random int between 1 and 3
computer = random.randint(1, 3)
# Send the move through the result function
result(player, computer)
return play_again()
# Function to obtain a move from the player
def move():
while True:
print
player = input("Rock = 1\nPaper = 2\nScissors = 3\nMake a move: ")
# Try to set the player move, or catch the error
try:
# Cast the user input as an integer
player = int(player)
# If entry is valid, set the variable
if player in (1,2,3):
return player
except ValueError:
pass
print ("Oops! I didn't understand that. Please enter 1, 2, or 3.")
# Function to determine the result of the game
# player move and computer move are passed in
def result(player, computer):
# Countdown to result display
print ("1...")
time.sleep(1)
print ("2...")
time.sleep(1)
print("3!")
time.sleep(0.5)
# Display the computer's move
# string.format() gets the text version
# of the move and inserts it where "0"
print ("Computer threw {0}!".format(names[computer]))
#Call the scores set earlier
global player_score, computer_score
# Check the results of the game
if player == computer:
print ("Tie game.")
# Check if the losing move to the player's move
# is equal to the computer's move
elif rules[player] == computer:
print ("Your victory has been assured.")
player_score += 1
else:
print ("The computer laughs as you realize you have been defeated.")
computer_score += 1
# Ask to play again
def play_again():
answer = input("Would you like to play again? y/n: ")
if answer in ("y", "Y", "yes", "Yes", "Of course!"):
return answer
else:
print ("Thank you very much for playing. See you next time!")
def scores():
global player_score, computer_score
print ("HIGH SCORES")
print ("Player: "), player_score
print ("Computer: "), computer_score
# Used to execute in command line or import
# into another Python script. This will prevent
# the code from being executed when being imported.
if __name__ == '__main__':
start()
Your print statements are a little off.
You should be including the arguments inside the print statement
print("Player: ", player_score)
Edit:
To speak a little more to printing. You could also use
print("Player: {}".format(player_score))
You need the variables inside the brackets so:
print ("Player: "), player_score
print ("Computer: "), computer_score
becomes
print ("Player: ", player_score)
print ("Computer: ", computer_score)
Alternatively,
print ("Player: {}".format(player_score))
print ("Computer: {}".format(computer_score))
Format is better to use as there is a whole lot more you can do with it (I'll let you find that out for yourself)!

Can't use functions in Python

I've been working on a project in python for a while now and I can't call the main function. I searched for a while but I can't get it to work. Right now the problem is that I can't call the main function. It used to be that once the program went through the main function once it wouldn't go back to the main function, but now it won't even go into the main function and I can't call it from the shell. Could someone help me? Here's my code.
#!/usr/bin/python
# I only have the above part in case the
# end user does not have python
# Wizard's Quest Copyright (c) 2016 by GrayHat4Life
# This software is open source and may be distributed freely
# Prepare the program
import sys, random
# Set up some variables & begin the story
global health
health = 10
global enemiesKilled
enemiesKilled = 0
print("You are a wizard travelling through the kingdom")
print("Your quest: to save the kingdom by placing the Gem of Karn in its rightful place, the Tower of Souls")
# Main gameplay loop
def main():
# Battle code
# Set up the battle variables
enemyList = ["Goblin", "Witch", "Dark Mage", "Dark Knight", "Theif", "Troll", "Orc"]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# Prepare the battles
print("As you are walking through the Forest of Doom, a " + random.choice(enemyList) + " appears on the path in front of you!")
# This part isn't very usefull, it's only to give the
# player the illusion of free will. It's actually a kind of gambling game :s
input("What spell do you use to attack it? ")
# The attack strengths
attack = random.choice(numbers)
enemyAttack = random.choice(numbers)
# Let the battle begin!
if attack > enemyAttack:
health = health - 1
print("Your attack failed and you've been hit! You narrowly escape the enemy and continue your quest")
main()
elif enemyAttack > attack:
enemiesKilled = enemiesKilled + 1
# This loop gives the user the ability to win. And lose. :D
while True:
if enemiesKilled == 10:
print("You've finally made it to the end of your quest!")
print("You place the Gem of Karn in the soul sphere and save the kingdom!")
sys.exit()
elif health == 0:
print("The damage was too much.")
print("You bleed out in the middle of the forest, alone and friendless.")
print("GAME OVER")
sys.exit()
Thanks!
Python does not have a main function. Define your functions first so the interpreter knows about them. It will then execute the first statement after the last 'return' and following statements after that.
Correct syntax for python:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
I don't see where you call the main() method initially.
Currently, you are entering a while True: and neither condition enemiesKilled == 10: or health == 0: are true
Your code should follow this structure if you are expecting to execute it
import somestuff
def main():
# do something here
if __name__ == '__main__':
# call the main function
main()
And if you want the while True: piece, then I would recommend something like this instead to stop the infinite loop
if __name__ == '__main__':
# call the main function
while enemiesKilled != 10 or health != 0:
main()
if enemiesKilled == 10:
print("You've finally made it to the end of your quest!")
print("You place the Gem of Karn in the soul sphere and save the kingdom!")
elif health == 0:
print("The damage was too much.")
print("You bleed out in the middle of the forest, alone and friendless.")
print("GAME OVER")

Categories