Try Statement Within for Loop not working python - python

I have the script below, what I am finding that if my Try statement is satisfied, the whole iteration of the first loop will end and it will just go into the next loop iteration.
What I want to happen is it the, if statement, is satisfied, it then just back to the elif within the for loop that it sits within.
So essentially I want to go
For loop.
Then try if something works (I know some wont)
Then go back into a for loop (and all the subsequent loops will still work.
Ideally I would structure this as: for loop- try statement- for loop, but essentially I am asking the same question as when that happens to, the loop also breaks out.
Thaankyou, Sam
# LOOP OVER THE DICTIONARIES (CSV LINE DATA) AND PULL UP THE PARAMETER KEY TO MATCH
tester = []
updatefamilyname = IN[6]
typename_input01_value = IN[7]
typename_input02_value = IN[8]
for datarow_dict in Data_DictionaryList:
# Get matching value from data row dictionary
Matching_Value = str(datarow_dict[parameter_key_tomatch])
#test.append(parameter_key_tomatch)
#test.append(Matching_Value)
try:
Get_Matching_Value_LongIndex = Base_MatchingWalls_Dict[Matching_Value]
Split_Index = Get_Matching_Value_LongIndex.split(indexplacesplit)[1]
MatchedWall = Base_MatchingWalls[int(Split_Index)]
#test.append(MatchedWall)
#test.append("here2")
for para_key, para_value in datarow_dict.items():
#ResultOutput.append(para_key)
#ResultOutput.append(typename_input01_value)
#test.append(para_key)
#test.append(para_value)
# We then say if the paramter key is the same as the matching key, open the following
if para_key == parameter_key_tomatch:
#test.append("inside")
ResultOutput.append(para_key + " equal to " + para_value)
# Set New Family Type Name Value
#if para_key == typename_input01_key:
#typename_input01_value = para_value
#tester.append("inside link")
#elif para_key == typename_input02_key:
#typename_input02_value = para_value
#else:
#print ("go")
elif para_key != parameter_key_tomatch:
ResultOutput.append(para_key)
print ("not here")
#ResultOutput.append(para_key)
#TestParameter_ = testparavalue(MatchedWall, para_key, para_value)
#else:
#pass
# We then say, if its not the same, this is when we want to do some things, could be where we change the family name if we change the name of the name and number
else:
print ("ouside exception")
#ResultOutput.append("else why")
if updatefamilyname == "Yes":
ResultOutput.append("update name accepted")
print ("yes")
# THIS IS WHERE WE COULD PASS IN THE OTHER ONE TO MATCH TO FORM THE CHANGE IN FAMILY TYPE NAME
#typename_input01_value
#typename_input01_value
# This is where we bring in
# Anything where matching para does not have a corresponding wall type
except:
print ("here")
ResultOutput.append(Matching_Value)

Related

Python conditions statement logic

Im beginner on selenium & python and i trying to understand the logic of condition statement but it doesn't take the second condition into account :
What i try to do :
PS : I put " ? " because I'm not sure if is that
My code :
users = []
elems = browser.find_elements_by_xpath("//body//div[#class='PZuss']//a[#class='FPmhX notranslate _0imsa ']")
url = "https://www.instagram.com/"
# Generate a list where to put the followers name
for i in range(100):
val = elems[i].get_attribute('innerHTML')
users.append(url+val)
print(users)
for follower in users:
#Iterate into the list
browser.get(follower)
sleep(2)
followButton = browser.find_element_by_css_selector('button')
print(follower_count)
print(following_count)
if int(follower_count) == 0:
follower_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/span/span').text.replace(",",""))
following_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[3]/span/span').text.replace(",",""))
continue #don't know if i need this word ?
if browser.find_elements_by_xpath("//img[contains(#src,'YW5vbnltb3VzX3Byb2ZpbGVfcGlj')]"):
print("profil haven't profil pic")
continue
else:
print("eligible")
followButton.click()
My understanding of what you're trying to achieve is this.
if int(follower_count) == 0:
follower_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/span/span').text.replace(",",""))
following_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[3]/span/span').text.replace(",",""))
if browser.find_elements_by_xpath("//img[contains(#src,'YW5vbnltb3VzX3Byb2ZpbGVfcGlj')]"):
print("profil haven't profil pic")
else:
print("eligible")
followButton.click()
You do not need the continue for the code to work
The second if statement is within the first if statement, with the else a part of the second if statement. The indented block of code is within the first if statement and is only run if follower_count is equal to 0, otherwise it will skip the if statement and go to the next value in the for loop.
You should use logical operators here. Assume you have your conditions check and validation logic in three dedicated methods:
def check_condition_one(*args):
pass # You evaluate your conditions here
def check_condition_two(*args):
pass # You evaluate your conditions here
def validate(*args):
pass # you implement your validation logic here
Then you do like this:
for user in users:
if check_condition_one(user) and check_condition_two(user):
validate(user)
So you validate a user when both the conditions have evaluated to True. Otherwise nothing happens.
P.S. - continue just skips the rest of the code till the end of current loop iteration and proceeds to the next one if any.

Querying a dictionary user input infinite loop python

Newbie trying to learn some basic python, I've imported a json file containing a dictionary of terms. I'm trying to create a script that lets users look up definitions from my dictionary. I'm getting stuck on lines 14-15. I don't want the script to stop after just two attempts. I can work out how to set it to a max # of attempts but not how to make it infinite allowing unlimited tries. Each new query should be followed by a close match result using the get_close_matches method in difflib if the attempt is not an exact match, with the user prompted to accept or reject the closest match. My script, however, will stop after two attempts and if the 2nd query is not an exact match error out instead of presenting the 3 (the default for the method) closest matches to the word. Any ideas?
import json
from difflib import get_close_matches
data=json.load(open('data.json'))
def translate(w):
w=w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w,data.keys()))>0:
yn=input("Did you mean %s? Enter Y or N: " % get_close_matches(w,data.keys())[0]).upper()
while yn =="N":
i=input("Enter Word: ")
return data[get_close_matches(i,data.keys())]
else:
return data[get_close_matches(w,data.keys())[0]]
word=input("Enter Word: ")
print(translate(word))
Your current approach isn't working because of the return statement inside the while yn == "N" loop. That return immediately takes you out of the function, regardless of whether the loop has completed, so there's no way for this loop to run more than once.
You could edit the loop to prevent it from always returning, but it's easier to move the loop outside the function. That way you don't have to worry about whether you're working with the initial input or a subsequent input, and you can cut down on duplicate code:
def translate():
w = input("Enter Word: ").lower()
if w in data:
return data[w]
close_matches = get_close_matches(w, data.keys()) # This only runs if w was NOT in data
if len(close_matches) > 0:
yn = input("Did you mean %s? Enter Y or N: " % close_matches[0]).upper()
if yn == 'Y':
return data[close_matches[0]]
return None # This is optional. Reaching the end of a function will return None by default
translated_word = None # Force at least one iteration of the loop
while translated_word is None: # Keep going until there's a match or the user types "Y"
translated_word = translate()
print(translated_word) # This will only run once the loop condition is False

