So I'm programming a text-based video game for a lark and one of the situations is if enemy health is less than 1 than it does a whole bunch of things (Mostly modifying variables and printing lines) then it should call a function. Problem being it's not calling. The function is being read and checked against the defined function, but it's not executing. Any idea what I'm doing wrong?
if enemy_hull < 1:
print (enemy_name + " breaks up as explosions rack the hull! You've won!")
scrap = scrap + randint(27,67)
scrapStr = str(scrap)
missile_count = missile_count + randint(1,8)
missile_countStr = str(missile_count)
shields = 60
shieldsStr = str(shields)
print ()
print ()
print("Your ship has " + shieldsStr + " shields and " + hullStr + " Hull Strength. You have " + scrapStr + " scrap and " + missile_countStr + " missiles.")
time.sleep(3)
FTLJump()
That's the function in question at the end, FTLJump, and it's being read but not executed. https://repl.it/Blt4/98 is the full code if anyone wants to take a looksie. Thanks!
Your FTLJump function only declares global variables and exits: there is no code inside. There is an indentation issue in that function.
Related
So, im making a command terminal that sends emails, tells you the time, and even generates passwords. Anyway the point being, lots of code in one spot means at least one part is bound to fail, and that part on my code currently is the slots command. The slots command is a fake gambling game. The problem is when checking if someone actually won. When someone wins the slots game, it will print "you win!" and otherwise will tell you that you lose, but instead, it always says that the user lost. Heres the code that actually is needed (dont want to make you look through a blob of 345 lines of code)
import random
def slots_p5():
print(" " + slots_p2)
print("ยป " + slots_p3)
print(" " + slots_p4)
def find( slotOne, slotTwo, slotThree):
if slotOne == slotTwo == slotThree:
print ("\nYou win")
else:
print ("\nUnfortuneatly, you lose!")
slots = ["๐","๐ต","๐ฐ","7๏ธโฃ"]
slotOne = (random.choice(slots))
slotTwo = (random.choice(slots))
slotThree = (random.choice(slots))
slots_p2 = (random.choice(slots) + random.choice(slots) + random.choice(slots))
slots_p3 = slotOne + slotTwo + slotThree
slots_p4 = (random.choice(slots) + random.choice(slots) + random.choice(slots))
slots_p5()
find( slotOne, slotTwo, slotThree,)
slots_p2 = (random.choice(slots) + random.choice(slots) + random.choice(slots))
slots_p3 = slotOne + slotTwo + slotThree
slots_p4 = (random.choice(slots) + random.choice(slots) + random.choice(slots))
slotOne = (random.choice(slots))
slotTwo = (random.choice(slots))
slotThree = (random.choice(slots))
Your code runs fine for me, you have to run the code many times to get a case where there are three in a row, but it does happen if you run it about a 100 times. indeed the syntax
if slotOne == slotTwo == slotThree:
was a surprise to learn that it works but it does
It works just fine. Since it's generating slots randomly and all slots must be the same, you will definitely not get wins a lot. It's all about probability.
Can anyone tell me what's wrong with this code. I have to follow guidelines for this class so they want it so your weekly pay is calculated by a "calc_weekly_wages" function and then for a "main" function to call the other and print it in a sentence rather than just a number output. I get an error that my "finalPay" variable is not defined, can anyone help?
hoursWorked = requestInteger("Enter weekly hours worked")
hourlyWage = requestNumber("Enter your hourly wage")
def calc_weekly_wages():
if hoursWorked <= 40:
finalPay = hoursWorked * hourlyWage
return (finalPay)
elif hoursWorked > 40:
finalPay = 40 * hourlyWage + (hoursWorked - 40)*(hourlyWage * 1.5)
return finalPay
def main():
calc_weekly_wages()
print ("Wages for " + str(hoursWorked) + "at $" + str(hourlyWage) + "is " + str(finalPay))
main()
Yes, finalPay is indeed out of scope on the line that does the print. The local variables of a function are inaccessible outside of that function.
Fortunately, finalPay is returned by calc_weekly_wages(). So, you could capture the return value in a variable by the same name:
finalPay = calc_weekly_wages()
That would fix things. Or you could substitute the problematic reference to finalPay with the call to your function:
print ("Wages for " + str(hoursWorked) + "at $" + str(hourlyWage) + "is " + str(calc_weekly_wages()))
And that would work too.
I'm new to StackOverflow (1st time posting) and new to coding with python. Currently enrolled in a course through Udacity. I'm having a very hard time with a project we were given for this course and decided to come here to see if anyone could help.
The project is to create a quiz with 4 blanks that need to be answered correctly by the player. It's required to have the quiz print out with the correct answer, but I'm having a very hard time getting this to print out correctly.
My code is below. Would appreciate any help or advice I can get on this.
Thanks!
easy_quiz = "If you ever get stuck, check out the __1__ for common
problems students face when attempting this project. If you need
additional help, you can schedule a 1:1 appointment with one of our
__2__ to get you un-stuck. This project should be __3__. If at any time
it becomes not fun, take a step back, deep breath, and ask for __4__!.
\n\n"
easy_answers = ["forums", "mentors", "fun", "help"]
medium_quiz = "Game must have 3 or more levels and each level contains 4 or more __1__ to fill in. Immediately after running the program, user is prompted to select a difficulty level from easy / __2__ / hard. Once a level is selected, game displays a fill-in-the-blank and a prompt to fill in the first one. When player guesses __3__, new prompt shows with correct answer in the previous blank and a new prompt for the next blank. When player guesses __4__, they are prompted to try again. \n"
medium_answers = ["blanks", "medium", "correctly", "incorrectly"]
hard_quiz = "__1__ are used as __2__ to automate tasks which are likely to be repeated. Functions produce the appropriate output (typically with a __3__ statement) from the appropriate input (function parameters). Your code should take advantage of __4__ and variable names should reflect the values they store. \n"
hard_answers = ["Functions", "tools", "return", "variables"]
blanks = ["__1__", "__2__", "__3__", "__4__"]
difficulty = raw_input("\nChoose your difficuty level = easy, medium, or hard? ")
print ""
if difficulty == "easy":
quiz = easy_quiz
answers = easy_answers
print "You chose easy!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + easy_quiz
elif difficulty == "medium":
quiz = medium_quiz
answers = medium_answers
print "You chose medium!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + medium_quiz
elif difficulty == "hard":
quiz = hard_quiz
answers = hard_answers
print "You chose hard!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + hard_quiz
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return pos
return None
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement != None:
user_input = raw_input("Type an answer for: " + replacement + " " )
word = word.replace(replacement, user_input)
replaced.append(word)
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
print "Incorrect, try again \n" + " ".join(replaced)
user_input = raw_input("Type an answer for: " + replacement + " ")
if guesses == 4:
return "\nGame Over! Better luck next time. \n"
print "Correct \n" + " ".join(replaced)
i = i + 1
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
print play_game(quiz, blanks)
Here is a working version of your play_game() method:
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement is not None:
user_input = raw_input("Type an answer for: " + replacement + " " )
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
if guesses == 5:
return "\nGame Over! Better luck next time. \n"
print "Incorrect, try again \n" + " ".join(replaced) + " " + replacement
user_input = raw_input("Type an answer for: " + replacement + " ")
replaced.append(user_input)
print "Correct \n" + " ".join(replaced)
i = i + 1
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
The main change is to delay modifying the replaced list until the correct answer has been given. That simplifies a lot of the code, eliminating the need for the word variable.
Here is my code:
# This program makes the robot calculate the average amount of light in a simulated room
from myro import *
init("simulator")
from random import*
def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
entry = raw_input("Press c to continue. ")
print("Thank you. ")
print
def randomPosition():
""" This gets the robot to drive to a random position """
result = randint(1, 2)
if(result == 1):
forward(random(), random())
if(result == 2):
backward(random(), random())
def scan():
""" This allows the robot to rotate and print the numbers that each light sensors obtains """
leftLightSeries = [0,0,0,0,0,0]
centerLightSeries = [0,0,0,0,0,0]
rightLightSeries = [0,0,0,0,0,0]
for index in range(1,6):
leftLight = getLight("left")
leftLightSeries[index] = leftLightSeries[index] + leftLight
centerLight = getLight("center")
centerLightSeries[index] = centerLightSeries[index] + centerLight
rightLight = getLight("right")
rightLightSeries[index] = rightLightSeries[index] + rightLight
turnRight(.5,2.739)
return leftLightSeries
return centerLightSeries
return rightLightSeries
def printResults():
""" This function prints the results of the dice roll simulation."""
print " Average Light Levels "
print " L C R "
print "========================="
for index in range(1, 6):
print str(index) + " " + str(leftLightSeries[index]) + " " + str(centerLightSeries[index]) + " " + str(rightLightSeries[index])
def main():
senses()
pressC()
randomPosition()
scan()
printResults()
main()
So, I am getting this error when I run my program.
NameError: global name 'leftLightSeries' is not defined
I understand that I must be doing something wrong related to the return statement. I'm not sure if I can only return one variable at the end of a user-defined function. If that were to be true, then I should probably separate the scan(): function. Anyways, I would appreciate any help on how to fix this error. Also, this is the result that I am looking for when I successfully complete my program:
Click Here
I am looking to complete the average values like the picture shows, but I am not worried about them at this point, only the list of values from the light sensors. I do not need to reach those exact numbers, the numbers will vary in the simulator.
If you want to return multiple items from scan(), don't use three separate return statements. Instead, do this:
return leftLightSeries, centerLightSeries, rightLightSeries
Also, when you call the function, you have to assign variable(s) to the returned values; it won't automatically create new local variables with the same names. So in main, call scan() like this:
leftLightSeries, centerLightSeries, rightLightSeries = scan()
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 7 years ago.
I'm half way through a chance fighting program and I wanted to shorten my work by using functions. But I got the error,
UnboundLocalError: local variable 'Ehealth' referenced before assignment
This is my code so far...
import random
import sys
import time
print ("You encounter a wild boar.")
time.sleep(1)
Weapon = input("Do you use a 'Bow and Arrow' or a 'Sword'.")
Ehealth = (100)
health = (100)
Ealive = (1)
alive = (1)
def attack():
damage = (random.randrange(5,21))
time.sleep(3)
print ("You attack the Boar for " + str(damage) + " attack points.")
time.sleep(3)
Ehealth = (Ehealth - damage)
print ("The Boars health is at " + str(Ehealth) + ".")
time.sleep(3)
if Weapon == ("Bow and Arrow"):
Emiss = (20) #out of 40
miss = (15) #out of 40
Espeed = (random.randrange(1,11))
speed = (random.randrange(1,11))
if Espeed > (speed):
print ("The Boar is faster than you so he attacks first.")
time.sleep(3)
print ("Your health is at " + str(health) + " and the Boars health is at " + str(Ehealth) + ".")
time.sleep(3)
while (alive == 1): #1 = alive, 2 = dead
Emiss = (random.randrange(1,41))
if Emiss < (20):
print ("The Boar missed.")
attack()
if Ehealth > (0):
alive = (1)
continue
else:
alive = (2)
print ("You Won!")
sys.exit()
Edamage = (random.randrange(5,16))
print ("The Boar attacks you with " + str(Edamage) + " attack points.")
time.sleep(4)
health = (health - Edamage)
time.sleep(4)
print ("Your health is at " + str(health) + ".")
time.sleep(4)
if alive <= (0):
print ("You died...")
sys.exit()
attack()
if Ehealth > (0):
alive = (1)
else:
alive = (2)
print ("You Won!")
sys.exit()
I got the error at the line on
Ehealth = (Ehealth - damage)
Any help would be appreciated.
You are trying to use the variable that lies outside of the function. In any case I'd do this:
def attack():
global Ehealth
damage = (random.randrange(5,21))
time.sleep(3)
print ("You attack the Boar for " + str(damage) + " attack points.")
time.sleep(3)
Ehealth = (Ehealth - damage)
print ("The Boars health is at " + str(Ehealth) + ".")
time.sleep(3)
Do note the 'global' keyword is needed if you're changing the value of the variable.
You are assigning to that variable in the attack() function:
Ehealth = (Ehealth - damage)
Assignment in a function makes a name local; you appear to expect it to be a global instead. Because it is a local, and hasn't been assigned to in the function before that line, you get your error.
Tell Python to treat it as a global instead. Add this line to your function (as the first line is probably a good idea):
global Ehealth
This tells the Python compiler to treat Ehealth as a global within your function, even though you assign to it.
Ehealth is global variable, If you just print it then there wont be any error But when you try to modify it, function consider it as local variable.
Solution :-
def attack(Ehealth=Ehealth):