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()
Related
So let's say I have a function of
def question():
print("")
question_section = str("B" + str(quiz_nmbr + 1))
print("Question", str(quiz_nmbr) + ": " + str(sheet[question_section].value))
question_become = str(input("Type your question: "))
sheet[question_section].value = question_become
book.save('Quiz_Problems.xlsx')
Then let's say one time I wanted to call the question() function again.
However, I don't want print("Question", str(quiz_nmbr) + ": " + str(sheet[question_section].value)) to be printed.
Is there anyway to just remove that statement for certain condition? and by condition what I mean is let's say I wanted to call the function in if else statement (which condition matters to give different output)
Try this:
def question(prompt):
print("")
question_section = str("B" + str(quiz_nmbr + 1))
if prompt:
print("Question", str(quiz_nmbr) + ": " + str(sheet[question_section].value))
question_become = str(input("Type your question: "))
sheet[question_section].value = question_become
book.save('Quiz_Problems.xlsx')
Then, inside your if/else clause, you can call question(True) or question(False) as desired.
I have been trying to figure out how to pass data between functions, I'm new to coding. I have tried multiple way to do it, I am struggling to understand how data is passed my code is below. Help would be awesome.
x = []
y = []
z = []
def w(): #Welcome greeting the user and asking for their name
print("Welcome to the BMI Index Calculator.")
name = input("Enter employee's name or Exit to quit: ") # Allows the user to input there name as a variable
if str.isnumeric(name): # Test as a string
print("That is not a name.")
w()
if name == 'Exit': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
else:
name = x.append(name)
def h():
height = input("Enter employee's height in inches: ")
if height == '0': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
else:
height = y.append(height)
def wt():
weight = input("Enter employee's weight in lbs: ")
if weight == '0': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
else:
weight = z.append(weight)
def bmi(): #gives the data back to the user
print(str(x).replace('[', '').replace(']', '').replace("'", '') + "'s " + "BMI profile")
print("---------------------------")
print("Height: ", str(y).replace('[', '').replace(']', '').replace("'", ''), '"')
print("Weight: ", str(z).replace('[', '').replace(']', '').replace("'", ''), "lbs.")
def math_cal():
bmi_weight = int(z) * 703
bmi_height = int(y) ** 2
print("BMI: ", bmi_weight / bmi_height)
def run():
x = w()
y = h()
z = wt()
xy = bmi()
xz = math_cal()
__main__()
run()
__main__()
I have been successful in passing the data to other functions but the code fails to see the list as an int. Thus I have found my way here, trying to get ideas of how to rewrite this code in a more efficient manner. I am looking for a way to reference functions to pass data between functions, however I have not been find a clean way to execute that process.
There are to points where values are passed when using functions:
at the start of the function, with parameters
at the end of the function, as return value
let us first take a look at the return value:
For example in your h() function, you ask the user for the height. This value is stored in height
height = input("Enter employee's height in inches: ")
after checking for all the cases you want, you can return one value at the end of the function by using "return":
return height
the complete function becomes:
def h():
height = input("Enter employee's height in inches: ")
if height == '0': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
return height
This means if you call the function h() it will ask for the height and return the value which it obtained. This could be used by you program like this:
bmi_height = h()
or
bmi_height = h()*2
if you want to multiply the entered value with 2.
The second part, passing values to a function at the start of the function with parameters:
for example you want to use the height and weight when calculating the BMI, then the function becomes:
def bmi(height, weight)
print("BMI: ", bmi_weight / bmi_height)
this function has to be called like this:
bmi(170, 85)
when entering the values hard-coded or
height = 170
weight = 85
bmi(height, weight)
when you use variables.
outcomeG = "0"
outcomeB = "0"
def roll(outcomeG, outcomeB):
outcomeG = random.randint(1, 6)
outcomeB = random.randint(1, 5)
return outcomeG, outcomeB
def goodDiceRoll():
goodDiceOptions.destroy()
global goodDiceRoll
goodDiceRoll = tkinter.Tk()
goodDiceRoll.title("Green Dice roll")
lbloutcome = tkinter.Label(goodDiceRoll, text="Press roll")
btnRollG = tkinter.Button(goodDiceRoll, text="Roll", command=roll(outcomeG, outcomeB))
if outcomeG == "1":
lbloutcome.config(text="Green 1")
goodDiceRoll.update()
f = open("Logs.txt", "a")
ts = time.time()
sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
f.write(sttime + "Green 1")
f.close()
elif outcomeG == "2":
lbloutcome.config(text="Green 2")
goodDiceRoll.update()
f = open("Logs.txt", "a")
ts = time.time()
sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
f.write(sttime + "Green 2")
f.close()
#rest of code
This is some of my code that is suppose to let you roll a green dice or red dice and then put it in a file. However when I press the roll button that i made, it is suppose to randomize a number from 1 to 6 and display it but what really happens is absolutely nothing. How can i fix this? Any help will be much appreciated.
If you do roll(outcomeG, outcomeB) then don't expect those two global variables to change. They will remain 0. This is because the (parameter) variables within roll are local to that function. Any assignment made to those variables will not affect the variables that were passed to the function.
If you then call goodDiceRoll() the if blocks will not be entered since the values of those variables are still 0, and by consequence nothing gets written to the file.
You can solve this by doing:
outcomeG, outcomeB = roll()
... and remove the parameters from the roll definition.
But, as you don't call roll that way, but pass a reference to it via:
btnRollG = tkinter.Button(goodDiceRoll, text="Roll", command=roll)
... you are forced into using global variables. So modify roll like this:
def roll():
global outcomeG, outcomeB
outcomeG = random.randint(1, 6)
outcomeB = random.randint(1, 5)
Make sure to also define them as such in goodDiceRoll.
Secondly, it is a really bad idea to assign to goodDiceRoll, which really destroys the previous value it had, i.e. the function you are in. This will make the function unreachable after the first invocation. Use a different variable name.
If what you have posted is the entirety of your code, then it is unlikely that anything will be written, since you only include cases for the green dice rolling a "1" or a "2". Instead of using if statements to deal with different cases of rolls, you should instead do something like this:
f = open("Logs.txt", "a")
ts = time.time()
sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
f.write(sttime + "Green " + outcomeG + ",\n")
f.write(sttime + "Blue " + outcomeB + "\n")
f.close()
Also you need to make sure when you call the 'roll' function, you can access that data.
OK - I am trying to get a Python function to accept variables from two other functions. Is this possible ?
A sample of what I am trying to do it below (I have simmed down the original code - for input here). Hopefully you get theidea of what I am trying to do. In a nutshell, I have Rectangle () which calls Extras() and the I want the output from Rectangle and Extras to be sent to the Calculate_Deposit ().
Is this possible ?
def calculate_deposit(total_cost, extras):
deposit_percent = float(raw_input("Enter Deposit % (as a decimal) of Total Cost: "))
months_duration = float(raw_input("Enter the number of months client requires: "))
if deposit_percent >0:
IN HERE JUST SOME CALCULATIONS
else:
print "The total amount required is: ", total_cost
def rectangle(width, height, depth, thickness):
type = raw_input("Enter lowercase c for concrete: ")
if type == 'c':
output = IN HERE JUST COME CALCULATIONS
else:
return raw_input("Oops!, something went wrong")
print output + extras()
total_cost = calculate_deposit(output, extras)
def extras():
type = float(raw_input("Enter 1 for lights: "))
if type == 1:
light = 200
print "The cost of lights are: ", light
return light
else:
return raw_input("No extras entered")
In rectangle, you call extras(), then you send just the function extras to calculate_deposit(). You want to send the result of the extras() call, not a reference to the function itself. You can make a minor change and save that value, referring to it when you print and when you go into calculate_deposit.
Change this:
print output + extras()
total_cost = calculate_deposit(output, extras)
To this:
extra = extras()
print output + extra
total_cost = calculate_deposit(output, extra)
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.