In my code, the 'detentions' integer seems to be taking the value of the 'day' integer when calling new_week()
I have looked through the code and just cannot find what is causing it.
It is defined like:
def new_week(self, detentions, motivation):
print(colored(detentions, 'yellow'))
oldmotiv = motivation
for i in range(0, detentions):
motivation = motivation - 3
print(colored("Detentions: " + str(detentions), 'yellow'))
print(colored("Motivation: " + str(motivation), 'yellow'))
print(colored("End of week summary: ", 'green'))
lostmotiv = oldmotiv - motivation
print(colored("You lost " + str(lostmotiv) + " motivation!", 'green'))
detentions = 0
It is invoked like:
print("It's the weekend! What would you like to do?")
WorldSettings.new_week(detentions, day, motivation)
again = input("Continue? yes, no ")
again.lower()
day = 1
Full code is here, on Repl.it
In your code you are invoking the method as if it were a class method:
WorldSettings.new_week(detentions, day, motivation)
It should be as an instance method:
class_worldsettings.new_week(detentions, day, motivation)
Also, notice that you are invoking the method with 3 parameters, but your method is defined to only need 2 parameters (besides the elf`that is an implicit parameter):
def new_week(self, detentions, motivation)
So it should be:
def new_week(self, detentions, day, motivation)
Related
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 a beginner and recently started python development.
The code i was working on:
import random
import textwrap
def show_message(dotted_line,width):
print(dotted_line)
print("\033[1m"+ "Attack of clones:" + "\033[0m")
message = (
"The war between humans and their arch enemies , Clones was in the offing. Obi-Wan, one of the brave Jedi on his way ,"
"he spotted a small isolted settlement .Tired and hoping to replenish his food stock , he decided to take a detour."
"As he approached the village, he saw five residence , there was no one to be seen around.He decided to enter" )
print(textwrap.fill(message, width = width))
def show_mission(dotted_line):
print("\033[1m"+ "Mission:" + "\033[0m")
print('\t Choose the hit where Obi wan can rest...')
print("\033[1m"+ "TIP:" + "\033[0m")
print("Be careful as there are Stormtroopers lurking around!")
print(dotted_line)
def occupy_huts():
global huts
huts = []
while len(huts) < 5:
random_choice = random.choice(occupants)
huts.append(random_choice)
def process_user_choice():
message = "\033[1m"+ "Choose the hut to enter (1-5) " + "\033[0m"
uc = input("\n" + message)
index = int(uc)
print("Revealing the occupants...")
message = ""
def reveal_occcupants(index,huts,dotted_line):
for i in range (len(huts)):
occupant_info = "<%d:%s>"%(i+1,huts[i])
if i + 1 == index:
occipant_info = "\033[1m"+ "" + "\033[0m"
message += occupant_info + " "
print("\t" + message)
print(dotted_line)
def enter_huts(index,huts,dotted_line):
print("\033[1m"+ "Entering Hut %d ..." %index + "\033[0m")
if huts[index - 1] == 'clones':
print("\033[1m"+ "There's Stormtrooper Here!!" + "\033[0m")
else:
print("\033[1m"+ "It's Safe here!" + "\033[0m")
print(dotted_line)
def run():
keep_playing = 'y'
global occupants
occupants = ['clones','friend','Jedi Hideout']
width = 70
dotted_line = '-' * width
show_message(dotted_line, width)
show_mission(dotted_line)
while keep_playing == 'y':
huts = occupy_huts()
index = process_user_choice()
reveal_occcupants(index,huts,dotted_line)
enter_huts(index,huts,dotted_line)
keep_playing = raw_input("Play Again?(y/n)")
if __name__ == '__main__':
run()
and the error is in body of
def reveal_occupants.
"TypeError: object of type 'NoneType' has no len()"
how this error can be overcome and please suggest an alternative approach too
Here :
while keep_playing == 'y':
huts = occupy_huts()
Your occupy_huts() function doesn't return anything (it populates a global variable huts but doesn't return it), so the after the huts = occupy_huts() statement huts is now None (the default function return value if you don't explicitely return something). Then you pass this (now None) huts variable to reveal_occupants() :
reveal_occcupants(index,huts,dotted_line)
The solution is simple: modify occupy_huts so instead of working on a global (which is almost always a very bad idea) and returning None, it works on a local variable and returns it:
def occupy_huts():
huts = []
while len(huts) < 5:
random_choice = random.choice(occupants)
huts.append(random_choice)
return huts
While we're at it, you are using a global for occupants too, which is brittle (occupy_huts() will break if called before this variable has been created), while you could just pass it as argument:
def occupy_huts(occupants):
huts = []
while len(huts) < 5:
random_choice = random.choice(occupants)
huts.append(random_choice)
return huts
and then in run():
def run():
keep_playing = 'y'
occupants = ['clones','friend','Jedi Hideout']
# ...
while keep_playing == 'y':
huts = occupy_huts(occupants)
The funny thing here is that you pass arguments for mundane stuffs that are mostly constants and have no impact on the program's logic (ie dotted_lines), but use globals for the important things - should really be the other way round (declare dotted_lines as a pseudo_constant at the start of your module and don't bother passing it to functions) ;)
Also, note that you have a similar issue with process_user_choice() here :
while keep_playing == 'y':
huts = occupy_huts()
index = process_user_choice()
since your process_user_choice() function doesn't return anything either. You should modify it so it returns its local variable index.
len() method accepts an object as parameter.
in your case, at line 43, huts may be None, so you can get an error.
you should insert if condition like below after line 42
if huts is None:
return
My guess is that "huts" is None-type, because occupy_huts() was never called. Or there is an issue with the scope of the "huts" variable -- this might be cleared up by declaring it as an empty set outside of the occupy_huts() function.
Also, you could take advantage of Python's syntax and change line 43 to "for hut in huts:". If you also need the index of the hut, try "for hut, i-hut in enumerate(huts):".
You method "reveal_occupants" receive empty value as huts. That means, that type of huts is None. That why you can't get len of this value.
I am trying to create a def file within a py file that is external eg.
calls.py:
def printbluewhale():
whale = animalia.whale("Chordata",
"",
"Mammalia",
"Certariodactyla",
"Balaenopteridae",
"Balaenoptera",
"B. musculus",
"Balaenoptera musculus",
"Blue whale")
print("Phylum - " + whale.getPhylum())
print("Clade - " + whale.getClade())
print("Class - " + whale.getClas())
print("Order - " + whale.getOrder())
print("Family - " + whale.getFamily())
print("Genus - " + whale.getGenus())
print("Species - " + whale.getSpecies())
print("Latin Name - "+ whale.getLatinName())
print("Name - " + whale.getName())
mainwindow.py:
import calls
import animalist
#import defs
keepgoing = 1
print("Entering main window")
while True:
question = input("Which animal would you like to know about?" #The question it self
+ animalist.lst) #Animal Listing
if question == "1":
print(calls.printlion())#Calls the animal definition and prints the characteristics
if question == "2":
print(calls.printdog())
if question == "3":
print(calls.printbluewhale())
'''if question == "new":
def new_animal():
question_2=input("Enter the name of the new animal :")'''
What I am trying to do is that question == new would create a new def in the calls.py and that I would be able to add a name to the def and the attributes as well.
I was hoping you could lead me to a way of how to do this, and if it is not possible please just say and I will rethink my project :)
What you're trying to do here seems a bit of a workaround, at least in the way you're trying to handle it.
If i understood the question correctly, you're trying to make a python script that takes input from the user, then if that input is equal to "new", have it be able to define a new animal name.
You're currently handling this using a whole lot of manual work, and this is going to be extremely hard to expand, especially considering the size of the data set you're presumably working with (the whole animal kingdom?).
You could try handling it like this:
define a data set using a dictionary:
birds = dict()
fish = dict()
whales = dict()
whales["Blue Whale"] = animalia.whale("Chordata",
"",
"Mammalia",
"Certariodactyla",
"Balaenopteridae",
"Balaenoptera",
"B. musculus",
"Balaenoptera musculus",
"Blue whale")
whales["Killer Whale"] = ... # just as an example, keep doing this to define more whale species.
animals = {"birds": birds, "fish": fish, "whales": whales} # using a dict for this makes you independent from indices, which is much less messy.
This will build your data set. Presuming every whale class instance (if there is one) inherits properties from a presumptive Animal class that performs all the printing, say:
Class Animal():
# do some init
def print_data(self):
print("Phylum - " + self.getPhylum())
print("Clade - " + self.getClade())
print("Class - " + self.getClas())
print("Order - " + self.getOrder())
print("Family - " + self.getFamily())
print("Genus - " + self.getGenus())
print("Species - " + self.getSpecies())
print("Latin Name - "+ self.getLatinName())
print("Name - " + self.getName())
You can then have a Whale class:
class Whale(Animal)
Which now has the print_data method.
for whale in whales:
whales[whale].print_data()
With that out of the way, you can move on to adding input:
In your main.py:
while True:
question = input("Which animal would you like to know about?" #The question it self
+ animalist.lst) #Animal Listing
try:
id = int(question)
# if the input can be converted to an integer, we assume the user has entered an index.
print(calls.animals[animals.keys[id]])
except:
if str(question).lower() == "new": # makes this case insensitive
new_species = input("Please input a new species")
calls.animals[str(new_species)] = new_pecies
# here you should process the input to determine what new species you want
Beyond this it's worth mentioning that if you use dicts and arrays, you can put things in a database, and pull your data from there.
Hope this helps :)
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()
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)