while loops not working for def() functions - python

I am trying a program that adds two elements together to make a new one, and you have to make as many elements as you can in this process e.g. https://littlealchemy.com/
But I can't seem to get my definitions to re-run inside of a while loop.
When I run it, it doesn't seem to strip the [] out of the list. What's more, it only runs once and then leaves the terminal blank.
Sorry about the abbreviations, I prefer it like that, but I can change it if needed.
Any help would be appreciated.
Thankyou.
Here is my code:
element1 = ""
element2 = ""
de = [] #discovered elements
ne = "" #new element
o1 = ""
o2 = ""
pne = ""
print("You have unlocked Fire, Water, Earth, and Air")
print("To see your unlocked elements, enter in 'menu' into the 'give the first element' option")
e1 = input("Give the first element ") #element 1
e2 = input("Give the second element ") #element 2
def pnestuff():
pne = str(de); pne.strip("["); pne.strip("]")
def operate(x, y, z):
global e1
global e2
o1 = (x)
o2 = (y)
ne = (z)
if (e1 == o1 and e2 == o2) or (e1 == o2 and e2 == o1):
de.append(ne)
print("You have unlocked "+ne+"!")
print("Your complete element list:")
pnestuff()
print(pne)
e1 = ""
e2 = ""
def menu():
global e1
global e2
if e1 == "menu":
print("You have unlocked:")
pnestuff()
print(pne)
e1 = ""
e2 = ""
#===============================================================================#
while 1:
menu()
operate("fire", "water", "steam")

Overall, your code is a disater. But let's focus on your immediate problem. I would guess it's this:
def pnestuff():
pne = str(de); pne.strip("["); pne.strip("]")
which wants to set the global pne but fails to declare it global, and fails to understand that strings are immutable:
def pnestuff():
global pne
pne = str(de).lstrip("[").rstrip("]")
though a better definition might be:
def pnestuff():
global pne
pne = ', '.join(de)

I forgot to put the two insert elements lines inside the while loop. facepalm. and thankyou everyone for the help with x.join

Related

why i am getting blank list as output in python even after appending item in it?

#bll
class cms():
def __init__(self):
self.namelist = []
self.idlist = []
self.moblist = []
self.emaillist = []
self.reslist = []
def addcustomer(self):
self.idlist.append(id)
self.namelist.append(name)
self.moblist.append(mob)
self.emaillist.append(email)
return print("Customer Added")
def showcustomer(self):
print(self.idlist, self.namelist, self.moblist, self.emaillist)
#pl
while(1):
print("Enter Your Choice Enter 1 to Add, 2 to search, 3 to delete, 4 to Modify, 5 to Display All, 6 to Exit")
ch = input("Enter your choice")
conman = cms()
if ch == '1':
id = input("ENter your id")
name = input("Enter Your name")
mob = input("Enter your mobile no")
email = input("Enter your email")
conman.addcustomer()
elif ch == '2':
conman.showcustomer()
this is my code when I am entering 1 then the customer gets added,but when I call another method to print that appended item it returns blank list
Output:-
Enter your choice2
[] [] [] []
Help!! Please.
conman = cms()
Because this is inside the loop, each time through the loop, this creates a separate, new cms with its own lists of data, and makes conman be a name for the new value.
elif ch == '2':
conman.showcustomer()
This, therefore, displays information from the new conman, ignoring everything that was done in the previous iteration of the loop.

access variables across different classes using kivy

I am trying to access a variables across classes to compare strings. I thought to use a global but that only works if I assign the global a value. I am assigning each variable random string from a list in one class and then doing the same in another class then comparing to see if they match.
class A(screen):
check1 = ""
check2 = ""
check3 = ""
def on_enter(self):
rand_files = ["hello", "goodbye", "what"]
Check1, Check2, Check3 = rand_files
class B(screen):
Ans1 = ""
Ans2 = ""
Ans3 = ""
Ans4 = ""
Ans5 = ""
Ans6 = ""
def on_enter(self):
rand_files = ["hello", "night", "goodbye", "day", "what", "morning"]
Ans1, Ans2, Ans3, Ans4, Ans5, Ans6 = rand_files
def verifyAns1(self):
if Ans1 == Check1 or Ans2 == Check2 or Ans3 == Check3:
print("You got it!!!")
else:
print("Try again")
When I try to do it like this I get the error:
NameError: name 'Ans1' is not defined
You are using class variables in your example. Nothing wrong here, but be aware that if you have multiple instances of these classes, each instance shares the class variables. If one changes a value, the value is changed for all.
If that behavior is not what you are looking for, you probably want to use Python properties.
It is not that one way is necessarily better than the other, it is just how you wish to control the scope of the variables.
That being said, here is an example that may solve your problem using class variables:
class A:
a0 = 0
a1 = 1
a2 = 2
def __init__(self):
print('hello from A')
print(A.a0)
print(B.b2)
class B:
b0 = 3
b1 = 4
b2 = 5
def __init__(self):
print('hello from B')
print(A.a2)
print(B.b0)
A()
B()
And the result:
hello from A
0
5
hello from B
2
3

How can I modify this code so it doesn't go back to the beginning of the function, but a little bit after the beginning?

