I'm making a double variable if statement and it keeps returning an error. I don't know what's wrong:
variable = float(0)
for index in range(10):
variable = variable + float(2)
if x <= float(variable/3) and > float(variable-2.0/3):
# do something
else:
pass
or something like that. This is the basic structure. Why does it keep highlighting the > in red whenever I try to run it?
Python supports regular inequalities as well, so you could just write this:
if variable - 2.0 / 3 < x <= variable / 3:
# ...
You want to do something like
if ((x <= float(variable/3)) and (x > float(variable-2.0/3))):
# do something
else:
pass
In other words, each side of the and must be a boolean expression on its own. I'm not sure whether you need all the parenthesis.
It seems like you're missing a variable or constant before the second condition in the if-block. That might be one reason you're getting an error.
This code works fine:
index=0
x=0
variable = float(0)
for index in range(10):
variable=variable + float(2)
if x <= float(variable/3) and x> float(variable-2.0/3):
print 'Doesn\'t Matter'
else:
print 'pass'
Related
I'm running multiple floats through a function to generate a scientific notation. However, not all floats are put in at all times (it is randomised) therefore generating an error.
Input:
a0,hvt,at,lambd = signify(a0,hvt,at,lambd)
Function:
def signify(*args):
rst = []
for arg in args:
if arg >= 100.0 or arg <= 0.01:
arg = '{:.2e}'.format(arg)
rst.append(arg)
return rst
In other words, 'rst' does not always consist of four elements (thanks for pointing it out Singh).
Is someone willing to point me in the right direction?
i don't think you quite understand what the error is. Can you post the error message?
I suspect you trying to assign a0,hvt,at,lambd = signify(a0,hvt,at,lambd) is the real culprit, what if "rst" returning from the function does not have 4 elements? That syntax on the left hand side forces the list on the right hand side to be unpacked exactly into 4 elements, and raises a ValueError: too many values to unpack (expected 4) in a mismatch.
try result = signify(a0,hvt,at,lambd) and check output.
Update:
If you want to only modify only some of the 4 terms but allow the rest to pass as-is, you Just need an else portion. Here is how you can think of the entire process.
def signify(*args):
rst = []
print(args)
for arg in args:
if arg >= 100.0 or arg <= 0.01:
arg = '{:.2e}'.format(arg) #returns a string
rst.append(arg)
else:
rst.append(arg) #take note that this else statement is the same as the last statement of if block
#also note that args going through else block are not "strings" unlike the if block, which gives a string during ".format()"
return rst
We can improve on this.
def signify(*args):
rst = []
print(args)
for arg in args:
if arg >= 100.0 or arg <= 0.01:
arg = '{:.2e}'.format(arg)
rst.append(arg) #note that you may want to typecast to string to maintain uniformity.
#rst.append(str(arg))
return rst
However, This essentially is the same as applying a function on all args. We can create a function that emphasizes this "working on 1 term" approach.
def signify_single(single_arg):
if single_arg >= 100 or single_arg <= 0.01:
return '{:.2e}'.format(single_arg)
return single_arg #or str(single_arg)
a,b,c,d = (signify_single(x) for x in (101,202,303,40))
But that makes us realise this is just an if-else statement. They do not have to be ugly necessarily. (PS. That last line is a list comprehension.)
a,b,c,d = ('{:.2e}'.format(x)
if (x >= 100 or x <= 0.01)
else x #or str (x)
for x in (101,202,303,40))
The condition can be tweaked around a little to give us a cleaner comprehension.
Note that these can be written in a single line as well if you prefer.
a,b,c,d = (x if (0.01 < x < 100) else '{:.2e}'.format(x) for x in (101,202,303,40))
You can use any of the styles which looks the cleanest to you, Or explore and find something even better. Just apply it to your case like this.
a0,hvt,at,lambd = (x if (0.01 < x < 100) else '{:.2e}'.format(x) for x in (a0,hvt,at,lambd))
This could be super simple but I can’t think of a solution. I want to be able to change a variable outside of a if statement. I have this in a try loop.
For example:
Try:
X = 0
If char == ord (‘w’):
X += 1
The only problem is that once it runs again the value of x will return to 0. How do I reassign the value of x to be the new number?
assign as an argument of the function what you want to change from one side and inside of the function make sure to use "return" the value that you want to be changed.
Once done push the same returned as an argument, with a loop most likely.
def function_name(x):
x +=1
print('New X Value',x)
return x
for i in range(5):
function_name(i)
Is there a way to do variable assignments(as shown below) using ternary operators in python:
if(x>1):
y="yes"
else:
z="yes"
Something like (x='yes') if(x>1) else (z='yes'), but this gives an error. Is there any other way to do this?
I know single variable assignments can be done like this: x="yes" if(l==0) else "no"
Edit: Assume x, y & z are assigned with some value before this is run.
You can use the following hack, which employs tuple unpacking:
y, z = ('yes', z) if x > 1 else (y, 'yes')
Don't miss those parentheses.
I wouldn't really recommend using this as it is harder to understand, has one redundant assignment statements, and uses unpacking unnecessarily. I'd recommend going for the normal if statement wherever you can.
This is what it would be with normal ifs:
if x > 1:
y = 'yes'
z = z
else:
y = y
z = 'yes'
No, you can't do that. You can only have expressions, not statements, inside the ternary. print works because (in Python 3 at least) it is a function call, therefore an expression; but assignment is always a statement.
varname = 'y' if x > 1 else 'z'
If you want to assign a global variable:
globals()[varname] = 'yes'
If you want to set an attribute on an object:
setattr(obj, varname, 'yes')
If it's a local variable inside a function, you have to get more hacky:
exec('%s = "yes"' % varname)
or
exec(varname + ' = "yes"')
You can of course place the definition of varname directly in all of these statements to keep it in one line, I'm just avoiding repetition.
But really it's best to not do any of these. Keep it simple and straightforward.
You can use exec function like this:
exec("y='yes'" if x > 1 else "z='yes'")
I want to have a program that prints me a word in this way only by recursion and if-else clauses:
P
Py
Pyt
Pyth
Pytho
Python
Why does following code not work? It gives me an error of maximum recursion depth exceeded.
def oneToAll (word, x):
if -x < 0:
print(word[:-x])
oneToAll(word, x+1)
else:
return
wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))
def oneToAll (word, x):
if -x < 0:
print(word[:-x])
oneToAll(word, x-1)
elif x == 0:
print(word)
else:
return
wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))
This seems to work. Note that I've now recursed using x-1 instead of x+1 because you want x to always be working its way toward 0.
Implementing this way, you have to handle the special case where x == 0. In that case, you want to print the entire string, not word[:0] (which is always an empty string). Also note that I didn't recurse further from the 0 branch. This is because at this point, you're done. You can actually remove the else clause entirely (give it a try!).
I may be missing something, but you could achieve the same thing like this:
def one_to_all(w):
if w:
one_to_all(w[:-1])
print w
one_to_all('Python')
Your code doesn't work because (i) you add 1 to x instead of subtracting 1 and (ii) when x reaches zero, word[:-x] is an empty string, so you need to deal with that case separately.
Try this code with intuitive index of "word"
def oneToAll(word, x):
if x > 1:
print (word[0:len(word) - x])
oneToAll(word, x - 1)
elif x == 1:
print (word)
wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))
I have written a very simple program in python
for i in range(1,1000):
if (i % 3 == 0) and (i % 5 == 0) :
result += i
else:
print('sum is {}'.format(result))
When I try to compile the problem I am getting the error.
NameError: name 'result' is not defined
This statement:
result += i
is equivalent to:
result = result + i
But, the first time this statement is reached in your loop, the variable result has not been defined, so the right-hand-side of that assignment statement does not evaluate.
Add result = 0 before your for loop.
First of all, your indentation is inconsistent and incorrect which makes it harder to read.
result = 0
for i in range(1,1000):
if (i % 3 == 0) and (i % 5 == 0) :
result += i
else:
print 'sum is ',result
This is the way to get around your error, but I don't think this is actually what you're trying to do. What is the problem you're trying to solve?
or...
try:
result += i
except:
result = i
but this won't get you past what happens if the loop condition never occurs (you would need another try in your printout), so just setting it prior to the loop is probably better.