Combining two for else block [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 3 years ago.
Improve this question
I have two for else block which verifies two integers,Is it possible to combine both together?
for vars in result['events']:
if vars['yyy'] == 977:
break
else:
raise AssertionError('output not found')
for vars in result['events']:
if vars['yyy'] == int(line.split(',')[-1], 16):
break
else:
raise AssertionError('output not found')

With simple or condition:
for vars in result['events']:
if vars['yyy'] == 977 or vars['yyy'] == int(line.split(',')[-1], 16):
break
else:
raise AssertionError('output not found')
Update after condition clarification:
(also line.split(',')[-1] is replaced with line[line.rfind(',') + 1:])
yyy_set = {977, int(line[line.rfind(',') + 1:], 16)}
for vars in result['events']:
vars['yyy'] in yyy_set and yyy_set.remove(vars['yyy'])
if not yyy_set: break # all set items were consumed
else:
raise AssertionError('output not found')

The other answers assume you want to find one of two needles in a single haystack, and don't care which one you find, but the question isn't clear if that's the correct solution.
To cover the case where you need both search values to be found (looking for two different needles in one haystack, and both must exist), there is no easy syntax to do it. But you can build that logic out of a set and for/else:
remaining = {977, int(line.split(',')[-1], 16)}
for vars in result['events']:
remaining.discard(vars['yyy'])
if not remaining:
break
else:
raise AssertionError('Expected outputs not found: {}'.format(remaining))
remaining.discard(vars['yyy']) removes each vars['yyy'] if it exists, and silently ignores it if it does not. When both expected values have been seen (and discarded), the set is empty, and you break, bypassing the else. If one or more values has not been seen, they'll remain in remaining and can be incorporated into the error message.

The question could have a bit clearer that what it is. Based on what I could understand, you are looking for 2 different values in result['events']. You could use 'or' condition to club the 2 conditions together.
if foobar == 'bac' or zoo == '123':
blah
else:
bleh

Related

Tips For an Intro Python Program [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Below is my first python program. I am trying idea not yet covered in class as i hate staying stagnant and want to solve issues that may arise if i were to just use the info we've learned in class. As for my question, the program works but what were be ways to condense the code, if any? Thanks!
#This is a program to provide an itemized receipt for a campsite
# CONSTANTS
ELECTRICITY=10.00 #one time electricity charge
class colors:
ERROR = "\033[91m"
END = "\033[0m"
#input validation
while True:
while True:
try:
nightly_rate=float(input("Enter the Basic Nightly Rate:$"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter the Dollar Amount"+colors.END)
else:
break
while True:
try:
number_of_nights=int(input("Enter the Number of Nights You Will Be Staying:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
while True:
try:
campers=int(input("Enter the Number of Campers:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
break
#processing
while True:
try:
campsite=nightly_rate*number_of_nights
tax=(ELECTRICITY*0.07)+(campsite*0.07)
ranger=(campsite+ELECTRICITY+tax)*0.15 #gratuity paid towards Ranger
total=campsite+ELECTRICITY+tax+ranger #total paid per camper
total_per=total/campers
except ZeroDivisionError: #attempt to work around ZeroDivisionError
total_per=0 #total per set to zero as the user inputed 0 for number-
break #-of campers
#Output #Cant figure out how to get only the output colored
print("Nightly Rate-----------------------",nightly_rate)
print("Number of Nights-------------------",number_of_nights)
print("Number of Campers------------------",campers)
print()
print("Campsite--------------------------- $%4.2f"%campsite)
print("Electricity------------------------ $%4.2f"%ELECTRICITY)
print("Tax-------------------------------- $%4.2f"%tax)
print("Ranger----------------------------- $%4.2f"%ranger)
print("Total------------------------------ $%4.2f"%total)
print()
print("Cost Per Camper------------------- $%4.2f"%total_per)
The else in try statement is unnecessary. You can just put the break in the the end of the try statement. REF
In the end, in the print statements, I recommend you to use another types of formatting. You can use '...{}..'.format(..) or further pythonic is f'...{val}'. Your method is the oldest. More ref
You can remove both the outer while loops, as break is seen there at the top level, so the loops runs once only.
You can convert colors to an Enum class if desired (this is more of a stylistic choice tbh)
The line tax=(ELECTRICITY*0.07)+(campsite*0.07) can be represented as x*0.07 + y*0.07, which can be simplified to 0.07(x+y) or 0.07 * (ELECTRICITY + campsite) in this case.
Instead of manually padding the - characters in the print statements, you can use f-strings with simple formatting trick.
For example, try this out:
width = 40
fill = '-'
tax = 1.2345
print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')

Add a tuple to a list of tuples [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 2 years ago.
Improve this question
I am trying to automate few of my DBA tasks using python3.
x = " ##Hostname: host1"
y = "##innodb_buffer_pool_size: 1"
z = " ##Max_connections: 150"
op = {}
a = tuple(x.split(':'))
b = tuple(y.split(':'))
c = tuple(z.split(':'))
host=""
if (a[0].strip()).lower() == "##hostname" and (a[1].strip()).lower() not in op:
host = a[1].strip()
op[host] = []
if (b[0].strip()).lower() == "##innodb_buffer_pool_size" and int(b[1].lstrip())<2:
#z = b[0].strip().lstrip('##'),b[1].strip()
op[host].append((b[0].strip().lstrip('##'),b[1].strip()))
if (c[0].strip()).lower() == "##Max_connections" and int(c[1].lstrip())<152:
op[host].append((c[0].strip().lstrip('##'),c[1].strip()))
#elif (a[0].strip()).lower() == "##log_bin" and int(a[1].strip()) == 0:
# op[host].append(tuple((a[0].strip()).lstrip('##'),a[1].strip()))
#elif (a[0].strip()).lower() == "##expire_logs_days" and int(a[1].strip()) == 0:
# op[host].append(tuple((a[0].strip()).lstrip('##'),a[1].strip()))
#else:
# pass
#print (c)
print (op)
Output i am getting:
{'host1': [('innodb_buffer_pool_size', '1')]}
Output i am expecting:
{'host1': [('innodb_buffer_pool_size', '1'),('max_connections','150')]}
If you look at my the code, my first append statement appends tuple to an empty list.
But my second append is not appending to the tuple to the list .
I cannot understand why this behaviour since this first python project and what should be done to append a tuple to an existing list for a specific key in a dictionary.
This is only part of the script, I am trying to iterate through several files and construct a list of tuples for each host with each unique host being the key, hence constructing a dictionary.
Thanks
When you have this kind of case, leanr to debug and split your code, here the problem from the if using Max_connections because that's the one missing
When printing the 2 conditions we have
print((c[0].strip()).lower() == "##Max_connections", int(c[1].lstrip()) < 152) # False True
Then looking further at the first, you set the value as lowercase but your testing stirng contains an uppercase : not valie
Correction
if (c[0].strip()).lower() == "##max_connections" and int(c[1].lstrip()) < 152:

pythonic return in try [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
What is the correct way to deal with return of function in try block?
Option 1:
def someFnc1() -> bool:
try:
fetchSomeData()
return True
except:
return False
Option 2:
def someFnc2() -> bool:
try:
fetchSomeData()
except:
return False
return True
This is described in part in PEP-8:
Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.
Yes:
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
No:
try:
# Too broad!
return handle_value(collection[key])
except KeyError:
# Will also catch KeyError raised by handle_value()
return key_not_found(key)
Based on this your second version should be considered most pythonic (i.e. the absolute minimum of code inside the try clause).

How can I return with a local variable in definition in Python? [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 5 years ago.
Improve this question
I am trying to create a simple AI program which plays stick game. The problem is that I would like to subtract chosen stick from the total stick number. This simple code shows some error such as nonexisting value. I could not assign returning value for my values. Is there another way to subtracts value with functions?
import random
msg = input('Determine stick numbers:')
print('Stick number is determined as:', msg)
# First player move
def robot(stick):
y = stick % 4
if y==0:
y=randint(1,3)
mov=int(y)
print('machine chose:', mov)
total = stick-mov
return total
def human(stick2):
mov2= int(input('your turn:'))
print('human chose:', mov2)
total = stick2-mov2
return total
players= {
'1': robot,
'2': human
}
number1= input('Determine first player machine(1) or human(2):')
number2= input('Determine second player (1) or (2):')
player1=players[number1]
player2=players[number2]
print(player1, player2)
print('the game begins')
while True:
player1(int(msg))
if msg == 0: break
print('remained sticks:', msg)
player2(int(msg))
print('remained sticks:', msg)
if msg == 0: break
Your players are references functions:
players= {
'1': robot,
'2': human
}
Later you call them player1 and player2:
player1=players[number1]
player2=players[number2]
But when you use these functions you don't do anything with the return value:
player1(int(msg))
...
player2(int(msg))
So those functions return something, but you ignore the value. You need to either print that return value or assign it to a variable so you can do something with the value later.
Since your return values are called total perhaps you want:
total = player1(int(msg))
print('new total:', total)
return does work, of course; it returns a value. However in your code you are not capturing that value and it is immediately thrown away.
It's really not clear what you want, but perhaps you want something like this:
msg = player1(int(msg))

while loop calling array outside [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 6 years ago.
Improve this question
Ill start again and thank you all for replying.
I have a log file, and i take the entry and remove all rubbish from it.
the array or list i am left with is this
23
23.23.23.23
45
45.45.45.45
100
34.34.54.13
how i call each line i want is with this.
a = 1
while a < 18:
a = a + 2
#logging.debug(line.split(PID_ANDROID)[a])
countIP = a
trySomething()
if a == 20:
break
but i have to do things after i call it.
i want to be able to use the first entry,
> do something
> see if something is happening
> if its not goto 3rd entry
> try the same thing again.
this is what I am stuck on.
because when I call it from inside something else and I use global to store.
python tells me I cant us a str or turp. or with code below gives me a continues output of everything in the list.
atm i have this code.
def trySomething():
global countIP
global LOG_SPLITER
#logging.debug('Processing Number: %s' % (countIP,))
logging.debug(LOG_SPLITER.split(PID_ANDROID)[countIP])
time.sleep(.5)
clearScreen()
#grabBox90()
#lineGoto()
my question is.
how can i do the loop, and pull out only one at a time to do something with it, and when i get to a finished loop goto the next one?
It looks as if you should use a for loop with an initial index of 1 and a step size of 2. Alternatively, use the explicit debug statement for value 1 and then loop over the rest, starting at 3, to avoid the if test. If the remainder of the code is to increment by 1 instead of 2, then that allows you to do the initial skip properly while still having the loop.
Instead of
c = 1
#do my stuff
while c < 20:
if c == 1:
logging.debug(line.split(PID_ANDROID)[c])
c = + 2
else:
logging.debug('Moving on to a refresh')
# You do not incremennt c
# c += 2 should go here to increment every time
Python 2
for i in xrange(1,20,2):
# do your processing
Python 3
for i in range(1,20,2):
# do you processing
If you simply want to log every entry in line you could do:
entries = line.split(PID_ANDROID)
for e in entries[::2]: # take every other element
logging.debug(e)
Iterating over the entries is "more pythonic".

Categories

Resources