changing variable value inside IF loop - python

I have a function which accepts value 1-5, and I want to declare a global variable called 'Des' and make it change according to the option selected because I want to use that value in another function. I tried this but it does not work.
def mainNJ():
#S_menu()
print( "\033[1m" " PLEASE SELECT THE TYPE OF DONATION.")
global Des
validate = False
while not validate:
option = input(" INPUT VALUE 1 TO 5 : " "\033[0m")
# For Selection 1 Animal Protection And Welfare.
if option == str(1):
validate = True
print()
print("\033[1m" " Animal Protection And Welfare Has Been Selected." "\033[0m")
#Amount()
Des1 = " Animal Protection And Welfare Has Been Selected."
Des = Des1
# For Selection 2 Support For Natural Disaster.
elif option == str(2):
validate = True
print()
print("\033[1m" " Support For Natural Disaster Has Been Selected." "\033[0m")
#Amount()
Des2 = " Support For Natural Disaster Has Been Selected."
Des = Des2
# For Selection 3 Children Education And Activities.
elif option == str(3):
validate = True
print()
print("\033[1m" " Children Education And Activities Has Been Selected." "\033[0m")
#Amount()
Des3 = " Children Education And Activities Has Been Selected."
Des = Des3
# For Selection 4 Children Education And Activities.
elif option == str(4):
validate = True
print()
print("\033[1m" " Caregiving And Health Research Has Been Selected." "\033[0m")
#Amount()
Des4 = " Caregiving And Health Research Has Been Selected."
Des = Des4
# For Selection 5 Conservation Of Cultural Arts.
elif option == str(5):
validate = True
print()
print("\033[1m" " Conservation Of Cultural Arts Has Been Selected." "\033[0m")
#Amount()
Des5 = " Conservation Of Cultural Arts Has Been Selected."
Des = Des5
else:
print()
print(" Invalid Option. Please Try Again.")
#S_menu()

Maybe, if Des is not defined outside of function, you are trying to access it before it > > was assigned. i.e. you are doing something with Des before making mainNJ() call
to give solution, if this is problem
in another function, where you use it
try:
print(Des) # example of usage
except NameError:
print("Des not yet created")
# also you can put return statement so function does not continue
# or call mainNJ() here

You assign Des to Desx and that is a string. You need to assign it to int(option)

Related

Check element value of specific element in list

