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.
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.
We're creating a small text-based bank application using python2, and we have to use the user's money for many of the functions. For instance: I create a variable a = 100 and I used the variable in the function with global a. But my teacher doesn't allow us to use the term global so i have to use something other than global.
For example:
a = 100
def withdraw():
global a
ko = input("Please enter the amount you want to withdraw:")
if ko > a:
print "You don't have " + " " + str(ko) + " " + "in your account."
print "Going back to main menu..."
else:
a = a - ko
print str(ko) + "Dollar" + "withdrawn from your account"
In this particular example, I'd simply pass a in, and return it back to the caller:
# Renamed a to balance
def withdraw(balance):
# Take input as before
return balance - ko
a = 100
a = withdraw(a)
Whenever possible, pass any relevant data in, and return any results back.
You can make the global variable (we are going to use account instead of a for this example) a local variable in your main and use it in every function that requires it. In this case something like this:
def withdraw(account):
# ... code here
account -= ko
print str(ko) + " Dollar withdrawn from your account"
return account
and you would call it like this
account = withdraw(account)
There are many ways you can avoid using global variables in your code for e.g. by using instance variables.
As your teacher suggests, you should avoid global variables because you may mistakenly declare another variable with the same name and then while reading the code, it will not be obvious which variable is getting accessed, making it hard to debug your code.
I suggest something similar to this:
class BankAccount():
def __init__(self, initial_balance):
self.balance = initial_balance
def withdraw(self, withdraw_amount=0):
if withdraw_amount > self.balance:
print "You don't have " + " " + str(withdraw_amount) + " " + "in your account."
print "Going back to main menu..."
else:
self.balance -= withdraw_amount
print str(withdraw_amount) + "Dollar" + "withdrawn from your account"
Following this you can create an instance of a bank account and withdraw form it in the following way:
bank_account = BankAccount(initial_balance=1000)
bank_account.withdraw(withdraw_amount=100)
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()
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()
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.