timer based on count in python [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 2 years ago.
Improve this question
I am trying to pass my query value to an external API, but since the API has a throttling issue I can make only 500 calls per 5 mins and need to give 10 mins of cooling time. so what I am trying, I added a count increment method and if the count passes more than 400 then sleep for 2 mins, I know the mistake is in my code, but I don't know how to write a function to it.
for info in contact:
id = info[0]
name = info[1]
print(id)
count += 1
print(count)
if count > 400:
print('11111111')
time.sleep(120)
print ("count crossed 400....")
print ("sleep for 2 minutes")
else:
logging.info(count)
print(name)
try:
...
so this will check the count and if the count is more than 400 it will sleep 2 minutes for every other call till the completion.
I am trying to make it in such a way that for every 400 calls sleep for 2 mins how to write that in python. kindly guide

for info in contact:
id = info[0]
name = info[1]
print(id)
count += 1
print(count)
if count > 400:
print('11111111')
time.sleep(120)
count = 0
print ("count crossed 400....")
print ("sleep for 2 minutes")
else:
logging.info(count)
print(name)
add the line : count = 0, it reset the variable count to 0 if count > 400

Related

python-Write a program that will ask for the name and age of two people [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 3 days ago.
Improve this question
Write a program that will ask for the name and age of two people.
The program should then display a message saying which is older than the other or that they are the same age, if they are the same age.
Ive tried many different ways but can't seem to get the full correct answer.
thename=' '
age=0
namelist=[]
counter = 0
while len(thename)>0:
counter += 1
thename=input('Enter name of person #' + str(counter) + ' (or hit enter to get older person): ')
while not int(age)>0 and thename!='':
age=int(input('Enter age of ' + thename + ':'))
if thename!='':
namelist.append([age,thename])
age = 0
if len(namelist)>=2:
namelist.sort(reverse=True)
print('Here is the age and name of oldest person in the list: ' + str(namelist[0]))
print('------\nHere is the full list in descending order:')
print(namelist)

Python continue and break usage [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to solve the following problem and I assume I have to use continue and break logic.
I have to create an empty to do list and iterate over the dictionary of tasks. I need to add tasks that contain the substring "organize" and once the length of the to do list reaches 2 tasks I break the loop. *
tasks = {
0 : ['Reorganize the cabinet'],
1 : ['Give the dog a bath', 'Create a twitter thread'],
2 : ['Learn python dictionary'],
3 : ['Take a walk'],
4 : ['Go grocery shopping'],
5 : ['Update Facebook'],
6 : ['Respond to emails'],
7 : ['Walk the dog']
}
I could solve the second part of adding the tasks that contain the substring "organize" and could iterate through the length of tasks to filter tasks that are not more than 2. Yet, I can't find the way how to combine two conditions into one.
Put an if statement in the loop that checks the length of the to do list, and breaks out of the loop when it reaches 2.
todo_list = []
for task in tasks.values():
if any('organize' in item for item in task):
todo_list.append(task)
if len(todo_list) == 2:
break
This will work :
to_do_list = []
for task in tasks.values():
for i in task :
if 'organize' in i:
to_do_list.append(i)
if len(to_do_list) == 2:
break
does this do the job:
to_do_list = []
for value in tasks.values():
to_do_list.append([val for val in value if 'organize' in val])
if len(to_do_list) == 2:
break
If you want a flattened list of items, replace to_do_list.append with to_do_list.extend

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}')

Find the "1"s in a list [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
I need to find a book's page count. The pages have 689 1's in it. So it goes 1,2,3,..11,12,.. in order to find the page count, I need to count the 1's. I thought:
book = []
page = 0
while True:
page += 1
book.append(page)
if book.count(1) == 689:
print("The book is {} pages".format(page))
break
but .count(1) does not include 11,21,111 etc. What can I use instead of .count()?
In order to count the number of pages, you could try to just keep track of a counter variable accumlatively instead of using count on the whole book array.
# book = []
page = 0
count = 0
while True:
page += 1
# book.append(page)
count += str(page).count('1')
if count == 689:
print("The book is {} pages".format(page))
break
book = []
page = 0
sum_of_ones = 0
while True:
page += 1
book.append(page)
sum_of_ones += str(book[-1]).count("1")
if sum_of_ones == 689:
print(f"this book has {page} pages.")
break
#output
1234 pages
I believe this is an efficient way.
It keeps counting the newly added page to the book and increases the sum if possible then rechecks if it is ==689 . It breaks when the number is met.
Only issue is that it will keep iterating if 689 is not met

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