I'm working on an assignment covering classes. There are several requirements but my program meets nearly all of them the way it is currently.
The program is to prompt the user to enter either a car or truck into their virtual garage. From there they select a number of options depending on if it is a car or truck.
The user continues doing this until they are done adding vehicles, then they get prompted with the vehicles they entered and their info.
As it is currently, I can enter an endless amount of cars or trucks and it will print what I entered correctly. It will not allow me to enter in both cars and trucks, which is what I need it to do.
I know the issue is likely with my last loop since it references carTruck and it should probably reference the value of the element in the instances list. I am unsure how to do that though.
I realize there are probably better ways to achieve this but there are certain ways it must be done according to the assignment. Also, error handling isn't needed in this so that is why it is not included.
class Vehicle:
def __init__(self, make, model, color, fuelType,options):
self.make = make
self.model = model
self.color = color
self.fuelType = fuelType
self.options = options
def getMake(self):
self.make = input('Please enter the vehicle make: ').title()
return self.make
def getModel(self):
self.model = input('Please enter the vehicle model: ').title()
return self.model
def getColor(self):
self.color = input('Please enter the vehicle color: ')
return self.color
def getFuelType(self):
self.fuelType = input('Please enter the vehicle fuel type: ')
return self.fuelType
def getOptions(self):
optionslist = []
print('\nEnter Y or N for the following options')
radio = input('Does your vehicle have a radio: ').lower()
bluetooth = input('Does your vehicle have bluetooth: ').lower()
cruise = input('Does your vehicle have cruise control: ').lower()
window = input('Does your vehicle have power windows: ').lower()
lock = input('Does your vehicle have power locks: ').lower()
mirror = input('Does your vehicle have power mirrors: ').lower()
rstart = input('Does your vehicle have remote start: ').lower()
bcamera = input('Does your vehicle have a back up camera: ').lower()
if radio == 'y':
optionslist.append('Radio')
if bluetooth == 'y':
optionslist.append('Bluetooth')
if cruise == 'y':
optionslist.append('Cruise Control')
if window == 'y':
optionslist.append('Power Windows')
if lock == 'y':
optionslist.append('Power Locks')
if mirror == 'y':
optionslist.append('Power Mirrors')
if rstart == 'y':
optionslist.append('Remote Start')
if bcamera == 'y':
optionslist.append('Backup Camera')
self.options = optionslist
return self.options
#car child class
class Car(Vehicle):
def __init__ (self, make, model, color, fuelType,options, engineSize, numDoors):
self.engineSize = engineSize
self.numDoors = numDoors
Vehicle.__init__(self, make, model, color, fuelType,options)
def getEngineSize(self):
self.engineSize = input('Please enter your engine size in liters: ')
return self.engineSize
def getNumDoors(self):
self.numDoors = input('Please enter the number of doors: ')
return self.numDoors
#pickup child class
class Pickup(Vehicle):
def __init__ (self, make, model, color, fuelType,options, cabStyle, bedLength):
self.cabStyle = cabStyle
self.numDoors = bedLength
Vehicle.__init__(self, make, model, color, fuelType, options)
def getCabStyle(self):
self.cabStyle = input('Please enter the cab style: ')
return self.cabStyle
def getBedLength(self):
self.bedLength = input('Please enter the bed length: ')
return self.bedLength
#creates instance and loops to get info for vehicles from user
instances = []
Exit = 'n'
x = 0
while Exit == 'n':
carTruck = input('Are you entering a car or truck? ')
plateNum = input('please enter your license plate number: ')
instances.append(carTruck + plateNum)
#if statement to use correct class based on user input
if carTruck == 'car':
instances[x] = Car('','','','','','','')
instances[x].getMake()
instances[x].getModel()
instances[x].getColor()
instances[x].getFuelType()
instances[x].getEngineSize()
instances[x].getNumDoors()
instances[x].getOptions()
if not instances[x].options:
print('\nYou need to select at least one option.')
Vehicle.getOptions(instances[x])
elif carTruck == 'truck':
instances[x] = Pickup('','','','','','','')
instances[x].getMake()
instances[x].getModel()
instances[x].getColor()
instances[x].getFuelType()
instances[x].getCabStyle()
instances[x].getBedLength()
instances[x].getOptions()
if not instances[x].options:
print('\nYou need to select at least one option.')
Vehicle.getOptions(instances[x])
#allows user to stop adding vehicles
Exit = input('Are you done adding vehicles (Y/N): ').lower()
x = x + 1
#loops through instances and provides output dependent on whether it is a car or truck.
b = 0
while b < len(instances):
if carTruck == 'truck':
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
elif carTruck == 'car':
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].numDoors} door with a {instances[b].engineSize} liter {instances[b].fuelType} engine.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
b = b + 1
Output:
Are you entering a car or truck? car
please enter your license plate number: 123456
Please enter the vehicle make: ford
Please enter the vehicle model: mustang
Please enter the vehicle color: red
Please enter the vehicle fuel type: gas
Please enter your engine size in liters: 5
Please enter the number of doors: 2
Enter Y or N for the following options
Does your vehicle have a radio: y
Does your vehicle have bluetooth: y
Does your vehicle have cruise control: y
Does your vehicle have power windows: y
Does your vehicle have power locks: y
Does your vehicle have power mirrors: y
Does your vehicle have remote start: y
Does your vehicle have a back up camera: y
Are you done adding vehicles (Y/N): n
Are you entering a car or truck? truck
please enter your license plate number: 789456
Please enter the vehicle make: chevy
Please enter the vehicle model: 1500
Please enter the vehicle color: black
Please enter the vehicle fuel type: gas
Please enter the cab style: crew cab
Please enter the bed length: 6
Enter Y or N for the following options
Does your vehicle have a radio: y
Does your vehicle have bluetooth: y
Does your vehicle have cruise control: y
Does your vehicle have power windows: y
Does your vehicle have power locks: y
Does your vehicle have power mirrors: y
Does your vehicle have remote start: y
Does your vehicle have a back up camera: y
Are you done adding vehicles (Y/N): y
Traceback (most recent call last):
File "c:\Users\chris\Desktop\School\Intro to Programming\python_work\classes.py", line 138, in <module>
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
AttributeError: 'Car' object has no attribute 'cabStyle'
``
Before you read the answer, ask yourself where did you get the carTruck instance you are trying to print.
...
You are referring to the last entry you have added instead of referring to the current instance! So correct way will be, eg.
b = 0
while b < len(instances):
if isinstance(instances[b], Pickup): #CHANGED
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
elif isinstance(instances[b], Car): #CHANGED
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].numDoors} door with a {instances[b].engineSize} liter {instances[b].fuelType} engine.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
b = b + 1
I want to add two suggestions...
1st - don't use while loop here use for, eg.
for moving_thing in instances:
if isinstance(moving_thing, Pickup):
...
2nd - create __str__ method for each class so you could call it without checking what type of vehicle it is. More here Dunder methods, than you could call
for moving_thing in instances:
print(moving_thing)

