Variable is not used - python

this would be my first question up here so don't be mad if i do something wrong. I got this homework of guessing the secret number and i had to implement Tkinter in it. The problem is that the counter isn't working since the variable counter is not used. I get it, but i tough i code it as it should be, and it looks like not. And for another question, bellow else statement i used IF again, is this OK or do you practice different code.
import Tkinter
import random
import tkMessageBox
secret_number = random.randint(1, 10)
window = Tkinter.Tk()
greeting = Tkinter.Label(window, text="Welcome to the game " + "guess the secret number".upper() + ". You have 5 tries.\n Select a number between 1 and 10:")
greeting.pack()
guess = Tkinter.Entry(window)
guess.pack()
def check_guess():
counter = 0
if int(guess.get()) == secret_number:
counter = counter + 1 #here it states "variable not used"
result_text = "You guessed correctly! Secret number is %s! " % secret_number
elif int(guess.get()) > secret_number:
counter = counter + 1
result_text = "Wrong. Your number is to HIGH! This was your %s try." % counter
else:
counter = counter + 1
result_text = "Wrong. Your number is to LOW! This was your %s try." % counter
if counter == 5 and guess != secret_number:
print "Secret number was %s!" % secret_number
tkMessageBox.showinfo("Result", result_text)
submit = Tkinter.Button(window, text="Try your luck", command=check_guess) # check_guess, not check_guess()
submit.pack()
window.mainloop()

Everytime the function is called, counter will be set to 0, meaning it will never be equal to 5. A simple fix could be to use a global variable instead. Set counter = 0 outside the function instead, and remove that line from the function. Instead, write global counter at the first line in the function. Something like this:
counter = 0
def check_guess():
global counter
if int(guess.get()) == secret_number:
...

Related

The global isn't working and didn't recognizing variable "text"?

The global isn't working properly and it says that
it does not know what text is, even though it is declared global.
def nguess():
answer = random.randint ( 1, 50 )
def check():
global attempts
attempts = 10
global text
attempts -= 1
guess = int(e.get())
if answer == guess:
text.set("yay you gat it right")
btnc.pack_forget()
elif attempts == 0:
text.set("you are out of attempts")
btnc.pack_forget ()
elif guess > answer:
text.set("incorrect! you have "+ str(attempts) + "attempts remaining. Go higher")
elif guess < answer:
text.set("incorrect! you have "+ str(attempts) + "attempts remaining. Go lower")
return
nw = tk.Toplevel(app)
nw.title("guess the number")
nw.geometry("500x150")
lable = Label(nw, text="guess the number between 1 - 50")
lable.pack()
e = Entry(nw, width = 40, borderwidth = 10)
e.pack()
btnc = Button(nw,text = "Check", command = check)
btnc.pack()
btnq = Button ( nw, text="Quit", command=nw.destroy )
btnq.pack()
text = StringVar()
text.set("you have ten attempts remaining ")
guess_attempts = Label (nw,textvariable = text)
guess_attempts.pack()
Well, what's going on is you're trying to get a variable before initialize it i.e. in check function you're calling a global text variable so what it means is you're bringing whatever text variable stores in global namespace, but the problem is text variable isn't exist in global namespace yet because you've created after calling the check function. Below I show an example:
def test():
global variable
print(variable)
test()
variable = 'Hello'
This will raise an error because of what I just explained, so what you have to do is something like this(based on the example):
def test():
global variable
print(variable)
variable = 'Hello'
test()
In short, initialize the text variable before calling the check function which uses global text

Python loop just keep going

I'm making a dart score keeper but it just keeps going round and round. I just need some help as to why this is.
The code:
import time
import sys
from sys import argv
script, name1, name2 = argv
def dartscore():
print "Play from 501 or 301?"
threeorfive = int(raw_input())
if (threeorfive == 501):
def playerone():
startnum1 = threeorfive
while (startnum1 > 0):
print "Ready ", name1,"?"
print "Please enter your score."
minusnum1 = int(raw_input())
startnum1 = startnum1 - minusnum1
playertwo()
if (startnum1 == 0):
print "Well done! You win!"
elif (startnum1 < 0):
print "Sorry but you have entered a wrong score"
playertwo()
def playertwo():
startnum2 = threeorfive
print "Ready ", name2,"?"
print "Please enter your score."
minusnum2 = int(raw_input())
startnum2 = startnum2 - minusnum2
if (startnum2 == 0):
print "Well done! You win!"
print "Unlucky ", name1,". Well played though."
sys.exit()
if (startnum2 < 0):
print "Sorry but you have entered an incorrect score. Please try again"
startnum2 += minusnum2
playerone()
playerone()
dartscore()
Now the two functions playerone() and playertwo() are different because I was trying something with the playerone() function to see if that solved my problem.
Well you have a while(startnum1 > 0):. It seems like startnum1is always bigger then 0. The only way to exit your loop is player 2 has a startnum2 on 0.
Your problem is:
threeorfive = 501
Throughout the entire game, and you begin each of your functions with
startnum = threeorfive
Which means the game 'resets' after both player takes a turn.
A possible fix would be to add global variables:
cumulative1 = 0
cumulative2 = 0
then update cumulative in each iteration:
cumulative1 += minusnum1
cumulative2 += minusnum2
and change your while loop to:
while(threeorfive - cumulative1 > 0)
while(threeorfive - cumulative2 > 0)

