i have this on my script
for x in test:
extra_data_list = ast.literal_eval(x['extra_data'][3])
if extra_data_list.has_key('first_name') == True:
if extra_data_list['email_address'] == current_user['email']:
linked.append('Linkedin')
elif is_google == current_user['email']:
linked.append('Google Plus')
but when i pass linked to my template, i got one result, just 'Linkedin',
even second condition is also true, can you tell me to solve this ?
You are missing a tab before the elif. It referers to the external if
Because the first if condition is true your code cannot execute the elif!
You can just use a normal if statement:
for x in test:
extra_data_list = ast.literal_eval(x['extra_data'][3])
if extra_data_list.has_key('first_name') == True:
if extra_data_list['email_address'] == current_user['email']:
linked.append('Linkedin')
if is_google == current_user['email']:
linked.append('Google Plus')
Related
Was trying to run code ended up with return outside
For row in rows:
If list1.index(0)== list2.index(0):
return new-list.append(row[0])
Elif list1.index(1)== list2.index(1):
return new-list.append(row[1])
Elif list1.index(2)== list2.index(2):
return new-list.append(row[2])
Elif list1.index(3)== list2.index(3):
return new-list.append(row[3])
getting return outside function error
The keyword return can only be used inside a function definition.
def helloworld():
return 'Hello World!'
print(helloworld()) # Hello World!
What you want might be something like this:
for row in rows:
if list1.index(0) == list2.index(0):
newList.append(row[0])
elif list1.index(1) == list2.index(1):
newList.append(row[1])
elif list1.index(2) == list2.index(2):
newList.append(row[2])
elif list1.index(3) == list2.index(3):
newList.append(row[3])
Also, keywords like if, elif can't be capitalized (Only True, False, and None are capitalized). And an indent is needed after every colon. And python variables can't contain -.
Python does not use braces to create code blocks like C++ or Java, instead it uses tabs/spaces to create what is known as code blocks if code is not indented then that part is not inside a code block. For example
x = 10
if x == 10:
print("X is 10") # This is inside if statement
print("Not if") # but this is not inside if statement so it will execute regardless of if statement.
So you need to indent your return statements to fix those errors. Also F and E of for and elif should be in small letters and variables cannot contain -(dash) in their names.
for row in rows:
if list1.index(0) == list2.index(0):
return newList.append(row[0])
elif list1.index(1) == list2.index(1):
return newList.append(row[1])
elif list1.index(2) == list2.index(2):
return newList.append(row[2])
elif list1.index(3) == list2.index(3):
return newList.append(row[3])
i wanted to make my code in a while loop and when the user inputs "end", the program closes. I did it like this
T = True
while T:
startInput = input()
# insert code
while True:
if startInput == "end" or startInput == "End":
T = False
break
The problem is that it doesn't work.
Try this:
T = True
while T:
startInput = input()
# insert code
if startInput == "end" or startInput == "End":
T = False
break
The problem was you were running the first loop and it never runs the second one so it can never exucute that code and break out of the loop.
if you are using python 3.8 above you can use like this :
T = True
while (startInput := input()) not in ["end","END"]:
# insert code
T=False
Is this the best way to execute the following code or is there a way to do it with an else statement after the for loop?
moved = False
for action in actions:
if action.type == KEY:
moved = True
if action.key == UP:
move_forward()
update_all()
if not moved:
update_all()
For that specific piece of code you could reduce to:
for action in actions:
if action.type == KEY and action.key == UP:
move_forward()
update_all()
Since you're always updating, even if your action is not of type KEY.
If there's any reason to update all, do it at the end after the for each loop
moved = False
for action in actions:
if (action.type == KEY and action.key == UP):
moved = True
move_forward()
update_all()
I am trying to exclude and remove some dictionaries from a list. I have searched for awhile through the site and haven't found anything specific to this. The list of dictionaries was created from a txt file located: http://s000.tinyupload.com/?file_id=48953557772434487729
I'm trying to sort out and exclude the things I don't need. I thought my syntax was right, but apparently not.
I only included necessary code to cut down on the clutter. I am having problems at the action_genre point and excluding and deleting the dictionaries there. When prompted enter "s" and then "a" to access those two menus.
def load_movies():
global movies_list
movies_list= []
file_ref = open("movies.txt", 'r')
line = file_ref.readline()
for line in file_ref:
line = line.strip()
current = {}
if line == '':
break
movie_data = line.split("\t")
current["title"] = movie_data[0]
current["year"] = movie_data[1]
current["length"] = movie_data[2]
current["rating"] = movie_data[3]
current["action"] = int(movie_data[4][0]) == 1
current["animation"] = int(movie_data[4][1]) == 1
current["comedy"] = int(movie_data[4][2]) == 1
current["drama"] = int(movie_data[4][3]) == 1
current["documentary"] = int(movie_data[4][4]) == 1
current["romance"] = int(movie_data[4][5]) == 1
movies_list.append(current)
del current
file_ref.close()
def menu():
movie_selector =("Movie Selector - Please enter an option below:\nL - List all movies\nY - List all movies by year\n"
"T - Search by title\nS - Search by genre, rating, and maximum length\nQ - Quit the program\nOption:")
movie_selector_input = input(movie_selector).upper()
if movie_selector_input == "L":
list_movies()
if movie_selector_input == "Y":
list_by_year()
if movie_selector_input == "T":
search_by_title()
if movie_selector_input == "S":
search()
if movie_selector_input == "Q":
print("Thanks for using my program! Goodbye.")
exit()
else:
print("Invalid input")
print("Please try again")
print()
return menu()
def search():
genre_input = input("Please make a selection from the following genres.\n(Action(A), Animation(N), Comedy(C), "
"Drama(D), Documentary(O), or Romance(R)):").lower()
if genre_input == 'a':
action_genre()
elif genre_input == 'n':
animation_genre()
elif genre_input == 'c':
comedy_genre()
elif genre_input == 'd:':
drama_genre()
elif genre_input == 'o':
documentary_genre()
elif genre_input == 'r':
romance_genre()
else:
print("Invalid genre")
print()
menu()
#this is where I can't get the syntax to work
def action_genre():
for current in movies_list:
if current["action"] == "False":
del current
break
for i in movies_list:#using this to test output
print(i)
load_movies()
menu()
I'm narrowing down the list by excluding things that don't fit the parameters. In the action_genre function, I'm trying to delete all the dictionaries that don't equal current["action"] == True. I've tried using "True" and "False" as strings, as well as the bools True and False for comparisons, and still an error. Unfortunately, I have to use the Boolean logic per my professors directions.
His e.g.:
Professor's example. Apparently since I'm new I can't embed images. :/
I'm in programming 101, so thank you for your patience as I learn this, and thank you in advance for the help.
Okay, so the issue runs a bit deeper than the if condition being incorrect. In get_action() you effictively do not modify the actual movies_list object, but rather the local variable current, as proven by this simple test:
def action_genre():
for current in movies_list:
print(current)
if not current["action"]:
del current
print(current)
The second print(current) will result in an UnboundLocalError saying that current does not exist anymore, while in movies_list the entry it just deleted continues to exist. But in general, using del in loops indeed causes problems because that's how iterables and del itself behave. I encourage you to read up more on this on other sources or SO if you wish, like here.
Using the answer from the provided link above, we can use list comprehension to filter the movies:
def action_genre():
filtered_movies_list = [movie for movie in movies_list if movie['action']]
print(filtered_movies_list)
This creates a new list (so it does not modify movies_list), which includes all dictionary entries where item['action'] == True.
I hope this helps.
You are trying to compare a string with a boolean. Look at the following:
a= 1==1
print a
True
print type(a)
<class 'bool'> # a is a boolean
b='True' #assign string 'True' to b
print type(b)
<class 'str'>
print a==b #compare boolean True to string 'True'
False
b = True # assign boolean True to b
print a==b #compare boolean True to boolean True
True
so you need if current["action"] == False instead of if current["action"] == "False"
Following is what I am trying, not sure where I'm messing up. I have the expected output at the bottom. Can anyone provide input on what is wrong here?
Create a lists in a dictionary for each master change and its dependent change
Repeat step #1 until the depchange status is not NEW
My code:
def depchange(change):
depchange_status=''
if change == "23456":
depchange=33456
depchange_status == 'NEW'
if change == "33456":
depchange=""
depchange_status == 'COMPLETED'
return (depchange,depchange_status)
def main ():
master_change="23456"
dep={}
while True:
dep_change,depchange_status=depchange(master_change)
master_change = dep_change
dep[master_change]=dep_change
if depchange_status != 'NEW':
break
print dep
if __name__ == '__main__':
main()
'''
EXPECTED OUTPUT:-
dep = {
'23456': ['33456'],
'33456': [],
}
'''
Uh, in your depchange() function, do you actually mean to compare the depchange_status, or do you mean to change them? You had '==' there.
There's that, and in that same function, depchange is switched from a string to an int. I assume you wanted it to stay a string.
def depchange(change):
depchange_status=''
if change == "23456":
depchange="33456"
depchange_status = 'NEW'
if change == "33456":
depchange=""
depchange_status = 'COMPLETED'
return (depchange,depchange_status)
def main ():
master_change="23456"
dep={}
while True:
dep_change,depchange_status=depchange(master_change)
dep[master_change]=[dep_change]
master_change = dep_change
if depchange_status != 'NEW':
break
print dep
if __name__ == '__main__':
main()
Swap the order of these two lines. You want to use the old value of master_change in the assignment to dep.
master_change = dep_change
dep[master_change]=dep_change
Also you have == instead of = in a couple of assignments.
depchange_status == 'NEW'
depchange_status == 'COMPLETED'