I have been stuck on this problem for about 1 hour : I want my command while to access in the next block. Case is a class: cases is the object. I made a definition that say on some condition : my object case become NoneType. There is the condition if element_voisin == case to be sure that the element is still a case and not a NoneType. If it's still a case I want to access case.ajouter une mine voisine() but my program won't go in. If you need more information tell me! I relly want this to work please.
for element in coordonnees_voisine:
element_voisin = self.obtenir_case(element[0], element[1])
if element_voisin == case:
case.ajouter_une_mine_voisine()
else:
None
Replace
if element_voisin == case:
with
if element_voisin is case:
When comparing objects, you want to use is, not ==.
Related
I want to verify if Items from a List are contained in what i fetch by using string.read().
How do I do this:
if string.find(lisst):
do_whatever()
elif string.find(lisst2):
do_something_else()
Example is pretty basic, but that's all I want to do. I keep getting invalid syntax error. :(
def verify(text):
lisst = ['awesome','failed','trolling']
lisst2 = ['boring','bad']
s = requests.get(text)
t = s.read()
if t.find(lisst):
print("Someone was awesome, failing or trolling!")
elif t.find(lisst2)
print("Something retarded happened")
error is thrown at elif t.find(lisst2), so I need a workaround.
elif any(n in t for n in lisst2):
^
SyntaxError: invalid syntax
Thank you in advance!
If I understood correctly, you want to do something in an if block if a string contains any the elements of a list.
if any(str in aVeryLongStringData for str in myList):
doStuff()
If you want to check if your data contains all of the elements on your list, you can just change "any" to "all"
if all(str in aVeryLongStringData for str in myList):
doStuff()
class Queue2Stacks(object):
def __init__(self):
# Two Stacks
self.instack = []
self.outstack = []
def enqueue(self,element):
# Add an enqueue with the "IN" stack
self.instack.append(element)
def dequeue(self):
if not self.outstack:
while self.instack:
# Add the elements to the outstack to reverse the order when called
self.outstack.append(self.instack.pop())
return self.outstack.pop()
Can someone please help me understand this question? I don't really understand how does the if not self.outstack work here. I thought the self.outstack start with an empty list, why would it triggers this statement? I also don't understand the while self.instack here, self.instack is a list that we appended from enqueue function right? What would break this while loop?
The if condition you refer to:
if not self.outstack:
...means "if outstack is empty". This is necessary, because the intended action is to pop a value from that stack (see return statement). Now if there is nothing there, we cannot just raise an exception "sorry, nothing there any more", as there might still be values in the other stack : instack. So in that case we need to return a value from that stack: the value we need to return is at the bottom of instack. So we will need to pop all values from that stack, and append them to outstack, which effectively will put them in reverse order: the value that was at the bottom of instack, will end up at the top of outstack, and that is exactly what we want, because we will pop that element as return value.
The while condition is saying: "while there are still values in instack". This is needed, because we want all values to be popped from that stack.
Better understanding of the loop structures may help with this piece of code.
Here's a resource: http://openbookproject.net/thinkcs/python/english3e/conditionals.html
if not (apples >= 5):
print("You have a few apples only.")
is similar to that of:
if (apples <= 5):
print("You have a few apples only.")
the logic gate is a little more deeper with the understanding of "not" as in not a "!" operator. Hope that helps with the understanding of your code.
I am searching elements in my list(one by one) by inputing into searchbar of a website and get apple products name that appeared in search result and printed. However I am getting following exception
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
I know its because of changing of element very fast so I need to add wait like
wait(driver, 10).until(EC.visibility_of_element_located((By.ID, "submitbutton")))
or explictly
Q1. But I don't understand where should I add it? Here is my code. Please help!
Q2. I want to go to all the next pages using but that's not working.
driver.find_element_by_xpath( '//div[#class="no-hover"]/a' ).click()
Earlier exception was raised on submitton button and now at if statement.
That's not what implicit wait is for. Since the page change regularly you can't be sure when the current object inside the variable is still valid.
My suggestion is to run the above code in loop using try except. Something like the following:
for element in mylist:
ok = False
while True:
try:
do_something_useful_while_the_page_can_change(element)
except StaleElementReferenceException:
# retry
continue
else:
# go to next element
break
Where:
def do_something_useful_while_the_page_can_change(element):
searchElement = driver.find_element_by_id("searchbar")
searchElement.send_keys(element)
driver.find_element_by_id("searchbutton").click()
items_count = 0
items = driver.find_elements_by_class_name( 'searchresult' )
for i, item in enumerate( items ):
if 'apple' in item.text:
print ('item.text')
items_count += len( items )
I think what you had was doing too much and can be simplified. You basically need to loop through a list of search terms, myList. Inside that loop you send the search term to the searchbox and click search. Still inside that loop you want to grab all the elements off the page that consist of search results, class='search-result-product-url' but also the text of the element contains 'apple'. The XPath locator I provided should do both so that the collection that is returned all are ones you want to print... so print each. End loop... back to next search term.
for element in mylist:
driver.find_element_by_id("search-input").send_keys(element)
driver.find_element_by_id("button-search").click()
# may need a wait here?
for item in driver.find_elements_by_xpath( "//a[#class='search-result-product-url'][contains(., 'apple')]" ):
print item.text
I am writing a code for the wind chill index for an assignment for college.
The prof wants us to prevent the code from crashing upon user input of blank or letters, without using Try/Except Blocks. (He refers to string methods only).
Instead of crashing it should out put an error message eg. ("invalid input, digits only")
I tried utilizing the string.isdigit and string.isnumeric, but it won't accept the negative degrees as integers.
Any suggestions? (code below)
Would another "if" statement work?
Replace the punctuation:
if temperature.replace('-','').replace('.','').isnumeric():
Use an infinite loop and check that everything seems right.
Whenever there's an error, use the continue statement. And when all checks and conversions are done, use the break statement.
import re
import sys
while True:
print("Temperature")
s = sys.stdin.readline().rstrip('\n')
if re.match("^-?[0-9]+(\\.[0-9]+)?$", s) is None:
print("Doesn't look like a number")
continue
if '.' in s:
print("Number will be truncated to integer.")
temp = int(float(s))
if not (-50 <= temp <= 5):
print("Out of range")
continue
break
I have some code getting data and then selecting it in order. For this I use simple maps that I may later access with ease (I thought..).
I use the following code within a loop to insert maps to another map named "companies":
def x = [:]
x.put(it.category[i], it.amount[i])
companies.put(it.company, x)
And I can surely write the result out: [Microsoft:[Food:1], Apple:[Food:1]]
But then, when I am about to get the food value of each company it always is null. This is the code I use to get the values:
def val = companies.get(it.company).get(key.toString())
def val = companies[it.company][key] // doesn't make a difference
Val is always null. Can someone help and / or explain why I have this error. What am I doing wrong? I mean, I can clearly see the 1 when I print it out..
My guess is that it.category[i] and key are completely different types...
One thing you could try is:
x.put(it.category[i].toString(), it.amount[i])
and then
def val = companies[it.company][key.toString()] // doesn't make a difference
The solution was simple to make the category as a string:
x.put(it.category[i].toString(), it.amount[i])
And after that little fix it all works as expected.