How to pass string as object name?

Here's how I finally solved the problem:
I created two lists, one containing the objects, the other containing the object names (strings). Then I write in the code to make sure that an object and its name are appended to the two lists at the same time. So that I can easily call an object with ObjectList[NameList.index(Name)], similarly with NameList[ObjectList.index(Object)] to call a name.
I don't know if it's the best solution. Maybe I'll find a better way to do this when I know more about python.
Thanks everyone for your help.
I've updated my code below.
I am trying to make a game that can take in user input, make new objects based on that input, and connect that object with an existing web of objects.
So I have the initial objects: Adam = Human("Male","God","God") and Eve = Human("Female", "God", "God")
But after Adam and Eve, I want to create objects like Josh = Human("Male", Adam, Eve), here the attributes of Josh becomes one string and two objects, instead of three strings. But if this worked, I can create a web of objects where every obect-child (except Adam and Eve) has object-parents.
If anyone has any suggestions on that, please let me know.
I want to pass an user-input string as the name of a new object of a certain class. I can't use eval() because it's dangerous. What can I do?
I am new to python3 and creating a little game just for practicing. I've created this class called "Human", and in the game users are supposed to input a name for a new Human.
I haven't tried much as none of the questions I found match my problem. I only know so far that I can't use eval() because it might cause trouble if things like eval("import") happened.
import random
# list of all humans
Humans = []
# creating the class Human
class Human:
global Humans
def __init__(self, gender, father, mother):
self.gender = gender
self.father = father
self.mother = mother
self.canHaveChild = False
Humans.append(self)
def growup(self):
self.canHaveChild = True
Adam = Human("Male", "God", "God")
Eve = Human("Female", "God", "God")
Humans.append(Adam)
Humans.append(Eve)
# creating the class SpiritualHuman
class SpiritualHuman:
def __init__(self, gend, stparent, ndparent):
self.stparent = stparent
self.ndparent = ndparent
self.gend = gend
self.canHaveChild = False
# haveChild function
def haveChild(Human1, Human2):
gender = ""
gen_pro = random.random()
if gen_pro < 0.5:
gender = "Female"
else:
gender = "Male"
if Human1.canHaveChild & Human2.canHavechild:
if (Human1.gender == "Male") & (Human2.gender == "Female"):
return Human(gender, Human1, Human2)
elif (Human1.gender == "Female") & (Human2.gender == "Male"):
return Human(gender, Human1, Human2)
elif (Human1.gender == "Male") & (Human2.gender == "Male"):
return SpiritualHuman("Yang", Human1, Human2)
else:
return SpiritualHuman("Yin", Human1, Human2)
else:
return "forbidden child"
# a list of all commands
command_list = ["who is the mother of", "who is the father of", "who is the child of", "have child named"]
# user input could be:
# "who is the mother of xxx"
# "who is the father of xxx"
# "who is the child of xxx and xxx"
# "xxx and xxx have child named xxx"
# user input function
def get_input():
command = input(":")
comsplit = command.split()
# check 1st command
if command_list[0] in command:
if comsplit[5] in str(Humans):
print("the mother of", comsplit[5], "is", Humans[str(Humans).index(comsplit[5])].mother())
else:
print(comsplit[5], "does not exist")
# check 2nd command
elif command_list[1] in command:
if comsplit[5] in str(Humans):
print("the father of", comsplit[5], "is", Humans[str(Humans).index(comsplit[5])].father())
else:
print(comsplit[5], "does not exist")
# check 3rd command
elif command_list[2] in command:
if comsplit[5] in str(Humans) and comsplit[7] in str(Humans):
for i in Humans:
if str(i.father()) in [comsplit[5], comsplit[7]] and str(i.mother()) in [comsplit[5], comsplit[7]]:
print(i, "is the child of", comsplit[5], "and", comsplit[7])
else:
print("they don't have a child")
else:
print("at least one of the parents you mentioned does not exist")
# check 4th command
elif command_list[3] in command:
if comsplit[0] in str(Humans) and comsplit[2] in str(Humans):
# here's where the problem is
# I want to use comsplit[7] as name for a new Human object
# how should I do it?
else:
print("at least one of them is not human")
elif command == "humans":
print(str(Humans))
else:
print("invalid command. If you need help, please type 'help'")
while(True):
get_input()
I don't know how to avoid errors, but I expect that if the user inputs:
Adam and Eve have child named Josh
the result should be that Josh is an object of class Human whose father is Adam and mother is Eve.
Use a dict containing your humans, with their names as keys:
# global dict, defined at the top of your code
humans = {}
def get_input():
command = input(":").split()
if len(command) == 1:
print(HUMANS) # well, don't know what this one is supposed to be...
elif len(command) > 1:
humans[command[1]] = Human(command[1])
humans[command[2]] = Human(command[2])
humans[command[0]] = haveChild(humans[command[1]], humans[command[2]])
Edit: I just read your comment, can't finish to answer right now, but in short, you must create your father and mother as humans before you can use them, so you need to change something in the way you create them...
The user will enter 2 humans objects with their attributes (gender,father,mother).The 2 objects will be passed to haveChild().Check my code
//import radom, it was missing from your code
import random
class Human:
def __init__(self, gender, father, mother):
self.gender = gender
self.father = father
self.mother = mother
self.canHaveChild = False
def growup(self):
self.canHaveChild = True
def haveChild(obj1, obj2):
gender = ""
gen_pro = random.random()
if gen_pro < 0.5:
gender = "Female"
else:
gender = "Male"
//obj1.canHaveChild & obj2.canHavechild, was throwing error
//'Human' object has no attribute 'canHavechild'
if obj1.canHaveChild and obj2.canHavechild:
if (obj1.gender == "Male") & (obj2.gender == "Female"):
return Human(gender, Human1, Human2)
elif (obj1.gender == "Female") & (obj2.gender == "Male"):
return Human(gender, mother, father)
elif (obj1.gender == "Male") & (obj2.gender == "Male"):
return SpiritualHuman("Yang", Human1, Human2)
else:
return SpiritualHuman("Yin", Human1, Human2)
else:
return "forbidden child"
def get_input():
print("Enter Human1 gender,father,mother")
command = input(":").split()
human1 = Human(command[0],command[1],command[2])
print("Enter Human2 gender,father,mother")
command = input(":").split()
human2 = Human(command[0],command[1],command[2])
haveChild(human1,human2)
# the problem above is, command[0] is an immutable (a string), I can't use it
# directly as the name of a new object
get_input()

