def para(value):
if(value==1):
a1=10
b1=11
c1=12
d1=13
elif(value==2):
a1=20
b1=21
c1=22
d1=23
elif(value==3):
a1=30
b1=31
c1=32
d1=33
else:
print("wrong input")
dict_a=dict({'a':a1,'b':b1})
dict_b=dict({'c':c1,'d':d1})
return(dict_a, dict_b)
def main():
global dict_a, dict_b
value=input("enter the choice: \n1. 1st \n2. 2nd \n3. 3rd \n4. 4th")
[dict_a, dict_b]=para(value)
main()
The error that I get is:
dict_a=dict({'a':a,'b':b})
UnboundLocalError: local variable 'a1' referenced before assignment
If your code hits the else block, a1 won't be assigned a value.
You can fix this in one of the following two ways:
Assign a default value in case it doesn't get assigned in the conditional blocks.
a1 = 0
b1 = 0
c1 = 0
d1 = 0
if(value==1):
a1=10
b1=11
c1=12
d1=13
elif(value==2):
a1=20
b1=21
c1=22
d1=23
elif(value==3):
a1=30
b1=31
c1=32
d1=33
else:
print("wrong input")
Or assign the variables in the else block which will achieve basically the same thing
if(value==1):
a1=10
b1=11
c1=12
d1=13
elif(value==2):
a1=20
b1=21
c1=22
d1=23
elif(value==3):
a1=30
b1=31
c1=32
d1=33
else:
a1 = 0
b1 = 0
c1 = 0
d1 = 0
print("wrong input")
If you don't want the user to use these default values, you can always throw an exception in the else that lets the user know they've inputted the wrong values
You should rather initialise the dictionary only in case of valid input
def para(value):
dict_a = dict()
dict_b = dict()
if(value==1):
dict_a={'a':10,'b':11}
dict_b={'c':12,'d':13}
elif(value==2):
dict_a={'a':20,'b':21}
dict_b={'c':22,'d':23}
elif(value==3):
dict_a={'a':30,'b':31}
dict_b={'c':32,'d':33}
else:
print("wrong input")
return(dict_a, dict_b)
Related
I have a list of dictionaries l1:
l1 = [
{'name':'Omer','fname':'ghaffar','sid':1},
{'name':'zoya','fname':'sattar','sid':2}
]
I'm trying to verify whether some content exists in l1. For example, I want to check if the name and sid is the same as the input values (a1 and a2), then it should display "valid user" along with the values.
My code:
a1 = input("name ")
a2 = input("sid ")
for e in l1:
if e['name'] == a1 and e['sid'] == a2:
print("valid user")
break
else:
print("invalid user")
The result I'm getting with the above code is:
name Omer
sid 1
invalid user
invalid user
I expect the result to be:
name Omer
sid 1
valid user
Change your condition to:
if e['name'] == a1 and e['sid'] == int(a2):
This is because by default input reads as string, so when you compare string with an integer, it's always a False.
Alternatively, you could also cast at the time you read from user also:
a2 = int(input("sid "))
Also note that your code keeps on printing 'invalid user' for an invalid entry or a valid entry that comes later in the list. To avoid this, you can add else to for instead of if:
a1 = input("name ")
a2 = input("sid ")
for e in l1:
if e['name'] == a1 and e['sid'] == int(a2):
print("valid user")
break
else:
print("invalid user")
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
I'm writing some python code that works out a person's total pay.
I am able to do this by getting the user to input their pay, however I would like them just to be able to enter their name and then the name is searched in position 0 of a list (Eg. 0,1 0,2 0,2 etc).
I have tried using a tuple but it is not callable and the dictionary and list would not work for me either.
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name:"))
except ValueError:
print("Error")
continue
else:
break
while True:
if name == employeelist[counter,0]:
print(employeelist[counter])
break
valid = 1
elif counter = 3:
print("invalid name")
break
else:
counter = counter + 1
if valid == 1:
break
months = employeelist[counter,1]
pay = employeelist[counter,1]
totalpay = int(months) * int(pay)
Edit:
I do no longer have the code with the dictionary, however I just edited the code from [counter,1] and [0,1] to [counter][1] and is working fine thank you :D
The code below is for your inner loop
employeelist = [["thomas","2","500"], ["jake","1","750"]]
name = ""
while True:
try:
name = input("Name:")
break
except:
print "Error"
position = -1
for i, element in enumerate(employeelist):
if element[0] == name:
position = i
break
if position == -1:
print "Invalid Name"
else:
totalpay = int(employeelist[position][1]) * int(employeelist[position][2])
Your code have multiple bugs. First, valid=1, is set after breaking the loop -meaning valid=1,is never set. You also are checking elif counter = 3 this way, you should rather use two equality signs, like this: elif counter == 3
The error you are getting, that list indices must be integers or slices, not tuple, you are having because you are accessing a multidimensional array the wrong way. Instead of name == employeelist[counter, 0], it should be name == employeelist[counter][0].
Your way of iterating through the array is possible, but its rather simpler using a for loop.
Try this way.
for employees in employeelist:
if name == employees[0]:
print(employee)
valid = 1
break
If it iterated through the hole employeelist, without the if-block running, valid = 1, would never been set.
Working code:
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name: "))
except ValueError:
print("Error")
continue
else:
break
for employees in employeelist:
if name == employees[0]:
print(employees)
valid = 1
break
if valid == 1:
break
months = employeelist[counter][1]
pay = employeelist[counter][2]
totalpay = int(months) * int(pay)
print(totalpay)
i'm trying to allow the user to change the value for a dictionary, my dictionary is d as follows:
d = {'gary:' : 'B','john:': 'C',}
Whenever I type in 'gary:'(gary with a semicolon) for the nameedit input, the why variable will always result in true but regardless, it will read the value as none and never reach the second input for the letter grade(inpu)
nameedit = str(input("Which student do you wish to edit the grade of?"))
why = print(nameedit in d)
if why == None:
print("That student doesn't exist")
else:
inpu = str(input("Enter new letter grade: A,B,C,D,F,"))
d[nameedit] = inpu
print(d)
I also tried some variations on this such as if nameedit == True: and an else with the same problem, the print statement will yield True but it will just continue to the else statement. I also tried a elif nameedit in d:
why = print(nameedit in d)
if nameedit in d == True:
inpu = str(input("Enter new letter grade: A,B,C,D,F,"))
d[nameedit] = inpu
print(d)
else:
print("That student doesn't exist")
, but with no avail. Is it impossible to pick up the value the print statement is reading? My ultimate goal is to simply check if the name is in the dictionary, if it is, continue, if it isn't, stop
python v 3.5
Use:
why = nameedit in d
if why:
inpu = str(input("Enter new letter grade: A,B,C,D,F,"))
d[nameedit] = inpu
print(d)
else:
print('Does not exists')
print() just puts output to the screen; it does not return what it is printing. If you want to assign why to the result of nameedit in d and print it; do it on separate lines:
why = nameedit in d
print(why)
Also, if ... is seeing if ... is True. Using if ... == True is seeing if ... == True == True. That is redundant. Just do this:
why = nameedit in d
print(why)
if why:
inpu = input("Enter new letter grade: A,B,C,D,F,")
d[nameedit] = inpu
print(d)
else:
print("That student doesn't exist")
I also removed your conversion of input(...) to a string. It already returns a string, so the conversion is redundant.
nameedit in d returns True or False, never None. And wrapping in print (which always returns None) is just nonsensical.
Remove the print wrapping, and change the test to if not why: or just move the test into the condition itself:
nameedit = input("Which student do you wish to edit the grade of?")
if nameedit not in d:
print("That student doesn't exist")
else:
d[nameedit] = input("Enter new letter grade: A,B,C,D,F,")
print(d)
I removed unnecessary str wrapping (input already returns str in Py3), and unnecessary intermediate locals.
Use just like:
if why in d:
or
if why not in d:
You don't need use two strings for this. Also, you can get value with get:
d = {'gary:' : 'B','john:': 'C',}
name = str(input("Which student do you wish to edit the grade of?\n"))
value = d.get(name, None)
if not value:
print("That student doesn't exist: {0}: [1}".format(name, value))
else:
value = str(input("Enter new letter grade: A,B,C,D,F \n"))
d[name] = value.upper()
print(d)
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"]: