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()
Related
I have to create this program for a class. I have been reading in various posts that lists in Python are already global and can be used in def statements.
Here are some of the resources I found that said this:
How to define a global list in python and append local list to it
How to declare python global list
Python global lists
None of these solutions have helped me and I am currently trying to figure this out. I might just have to rewrite it so that it doesn't use "options...". I also have a lot of "\n"s to make it look like it scrolls away from the old outputs because the teacher doesn't want to see them.
Here is the code I am having an issue with:
#!/usr/bin/python
import sys
def Switcher():
selec = 0
while (1):
print "\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "\n==== WELCOME TO SPACECODE'S BANK ===="
print "==== Select an Option: ====\n"
print " 0. Check Current Balance\n"
print " 1. Deposit Money\n"
print " 2. Withdraw Money\n"
print " 3. Transaction History\n"
print " 4. Exit\n"
options = {0: zero,
1: one,
2: two,
3: three,
4: four
}
selection = input("\n")
if (selection < 0) or (selection > 4):
print '\n'
else:
selec = selection
options[selec]()
def zero():
global current
print "\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "\n==== YOUR CURRENT BALANCE: ====\n"
print current
raw_input("\n Press enter to continue....")
Switcher()
def one():
print "\n\n\n\n\n\n\n\n\n\n\n\n\n"
global current, i
print "\n==== INPUT DEPOSIT AMOUNT: ====\n"
add = input()
current = add + current
i =+ 1
transact.append(i)
account.append(current)
raw_input("\n Press enter to continue....")
Switcher()
def two():
print "\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "\n==== INPUT AMOUNT TO WITHDRAWL: ====\n"
global current, i
temp = current
wdrw = raw_input()
if (temp == 0):
print "==== YOU DONT HAVE ANY MONEY TO WITHDRAWL ====\n"
Switcher()
elif ((temp - wdrw) < 0):
print "==== YOU CANT WITHDRAWL MORE THAN YOU HAVE IN BALANCE ====\n"
two()
elif ((temp - wdrw) >= 0):
i =+ 1
transact.append(i)
current = temp - wdrw
account.append(current)
print "\n==== TRANSACTION SUCCESSFUL ====\n"
raw_input("\n Press enter to continue....")
Switcher()
def three():
global i
print "\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "\n ==== TRANSACTION HISTORY (SAVES LAST 30) ====\n"
for w in range(len(trasac)):
print(transac[w]," : ",account[w])
print()
raw_input("\n Press enter to continue....")
Switcher(current)
def four():
sys.exit()
account = []
current = 0
transac = []
i = 0
Switcher()
Is it perhaps because you are declaring transac = [] instead of transact = [] at the bottom of your 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()
just wondering why the error says NameError name question1 is not defined
count = 0
import random
my_list = [question1, question2, question3, question4, question5, question6, question7, question8,question9, question10, question11, question12, question13, question14, question15, question16, question17, question18, question19, question20, question21, question22, question23, question24, question25, question26, question27, question28, question29, question30, question31, question32, question33, question34, question35, question36, question37, question38, question39, question40]
def intro(start):
if start == "YES" or start == "Y":
print("Lets begin.")
else:
print("Thanks for checking it out! Bye Bye!")
def question1():
global count
text_file = open("q1.txt")
print (text_file.read())
text_file.close
item = ""
ans1 = "B"
while item != "A" and item != "B" and item != "C" and item != "D":
item = input()
if item == (ans1):
print ("Correct")
count += 1
else:
print("Incorrect")
return count
def main():
print("Hello There! Welcome to an all new Trivial Pursuit!")
print("You have twenty multiple choice questions and twenty true and false.")
print ("Each question is one point. Your score will be presented at the end. ")
print("Would you like to begin? Press Y or YES. Please answer all questions in CAPS.")
start = input()
intro(start)
random.choice(my_list)()
question1()
question2()
question3()
question4()
question5()
question6()
question7()
question8()
question9()
question10()
question11()
question12()
question13()
question14()
question15()
question16()
question17()
question18()
question19()
question20()
question21()
question22()
question23()
question24()
question25()
question26()
question27()
question28()
question29()
question30()
question31()
question32()
question33()
question34()
question35()
question36()
question37()
question38()
question39()
question40()
print("You got", count, "right out of 40!")
main()
You can make count global:
count = 0
def intro(start):
if start == "yes" or start == "y":
print("Lets begin.")
else:
print("Thanks for checking it out! Bye Bye!")
def question1():
global count
count += 1
return count
def question2():
global count
count += 1
return count
def main():
print("Hello There! Welcome to an all new Trivial Pursuit!")
print("You have twenty multiple choice questions and twenty true and false.")
print ("Each question is one point. Your score will be presented at the end. ")
print("Would you like to begin? Press y or yes")
start = input()
intro(start)
question1()
question2()
print("You got", count, "right!")
main()
I edited your code to have the functions just add to count. I know globals aren't recommended, but this may work for you.
How do you minus one from an INT in a function?
This is what I'm trying:
try:
lives
except NameError:
lives = 6
else:
lives = lives-1
print("\nWrong!\nYou have " +str(lives)+ " lives remaining\n")
But it doesn't work.
The lives are always at 6 :(
Any ideas?
UPDATE:
def main():
used = []
print(blanks)
choice = input("\nEnter a letter:")
lives -= 1
print("\nWrong!\nYou have " +str(lives)+ " lives remaining\n")
used.append(choice)
main()
The real reason you are seeing 6 is because the NameError is thrown, and therefore your else clause is never actually executed
NameError: name 'lives' is not defined
If lives wasn't defined before, than try: lives will always get you to the except section.
if you define lives before this code (by assigning it something) or inside the try section, you'll get to see the -1 in action.
try:
lives = 1
except NameError:
lives = 6
else:
lives = lives-1
print lives
will output 0
as well as:
lives = 1
try:
lives
except NameError:
lives = 6
else:
lives = lives-1
print lives
EDIT:
For your comment, here is some sample code that does something like what you are probably trying to achieve, that is a game of guess the letter. Hopefully this will help you.
def main():
# The setup
right_answer = "a"
lives = 6
# The game
while lives > 0:
choice = raw_input("Enter a letter:")
if choice == right_answer:
print "yay, you win!"
break
else:
lives -= 1
print "nay, try again, you have", lives, "lives left"
else:
print "you lose"
# This will call our function and run the game
if __name__ == "__main__":
main()
** written fro python 2.7, for python 3 the prints will need parentheses.
All I needed to go was define the variable outside the function and then put:
global lives in the function.
Job done.
Ok so im working on a basic dice game, But when it gets to the while loop it doesnt print the message inside, The message is just a placeholder.
dicenumber = None
numberchoice = None
ready = None
test = "Lol"
class playerClass():
points = 0
class enemyClass():
point = 0
def rolldice():
dicenumber = dicenumber.randint(1,9)
def start():
print("Hello welcome to the dice game.")
print("The goal of the game is to guess what number the dice will land on.")
print("The option are 1 to 6 and the game is won by getting 3 points.")
print()
print("Are you ready to play?")
print("1 - Yes")
print("2 - No")
ready = int(input())
start()
while ready == 1:
print("hello")
Use global inside your start function. Also, as you were trying to put while ready==1, it will be in infinite loop!
dicenumber = None
numberchoice = None
ready = None
test = "Lol"
class playerClass():
points = 0
class enemyClass():
point = 0
def rolldice():
dicenumber = dicenumber.randint(1,9)
def start():
global ready
print("Hello welcome to the dice game.")
print("The goal of the game is to guess what number the dice will land on.")
print("The option are 1 to 6 and the game is won by getting 3 points.")
print()
print("Are you ready to play?")
print("1 - Yes")
print("2 - No")
ready = int(input())
start()
while ready == 1:
print("hello")
When you access ready inside the start() method, you are accessing it as a local variable. Python assumes that all variables you use are local, not global. Put global ready in the start() method before you set the ready variable. This will tell python to access ready as a global variable.
There is a scoping issue. ready variable defined in a global scope is not updated inside the start() function.
Simple demo of what is happening:
>>> ready = None
>>> def start():
... ready = 1
...
>>> start()
>>> print ready
None
Better return ready variable from the start():
def start():
print("Hello welcome to the dice game.")
print("The goal of the game is to guess what number the dice will land on.")
print("The option are 1 to 6 and the game is won by getting 3 points.")
print()
print("Are you ready to play?")
print("1 - Yes")
print("2 - No")
return int(input())
ready = start()
You can also make it global as #S.M. Al Mamun suggested, but i would not recommend it. Global variables are needed for sharing data, state between functions. In this case there is no need for it - your start() function defines a value for the ready variable. It is a single one place where ready is defined - no need to make it global. start() is an entry point and it would be a good idea to return a "state" (ready variable) from it.
See also:
Short Description of the Scoping Rules?
ready is defined in the global scope, but you are setting it in the local scope of the start function. Also, your rolldice function returns a number from 1 to 9 instead of 1 to 6.
from random import randint
class Player:
def __init__(self, name):
self.name = name
self.points = 0
self.won = False
def add_point(self):
self.points += 1
self.won = True
print('''
Hello welcome to the dice game.
The goal of the game is to guess what number the dice will land on.
The options are 1 to 6 and the game is won by getting 3 points.
Are you ready to play?
0 - No
1 - Yes'''
ready = int(input())
if ready:
players = []
number_of_players = int(input('How many players? '))
for i in range(number_of_players):
name = input('What is the name of player {}?'.format(i+1))
players.append(Player(name))
winners = []
while ready:
random_number = randint(1, 6)
for player in players:
guess = int(input('What is your guess, {}?'.format(player.name)))
if guess == random_number:
player.add_point()
if player.won:
winners.append(player.name)
if winners:
print('Winners: {}'.format(', '.join(winners)))
break
You are accessing a variable(ready) which was defined originally as a global variable, then you are accessing it in your start function without mentioning in your code('start' function) that is a global variable and finally in your while loop you are again trying to access a variable which you assume it has a value assigned to it.
The other thing is you while loop. when you set ready==1, you need to some where break from your loop if you don't want it to be infinite loop.