Pulling from a list

My question is about getting a user to pull and item from a list. If the item from the list isn't pulled from the list I want to tell the user that he is incorrect. So my code looks like this:
Body_Type = ['Large', 'Medium', 'Small']
print('Create a Character-')
print('Body Type Choices: ' + str(Body_Type))
bt = input('Enter your Body Type: ')
while bt != Body_Type:
if bt == Body_Type[0:]:
print('Your Body Type is: ' + bt)
else:
print('Invalid Body Type')
What I'm trying to do is make my user create a character. This is just the first part of my first simple project. I want to have him pull from one of the items on the list, being "Large, Medium, Small" respectively. I want it to repeat until the user chooses one of the three. I tried to use or but it seems to feel unorganized and I'd have to break up the list and assign each individual variable.
Thanks in advance!
Several errors here like comparing a string to a list, or random slicing hoping that it would work. And the fact that your input statement is before the loop creates an infinite loop because you're comparing 2 variables of a different type again and again (bt != Body_Type is always True regardless of the content of bt since left hand is a string, right hand is a list).
But it shouldn't be so complex to write some working code.
I would create an infinite loop and break only if choice is in the list:
while True:
bt = input('Enter your Body Type: ')
if bt in Body_Type:
print('Your Body Type is: ' + bt)
break
else:
print('Invalid Body Type')
simpler and clearer (and repeats input if fails). The infinite loop (with an always true condition) allows to avoid double input call & test. Just loop, input the string, and break from the loop if matches.
The key statement you were looking for was bt in Body_Type which tests if the string is within the list.