CPU player dice game

Need to program a CPU that decides between throwing the dice again or ending its turn.
The game already works with two players. Now I just need the 2nd player to make decisions on its own.
What do I do? This is a part of the code:
while not juego_termina:
print("")
jug_turno.lanzar_dado(dado)
jug2.dec_cpu()
while jug_turno.jugando:
jug2.dec_cpu() #Se anida un while para cada turno del jugador
print("Puntaje parcial acumulado:",end=' ')
print(jug_turno.p_parcial)
continuar = ""
jug2.dec_cpu()
while continuar != "SI" and continuar != "NO": #Pregunta si continua el turno
print("Desea seguir jugando? (SI/NO)")
continuar = input().upper() #.upper para la mayuscula
if continuar == "SI":
jug_turno.lanzar_dado(dado)
else:
jug_turno.terminar_turno()
if jug_turno.p_total >= meta: #Compara el puntaje total con la meta asignada al inicio
juego_termina = True #Se acaba el juego y salta a nombrar el ganador
else:
if jug_turno == jug1:
jug_turno = jug2
else:
jug_turno = jug1
mostrar_puntajes(jug1,jug2)
print("El ganador es:")
print(jug_turno.nombre)
I only know a small amount of Spanish, so it's possible I'm reading your code incorrectly, but it looks like the game works like Blackjack - the winning player is the player who has the highest total without going over some maximum value (21 in the case of Blackjack). The code for the simplest algorithm you could use probably looks something like this:
def dec_cpu(maximum):
total = 0
while total < maximum and (highest_possible_die_roll / 2) < (maximum - total):
total = total + roll_die()
return total
The (highest_possible_die_roll / 2) < (maximum - total) part is essentially saying, "if there's less than a 50% chance that rolling the die again will put me over the maximum, roll again". From there, you can refine it depending on the rules of the game. For example, if there's an amount of money being wagered each time, the computer might want to be 75% sure that they won't go over the maximum when the die is rolled if there's a lot of money on the line.