How do you change a variable in a function to then be used in the main code?

I am quite new to Python and I am having some trouble figuring out the following:
import random
import sys
print("Welcome to this Maths quiz.")
playerName = str(input("Please enter your name: "))
playerAge = int(input("Please enter your age: "))
if playerAge < 11:
print("This quiz is not for your age.")
sys.exit(0)
else :
print("Great! Let's begin.\n")
quizQuestions = ["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"]
quizAnswers = ["99", "79", "88", "12.5", "0"]
quizSync = list(zip(quizQuestions, quizAnswers))
random.shuffle(quizSync)
quizQuestions, quizAnswers = zip( * quizSync)
questionNumber = 1
quizScore = 0
def displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore):
print("Question " + str(questionNumber) + ": " + quizQuestions[questionNumber - 1] + "\n")
questionAnswer = str(input())
if questionAnswer == quizAnswers[questionNumber - 1]:
print("\nCorrect!\n")
quizScore += 1
else :
print("\nIncorrect! The answer is: " + quizAnswers[questionNumber - 1] + "\n")
while questionNumber < 6:
displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore)
questionNumber += 1
print("You have a total score of: "+str(quizScore))
I would like the variable "quizScore" in the function "displayQuestion" to increase by one if the player gets a question right. However, after the quiz is finished, the print function at the end always prints the score is 0 even if the player gets questions right.
You have to declare it as a global variable inside the function so that it can modify the variable in the global scope
def displayQuestion(quizQuestions, quizAnswers, questionNumber):
global quizScore
...
quizScore += 1
That being said, you should generally avoid global variables if you can and try to redesign your program to either pass the variables along as arguments and return values, or use a class to encapsulate the data.
Although this won't be the shortest answer, which is to use another global variable. It instead will show you how to avoid using global variables (which are considered harmful) by using Object Oriented Programming (OOP). To accomplish this, most of the code in your question can be encapsulated into a single class named MathQuiz below.
Besides getting rid of almost all global variables, it also provides a usable template for you to create any number of independent math quizzes.
import random
import sys
class MathQuiz:
def __init__(self, questions, answers):
quizSync = list(zip(questions, answers))
random.shuffle(quizSync)
self.quizQuestions, self.quizAnswers = zip(*quizSync)
self.quizScore = 0
print("Welcome to this Maths quiz.")
self.playerName = str(input("Please enter your name: "))
self.playerAge = int(input("Please enter your age: "))
if self.playerAge > 10:
print("Great! Let's begin.\n")
else :
print("This quiz is not for your age.")
sys.exit(0)
def run(self):
for questionNumber in range(len(self.quizQuestions)):
self._displayQuestion(questionNumber)
print("You have a total score of: " + str(self.quizScore))
def _displayQuestion(self, questionNumber):
print("Question " + str(questionNumber) + ": "
+ self.quizQuestions[questionNumber-1]
+ "\n")
questionAnswer = str(input())
if questionAnswer == self.quizAnswers[questionNumber-1]:
print("\nCorrect!\n")
self.quizScore += 1
else :
print("\nIncorrect! The answer is: "
+ self.quizAnswers[questionNumber-1]
+ "\n")
quiz = MathQuiz(["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"],
["99", "79", "88", "12.5", "0"])
quiz.run()

I don't understand why my function doesn't happen