I'm working on a school project and I have a problem. I have to write code for apothecary where clients can buy medicine. So, I need to make restrictions, which one doesn't go with others and etc. Here is the code:
def prodajLek():
lekovi = Fajl1.UcitavanjeLekova()
lekoviRed = []
brojacZaForPetlju = 1
n = 0
cena = 0
kolicina = []
korpa = []
rednibrojevilekova = []
ukupnacena = 0
print(" Fabricki naziv Genericki naziv Serijski broj Kolicina Cena \n")
for i in lekovi:
x = i.strip().split("|")
lekoviRed.append(x)
if lekoviRed[n][5] == "False":
print(brojacZaForPetlju,"\t {:10} \t {:10} \t\t\t {:3} \t\t\t {:4} \t\t {:5}".format(x[0],x[1],x[2],x[3],x[4]))
brojacZaForPetlju = brojacZaForPetlju + 1
n = n + 1
print("\n\n\n\n")
rednibrleka = input("Izaberite redni broj leka koji zelite da prodate:\n>>\t")
rednibrleka = int(rednibrleka)
rednibrleka = rednibrleka - 1
rednibrojevilekova.append(rednibrleka)
kolicinaZahteva = input("Koju kolicinu zelite da prodate?\n>>\t")
kolicinaZahteva = int(kolicinaZahteva)
if kolicinaZahteva > int(lekoviRed[rednibrleka][3]):
print("Nema toliko na lageru!\n")
Fajl1.LekarMenu()
kolicina.append(kolicinaZahteva)
cena = int(lekoviRed[rednibrleka][4])
korpa.append(cena)
print("Da li zelite da kupite jos lekova?\n1.Da\n2.Ne\n")
nastavakKupovine = input(">>")
if nastavakKupovine == "1":
prodajLek()
elif nastavakKupovine == "2":
Fajl1.LekarMenu()
So, when I get to the nastavakKupovine input, when I press 1, I need to continue shopping and store my row numbers, my price and quantity in arrays rednibrojlekova = [] , korpa = [] and kolicina = []. But I have a problem, because I dont know how to continue this without reseting these arrays to empty.
The standard idiom for what you want to do is a while True loop. Rather than show how to change your (rather long) function, here's a very simple one which hopefully shows the principle in a straightforward way:
def ask():
answers = []
while True:
response = input("What do you have to say? ")
answers.append(response)
check = input("Type 'q' to quit, anything else to repeat: ")
if check == "q":
break
else:
continue
return answers
For this simple function, the else: continue part isn't necessary, because the loop will continue anyway, but I've included it so you can see how to use it.
Here's an example of the function in action:
>>> ask()
What do you have to say? Something
Type 'q' to quit, anything else to repeat:
What do you have to say? Another thing
Type 'q' to quit, anything else to repeat:
What do you have to say? Ok, done
Type 'q' to quit, anything else to repeat: q
['Something', 'Another thing', 'Ok, done']
>>>
You can find out more about while, break and continue by reading the More Control Flow Tools chapter of the official Python tutorial.

Problems transferring information from one part of a function to another

While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:

Python, How to add more choices in an if statement

I have a python program with an if statement. I want to add more choices to the if statement, how do I do it?
def start():
print ("A Wise man once said ...")
o1 = input("\n" +
"[L]ook to the poverty of Africa ... [T]HIS HAS YET TO BE WRITTEN")
if o1 == "L" or "l" or "Africa" or "1":
print ("\n" + "You decide only a radical solution is viable...")
else:
print ("THIS IS NOT WRITTEN YET")
def menu ():
print ("Menu\n")
print ("(1)Start")
print ("(2)Exit\n\n")
choice = (input('>>'))
if choice=="1":
start()
if choice=="2":
quit()
menu()
I am trying to make this option next:
o2 = input (
"\n" + "[D]ecide to take advantage ..., or T[H]IS HAS YET TO BE WRITTEN?"*)
How should I go about adding more options and choices so that I end up with a story?
There are a couple of good ways to do this, but I would make a class (lets call it "option_node") that uses dictionaries. The class would hold the text of the prompt, then a dictionary that mapped the text options to other option_nodes or a special option node that ends the dialog.
class option_node:
def __init__(self, prompt):
self.prompt = prompt
self.options = {}
def add_option(self, option_text, next_node):
self.options[option_text] = next_node
def print_prompt(self):
print(prompt)
def select_input(self):
for each in self.options:
print(each)
while(True)
user_input = input(">>")
if self.options.get(in):
return self.options.get(in)
def main():
nodes = []
nodes.append(option_node("Welcome"))
nodes.append(option_node("Stay Awhile"))
nodes.append(option_node("That's fine, I don't like you much either"))
nodes[0].add_option("Hello friend", nodes[1])
nodes[0].add_option("Hello enemy", nodes[2])
nodes[1].options = None
nodes[2].options = None
current_node = nodes[0]
while current_node.options is not None:
current_node.print_prompt()
current_node = current_node.select_input()
Hope this helps. I can elaborate more if you'd like
Add a new condition using elif (else if):
if ...
elif o1 == "D" or o1 == "H":
# your code here
else ...
By the way, you have a syntax error in your conditional statement. Correct it to this:
if o1 == "L" or o1 == "l" or o1 == "Africa" or o1 == "1":
If it makes it easier, look at it this way:
if (o1 == "L") or (o1 == "l") or (o1 == "Africa") or (o1 == "1"):
You should think about the order of operations in your statements. or has higher precedence than ==; additionally, the meaning of "L" or "l" is not what you think it is.
>>> if "L" or "l":
... print("foo")
...
foo
Curious, no? Try some of this stuff out for yourself at the interpreter.

Categories