Troubleshooting my code - Key Error results when referencing by key name taken from raw_input()

This part of the equation is the part I don't need help on. This basically asks the user to input the amount of player in the game, and creates a sub-dictionary for every player within one main dictionary:
ans = raw_input('Enter Amount of Players: ').lower()
if ans == '2':
a = raw_input('What is Player 1 named: ')
b = raw_input('What is Player 2 named: ')
cf={a:{}, b:{}}
p1 = raw_input(a + ", what is your city named: ")
p2 = raw_input(b + ", what is your city named: ")
cf[a][p1] = '50'
cf[b][p2] = '50'
for key, cf in cf.items():
print(key)
for attribute, value in cf.items():
print('{} : {}'.format(attribute, value))
Here is the part I need help on:
##This function may be screwing it up
def cva(x):
y = cf[ques][city]
y = float(y)
return x + y
while True:
one = raw_input("Type 'view' to view civil form, type 'change' to change civil order, or 'add' to add a city: ")
if one == 'change':
ques = raw_input('Enter Name of Player That Will Change His/Her Civil Form: ').lower()
city = raw_input(ques + 'Enter Name Of City That Will Change Civil Form: ').lower()
inc = raw_input(ques + ' Enter Amount of change for ' + city + ": ").lower()
cf[ques][city]=cva(float(inc))
for key, cf in cf.items():
print(key)
for attribute, value in cf.items():
print('{} : {}'.format(attribute, value))
Lets say I inputted the name 'evan' and his city 'LA', an error would come up saying 'KeyError: 'evan'. How do I get this to work?
You need to make sure the Player has been previously added to the dictionary. You should also normalize the inputs and dictionary keys.
Assuming you do not need to support case sensitive unique names for people, then adding:
if ques.lower() not in [key.lower() for key in cf.keys()]:
print "Player record does not exist - please create player before updating."
continue
after the player name input would be one way to handle this sort of thing.
The problem is that you have to update your dic before you call the cva function. Otherwise, the y = cf[ques][city] in the cva function won't have the updated city value.
ex :
while True:
one = raw_input("Type 'view' to view civil form, type 'change' to change civil order, or 'add' to add a city: ")
if one == 'change':
ques = raw_input('Enter Name of Player That Will Change His/Her Civil Form: ').lower()
city = raw_input(ques + 'Enter Name Of City That Will Change Civil Form: ').lower()
inc = raw_input(ques + ' Enter Amount of change for ' + city + ": ").lower()
cf[ques].update({city:0}) # create the entry in the dic
cf[ques][city] = cva(float(inc))
# ...
And as #selllikesybok said, add some code that verify the dic before iterate on it.
Actually the problem is due to a bug in the first snippet of code which you think is OK.
Note that in theforloop at the end where you have:
for key, cf in cf.items():
print(key)
for attribute, value in cf.items():
print('{} : {}'.format(attribute, value))
However the issue is with thefor key, cf in cf.items():which changes the value ofcfwhen it executes.
If you change the name of the second target variable fromcfto something else which does not conflict with any existing variable, your second part won't get theKeyErroron'evan'any longer.For example:
for key, info in cf.items():
print(key)
for attribute, value in info.items():
print('{} : {}'.format(attribute, value))