I am trying to write a typing challenge game where the player has to type a word as fast as possible within the time limit. At the end of the game() function it is supposed to execute the round1() function when the timer gets to 0. However, nothing happens and it just stays on the number 1. Any ideas what is causing this behavior?
This is the code I am using:
import random
import time
global timer
timer = 20
global counting
counting = 10
global rounds
rounds = 0
def menu():
print ("Main Menu\nType in 'start' to begin the typing challenge")
start = input()
if start == "start":
game()
else:
menu()
def game():
global counting
choices = ["snazzy", "pizzas", "sizzle", "jackal"]
global word
word = (random.choice(choices))
print ("The word you must type is", word)
print ("You will be timed on how long it takes you to type the word.")
print ("Each round you will have a slightly smaller amount of time to type the word")
time.sleep(10)
print ("Starting in...")
for count in range(10):
print (counting)
time.sleep(1)
counting -=1
round1()
def round1():
useless = 100
global rounds
global word
global timer
while useless > 1:
for count in range(20):
time.sleep(1)
timer -=1
print ("Type", word)
attempt = input()
if attempt == word and timer > 0:
rounds = rounds+1
round2()
else:
lose()
You are getting into the function round1, but once you are there, you are caught in an infinite loop because the variable useless will never change.
Even if you take out the while loop, you will never be able to win because you do not take input in until after the timer has already run out.
Try this code from round 1 on:
def round1():
import sys, select
global rounds
global word
global timer
print ("Type", word)
input, out, error = select.select( [sys.stdin], [], [], timer)
if (input):
attempt = sys.stdin.readline().strip()
if attempt == word:
rounds = rounds+1
round2()
else:
lose()
else:
lose()
if __name__ == '__main__':
menu()
Note that, as-is, it will fail with a NameError since you don't have a round2() function defined. A better solution would be to generalize your function, with something like round_x(number, word, time_to_answer); That way you can reuse the same code and don't have to import globals.
I was playing a bit with your game you're doing too many overhead and mistakes
there so I just changed it's structure to simplify:
import random
import time
current_milli_time = lambda:int(time.time() * 1000)
timer = 20 #suppose user has 20 secs to enter a word
counting = 10
requested_word = ""
choices = ["snazzy", "pizzas", "sizzle", "jackal"]
rounds = 0
def menu():
print ("Main Menu\nType in 'start' to begin the typing challenge")
game() if input().lower() == "start" else menu()
#There is no need to split game and round but I didn't want to mess with
#your program structure too much
def game():
global requested_word
try:
requested_word = (random.choice(choices))
choices.remove(requested_word)
except IndexError:
print "Game is finished"
return
print ("The word you must type is", requested_word)
print ("You will be timed on how long it takes you to type the word.")
print ("Each round you will have a slightly smaller amount of time to type the word")
print ("Starting typing in in...")
for count in range(10,-1,-1):
print (count)
time.sleep(1)
round()
def round():
global timer
start = current_milli_time()
word = input("Enter word -> ")
stop = current_milli_time()
time_delta = stop-start #this is in milliseconds
if time_delta< timer*1000 and word == requested_word :
timer = timer-5 #lower the time to enter a word
game()
else:
print("Game OVER")
menu()
When prompt 'Enter word ->' appears the user has all the time he wants to enter a word, but after it time_delta is calculated and if it passes your limit, it's game over for him.

Issues with global variables and their values

I'm having some issues with this code. There is a lot of other code to go with it but none that will interfere or have any affect on the issue I'm having. So basically, when I run the code and we get to the for loop at the bottom, it prints nothing because apparently the variable 'walls' = 0, even though I've already given it a valid input. If anyone could help it would be much appreciated.
global walls
global wallLengths
walls = 0
wall = 0
wallLengths = 0
def clientDetails():
#global walls
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Please enter you first address line here:")
addressLineOne = input(">>>")
print("Please enter your second address line here (OPTIONAL)")
addressLineTwo = input(">>>")
print("Thank you for your information")
print (userName)
print (addressLineOne + ", " + addressLineTwo + ", " + postCode)
print (" ")
def ValidationOne():
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
elif clientDetailsCorrect == "Yes" or clientDetailsCorrect == "yes":
roomDimensions()
else:
("Invalid response, please try again")
ValidationOne()
ValidationOne()
def roomDimensions():
global walls
print ("STEP 2 - ROOM DIMENSIONS")
def ValidationTwo():
global walls
print ("How many walls does your room have?")
walls = int(input(">>>"))
if walls > 10 or walls < 3:
print("Invalid, please enter a number between 3 and 10")
ValidationTwo()
elif walls == " " or walls == "":
print("Invalid")
ValidationTwo()
def ValidationThree():
global walls
print ("How tall is the room in meters?")
roomHeight = float(input(">>>"))
if roomHeight < 2.4 or roomHeight > 6:
print ("Invalid, please enter a value between 2.4 and 6")
ValidationThree()
def IndividualWalls():
global wallLengths
global walls
for i in range(1,walls):
print("Please enter the width of wall" , i)
wallLengths[i] = float(input(">>>"))
ValidationTwo()
ValidationThree()
IndividualWalls()
clientDetails()
there is no need to use 'global' keyword when declaring a global at the top of the script:
>>> walls = 0
>>> def increase_walls():
... global walls
... walls += 1
... print walls
...
>>> increase_walls()
1
I can't comment to your question because I don't have over 50 reputation so I will ask here
Can you tell me what the function roomDimensions does?
I tried to run it and you have some deep recursion problem (you can't call recursion function without any if - it will run forever) BUT the first thing that I notice is that you don’t initialize the walls variable so it will not be global variable it will be non-local variable. and you don't call any inner function ( ValidationTwo, ValidationThree,IndividualWalls)
so you main problems are: (handle them in this order)
walls initialize
you didn't call any inner function
deep recursion
here is my example for the use of the three of above:
global_var = 12
def outer():
global global_var
print("*"*10)
print('hello im outer function')
print("*"*10)
def inner1():
global global_var
print('hello im inner1 function')
if global_var < 10:
return 'end for inner1'
print ('global_var is: ' + str(global_var))
global_var -= 1
return inner1()
def inner2():
global global_var
print('hello im inner2 function')
if global_var >= 10:
return 'end for inner1'
print ('global_var is: ' + str(global_var))
global_var += 1
return inner2()
if global_var >= 10:
return inner1()
else:
return inner2()
if __name__ == '__main__':
print outer()

Categories

Resources