Variable not defined in while loop in python?

I am trying to write a simple program in python to read command line arguments and print a final word based on the arguments. If there is any argument of the form "-f=" then the will go to the front of the final printed word. Similarly for "-e=" the text goes to the back and if there is -caps as an argument then the final printed word will all be uppercase. I do a while loop to scan through the arguments and check for these flags. The full code is:
import sys
i=1
while i<len(sys.argv):
frnt_wrd = None
lst_wrd = None
arg_1 = str(sys.argv[i])
if arg_1.startswith('-f='):
front = arg_1.split('=')
frnt_wrd = front[1]
elif arg_1.startswith('-e='):
last = arg_1.split('=')
lst_wrd = last[1]
if arg_1.startswith('-caps'):
caps = True
else:
word = arg_1
i+=1
print (front)
print (frnt_wrd)
I had a couple of if statements later on to print out the word based on whether frnt_wrd and lst_wrd were not equal to None (i.e. a value had been assigned to them) but nothing was printing out. To check the problem I did:
print (front)
print (frnt_wrd)
and the output actually gives me front as the desired array (when there is an argument of the form "-f=" but returns frnt_wrd as None even though I defined:
frnt_wrd = front[1]
When I type exactly this line outside of the while loop it actually works but why is it not defining the frnt_wrd inside the while loop?
Edit: The full code giving me frnt_wrd as None is above. What else do you need?
I would like to learn how to do it with while and without argparse. I need to understand why I am defining a variable and it is not defining.
Traceback:
enter image description here
The problem is that you reset frnt_word and lst_word to None each time through the loop, so you're overwriting the value that was set by a previous argument. You should just initialize them before the loop.
frnt_word = None
lst_word = None
caps = False
word = None
for arg in sys.argv[1:]:
optarr = arg.split("=")
if optarr[0] == "-f":
frnt_word = optarr[1]
elif optarr[0] == "-e":
lst_word = optarr[1]
elif optarr[0] == "-caps":
caps = True
else:
word = arg

Printing multiple database entries with the same name

sorry, i'm not too sure how to phrase this question.
I am making a database of herbs to be used in cooking etc. and using a python scrip to search the database.
Basically i have multiple entries in the database that have the same name or similar (such as Siberian ginseng and panax ginseng). I would like to print out all of the entries that have the name in them (eg. ginseng), but am not sure how.
this is my code so far:
while True:
herb=input("Herb: ")
database=open("db.txt")
for line in database:
record = line.split('|')
if record[0] == herb:
found = True
break
else:
found = False
continue
if found == False:
print("No herbs in database.")
print('')
else:
print(record[0])
print(record[1])
print(record[2])
print(record[3])
print('')
The output only displays the first entry that has the herb (ginseng) in it, however i want all entries that have the name anywhere in it to be displayed.
Apologies if this question has already been answered or i haven't phrased it right.
It looks like your iterating over your records and when you find an entry that matches you break out of the loop and print it right away.
Something you might want to do is to make a printHerbs function which takes the record array and prints it when its found and not break the loop.
Also only display not found if they reach the end of the loop an nothing was found. It might look something like this:
herb=input("Herb: ")
database=open("db.txt")
def printHerbs(record):
print(record[0])
print(record[1])
print(record[2])
print(record[3])
print('')
found = False;
for line in database:
record = line.split('|')
if herb.lower() in record[0].lower():
found = True
printHerbs(record)
if found == False:
print("Herb not found in database")
Also if you are trying to match if a string is a substring of another string you can use:
if "Ginsing" in "Ginsing Tea":
print("Found")
The .lower() method will make sure both strings are lowercase when they are being compared.

Categories

Resources