How would I go about interpreting this python code? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
so I was just looking over a few problems where I had to interpret a piece of code, and I stumbled upon this one :
a = 10
b = 4
c = 2
d = 3
if ((c+2<d)) or ((c*d)==(a-b)):
if (True and not(True)) or True:
print ("X")
else:
print("Y")
print("Z")
I understand that the first part of the statement will evaluate to False, while the second part will evaluate to True. The problem I am having is about interpreting the if statement that follows. What is the "True and False" or "True" referring to, the previous statement? Thanks

First, you need a closing parenthesis after that last True.
Second, that second if statement will always evaluate to True, because of the or True part. It's not referring to anything. It's just using the Python built-in constant True.
Here's a corrected version of that code. It runs, but it doesn't accomplish anything significant. It will always print "X" and "Z".
a = 10
b = 4
c = 2
d = 3
if ((c+2<d)) or ((c*d)==(a-b)):
if (True and not(True) or True):
print ("X")
else:
print("Y")
print("Z")

Related

My if statement is not working. The condition is not being evaluated. I have no idea why [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
if len(enterlist) == 0:
print('no list')
elif 5.5<=9.32 or 9.6:
print('sell')
closelist.append([driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[1]/div[3]/div[2]/div[1]/div/table/tbody/tr[1]/td[2]').text])
else:
print('no list no sell')
sell
I have the above code. It prints sell when it should print the next line. I am building the script in sublime with python, but do not know why it will not work.
elif 5.5<=9.32 or 9.6:
is evaluated as
if either of these is true:
5.5 <= 9.32
9.6 is truthy
and nonzero numbers (such as 9.6) always are truthy.
You might be looking for
elif 5.5 <= 9.32 or 5.5 <= 9.6:
It will always print sell if len(enterlist) == 0 is false
Here is why
the second if condition is always true because 5.5<=9.32 is always true. The problem is that you wrote a comparison between numbers (not variables) and if the universe is not going to change its' laws then 9.32 is always bigger than 5.5.

Why is python if condition not working for values of "False"? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In the following code, is_number is False for the value "foo", but this still prints is a number for that string. Why? And how do I fix it?
def string_is_number(a_string):
pattern = re.compile(r'[0-9]+')
if pattern.search(a_string):
return("True")
else:
return("False")
for value in 42, 0.5, "foo":
the_string = str(value)
is_number = string_is_number(the_string)
print(the_string, is_number)
if is_number:
print(the_string, "is a number")
Output:
42 True
42 is a number
0.5 True
0.5 is a number
foo False
foo is a number
Return a bool, not a str:
if pattern.search(a_string):
return True
else:
return False
Any non-empty string in Python is considered true (or "truthy"), including "False":
>>> bool("False")
True
Then of course, the regex for your number detection is a bit off:
re.match("^\d+([.,]\d+)?$", a_string)
would be a tighter test.
You're trying to return "True" and "False" as string. You need to return them as boolean like this:
def string_is_number(a_string):
pattern = re.compile(r'[0-9]+')
return pattern.search(a_string) # Returns True or False
Your function failed because you returned non-empty strings, which are alwaysTrue. A more subtle problem is that you call anything that has at least one digit a number. So "I am not the number 1" is a number. A nice way to check if something is a "number" is to try to convert it. In your case, it looks like you are dealing with integers and floats which both can be converted to float. Because commas are not allowed in string literals, they need to be factored out, but your function could be
def string_is_number(a_string):
try:
float(a_string.strip(','))
return True
except:
return False

If a = str(integer), do print(len(a)) and return len(a) work the same in a function? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am new to programming and have just briefly learned functions in python. I do not understand why print(len(str)) don't work the same as return len(str) in a function.
I have tried both print and return for the last statement of the function and am confused about my understanding of len(). I need some guidance, thank you! Perhaps someone can guide me as to how I can further improve my foundation as I am still pretty new to programming. Thank you!!
def numDigits(n):
#return number of digits in an integer
str_digits = str(n)
print(len(str_digits))
numDigits(833)
If I change the
print to return len(str_digits) and
numDigits(833) to print(numDigits(833)),
I get my expected answer.
What i expected:
3
Actual result:
3
None
1
2
4
3
In the first case numDigits doesn't return a value from the function, and you only print it inside the function
def numDigits(n):
#return number of digits in an integer
str_digits = str(n)
print(len(str_digits))
print(numDigits(833))
The output here is
3
None
The 3 comes from print and None comes from the function, and when you print it, it prints None
If you want to return, you need a return statement like return len(str_digits) at the end of the function like so
def numDigits(n):
#return number of digits in an integer
str_digits = str(n)
print(len(str_digits))
#Return statement
return len(str_digits)
print(numDigits(833))
The output will now be
3
3
Now the first 3 comes from print, and the second 3 comes when you print what numDigits return, which is 3

Pandas if/then/else logic [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a dataframe which looks like this,
df=pd.DataFrame([2,4,6,2],columns=['x'])
df['y']=[3,2,1,2]
df['x_test']=['x_larger','x_larger','x_smaller','x_equal']
I am trying to do a if/then/else, similar to this idiom and cookbook. I am able to get one if statement correct but I am not sure how to test for equal.
df['valid']=False
df['invalid']=True
df.ix[(df.x_test=="x_larger") & (df.x>df.y),['valid','invalid']]=[True,False]
This works partially. But I would also like to test for x_equal in this line. Is that possible?
The desired output should be
x y x_test valid invalid
0 2 3 x_larger False True
1 4 2 x_larger True False
2 6 1 x_smaller False True
3 2 2 x_equal True False

what is invalid about this syntax? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm writing code to simulate x number of craps games and I have some code written that may or may not work. I'm not sure yet but I can't check because when I finish editing the module a syntax error notifies me that my code doesn't make sense. The thing is though I feel like I've used this syntax hundreds of times before. The error message reads
File "<ipython-input-5-9e8dfc269e5b>", line 7
if roll=7 or roll=11:
^
SyntaxError: invalid syntax
It doesn't like the equals sign? I don't understand why python can't read this. What is wrong?
here is all of the code for the simulation if it helps
def crap(x):
from random import randint
win=0
loss=0
for i in range(x):
roll=rand(2,12)
if roll = 7 or roll = 11:
win=win+1
elif roll = 2 or roll = 3 or roll = 12:
loss=loss+1
elif roll=4 or roll=5 or roll=6 or roll=8 or roll=9 or roll=10:
rolln=randint(2,12)
while rolln =! 7 or rolln =! roll:
rolln=randint(2,12)
if rolln = 7:
loss=loss+1
elif rolln = roll:
win=win+1
= is an assignement operator, you cannot use that in if-elif conditions. Use == for equality check.
if roll == 7 or roll == 11:
Secondly you can also reduce expressions like:
elif roll==4 or roll==5 or roll==6 or roll==8 or roll==9 or roll==10:
to:
elif roll in (4, 5, 6, 8, 9 ,10):
= is used to assign values to variables. Since you're trying to test for equality, you should be using ==, e.g.
if roll == 7

Categories

Resources