functions and returns

I'm new to python and I've been assigned in writing an invoice program for a hypothetical hotel. I'm running into difficulty when trying to call on functions for their return value. I could really use the help as I'm really stumped. The implementation code is to follow along with the description of the program so a handle can be put on what exactly is the mistake.
Invoice
PCCC Palace Hotel
Eddie’s Billing Statement
Number of days in hotel: 2
Room Charges $675.00
Internet Charges $29.85
Television Charges $8.85
Total Charges $703.70
Local Taxes $24.63
Total Due $728.33
Thank you for using PCCC Palace Hotel. Hope to see you again.
Requirements:
• Include relevant information in the form of comments in your code as explained in the class.
• Use a different function to handle each of
o the room type
o The Internet Access usage
o The TV usage
• The Internet and TV usage may be denied, in that case the charges would be $0.00
• All the rates are defined as local constants inside the functions
• Each function has a menu that displays the options to select from
• Each function returns the charges incurred for that option
• The local tax rate is 3.5% and is to be defined as a local constant
The problem is:
Traceback (most recent call last):
File "C:/Python33/hotel.py", line 28, in
print("Room Charges: ", roomcost())
NameError: name 'roomcost' is not defined
Code:
def main():
input = int , 2
costofinternet = costofinternet
costoftv = costoftv
customername = input("The Customer Name Please: ")
visitdays = input("Enter the Number of Days in the Hotel: ")
room = input("Rooms Used \n1 - Single Room - One Bed \n2 - Family Room - Doulble Bed \n3 - Suite \n Enter Choice 1, 2, or 3: ")
roomcost()
internet = input("Would You like Internet: ")
if internet == 'Y':
internettype = input("Internet Access Usage \n1 - Wireless \n2 - Wired \nEnter Choices 0, 1, or 2: ")
television = input("Would You like to use the TV: ")
if television == 'Y':
tvtype = input("TV Usage \n1 - Cable \n2 - Basic Channels \nEnter Choice 0, 1, or 2: ")
print("\t\t\t\t\t\t Invoice")
print("\t\tPCCC Palace Hotel")
print(customername, "'s Billing Statement")
print("Number of Days in Hotel: ", visitdays)
print("Room Charges: ", roomcost)
print("Internet Charges: ", costofinternet)
print("Television Charges: ", costoftv)
totalcharge = print("Total Charges: ", roomcost + costofinternet + costoftv)
localtaxes = print("Local Taxes: ", ((roomcost + costofinternet + costoftv) * .035))
print("\t\tTotal Due\t\t\t", totalcharge + localtaxes)
print("\t\tThank You For Using PCCC Palace Hotel. Hope To See You Again.")
def roomcost():
cost = []
if room == '1':
cost == 225
if room == '2':
cost == 325
if room == '3':
cost == 550
return(cost)
def internet():
costofinternet = []
if internettype == '0':
costofinternet == 0
if internettype == '1':
costofinternet == 9.95
if internettype == '2':
costofinternet == 5.95
return(costofinternet)
def tv():
costoftv = []
if tvtype == '0':
costoftv == 0
if tvtype == '1':
costoftv == 9.95
if tvtype == '2':
costoftv == 2.95
return(costoftv)
roomcost is a function, so you'll need to call it using the () operator, along with your other function calls:
print("Room Charges: ", roomcost())
print("Internet Charges: ", costofinternet())
print("Television Charges: ", costoftv())

Categories