How to show that a program is being processed? [closed] - python

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 4 years ago.
Improve this question
I made a program on checking if an user-input number is prime or not. However, when I enter large numbers, it takes a considerable amount of time. What sort of code would help to show the user that the number is being checked upon, something similar to a loader, unless the result has been determined? The code is as follows:
from math import sqrt as s
from time import time as t
def check_prime(p):
prime = [p]
start = t()
if p > 3:
for i in range(2, int(s(p)) + 1):
if p % i == 0:
end = t()
print('Time taken is', end - start, 'seconds')
prime.remove(p)
break
else:
continue
else:
pass
try:
end
except:
end = t()
print('Time taken is', end - start, 'seconds')
if p in prime:
if p == 2 or p == 3 or (p != 1 and p > 0):
return(f'{p} is a prime number')
elif p <= 0:
return(f'{p} is not in the domain of prime or composite numbers')
else:
return('1 is neither prime nor composite')
else:
return(f'{p} is NOT a prime number')
while True:
p = input('> ')
print(check_prime(int(p)))

I think the simplest solution to get an animated loader (as I guess that's what you asked for) that can be inserted anywhere is something like this:
import sys, threading, time
loading = True
def loader(*args):
while loading:
time.sleep(0.5)
sys.stdout.write('[-]' + '\b'*3) # Write loader and return to start of line
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('[/]' + '\b'*3)
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('[|]' + '\b'*3)
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('[\]' + '\b'*3)
sys.stdout.flush()
t = threading.Thread(target=loader)
t.start()
# Do some work here
loading = False
To avoid creating a thread, you can do this in your loop while checking if your number is prime.

You could print to the console something like a loading bar( for example, using _ characters ). Therefore, you could add a new '_' char to the console buffer whenever a percentage of the given operations that you perform is being processed.
You could do that in the loop inside the "check_prime" function, as I do not suggest assigning this task to another thread, as there are several situations that you'd have to take into consideration.

Related

I need a better way to implent a condition for this while loop [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 1 year ago.
Improve this question
def factors(x):
if x >= 0:
for i in range(1,x): # cannot do mod on 0
if (x%i) == 0: # a factor evenly divides with no remainder
print(i, end= " " )
else: print("error message ")
factors(21)
factors(-1)
factors(-3)
How can I print factors more organized so you can tell where each factor came from? for example I wanted to print " Factors for 21 are ...... etc. however they are on the same line
My output is :
1 3 7 error message
error message
and I want my out put to be
Factors for 21 are : 1 ,3 ,7
error message
error message
The solution is about finding the right structure. Since you want "Factors for 21 are :" printed first you should start the function printing that. Since you want a new line, you could insert a simple print() after the for-loop.
A solution could be:
def factors(x):
if x >= 0:
print(f"Factors for {x} are :", end= " ")
for i in range(1,x): # cannot do mod on 0
if (x%i) == 0: # a factor evenly divides with no remainder
print(i, end= " " )
print()
else: print("error message ")
factors(21)
factors(-1)
factors(-3)
Always remember that code works in the order you write. So if you want A to happen before B happens, then write the code for A before the code for B.
Try this:
def factors(x):
if x >= 0:
print(f"Factors for {x} are:", end=" ")
for i in range(1,x): # cannot do mod on 0
if (x%i) == 0: # a factor evenly divides with no remainder
print(i, end=", ")
print()
else:
print("error message")
factors(21)
factors(-1)
factors(-3)
We are first printing out the "Factors for..." and putting the end argument so the result happens all on 1 line. Then, in the for loop, we are iterating and place a comma after each iteration. Then, we are using the a regular print statement to create a new line before you print out "error message".

Why does my algorithm stop after a while? [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
I wrote an Algorithm to guess a number the user inputs:
import random
def innum(x):
innumber = ""
for y in range(x):
innumber += str(y)
return innumber
def ml():
wrong = ""
while True:
guess = start
action = random.choice(["+","-"])
if action == "+":
guess += random.randint(0,1000)
if action == "-":
guess -= random.randint(0,1000)
if "-" not in str(guess):
if str(guess) not in wrong:
if guess == answer:
print("Correct: " + str(answer))
break
else:
print("Wrong:" + str(guess))
wrong += str(guess)
start = random.randint(0,1000)
answer = input("What number to go to from " + str(start) + ". Has to be in range 2000.")
if answer in innum(2000):
ml()
else:
print("Number not in range 2000.")
But after a while it just stops I ran it multiple times and it keeps stopping and never gets a answer. I read the program multiple times and I still don't know why it stops.
After some testing, I would assume that the condition if str(guess) not in wrong: is never true after some time of execution. Since the program will with time populate the wrong with many different combinations of digits, the str(guess) will eventually be somewhere among the wrong.
The problem is if str(guess) not in wrong: will check if the value is not in the string. But once it encounters the value, the if statement returns False and hence the program halts. However there is no halting in the while loop.

How to proceed to next step when if statement is true for more than xy amount of seconds? [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 4 years ago.
Improve this question
Tried to find an answer, didn't have luck.
How to proceed to next step when if statement is true for more than xy amount of seconds.
Example:
if 10 > 5 and True for 5 seconds:
print("you did it")
This is what I meant. Modified Rakesh's script a little bit to help newbies like me:
import time
import random
while True:
blue = random.random()
red = random.random()
print("orange")
print("green")
if blue < red: # check condition
time.sleep(5) # sleep 5 seconds
if blue < red: # check condition again
print("you did it") # if condition still true after 5 seconds print message
break # break while loop and continue with script
else:
continue # if condition is not true continue with loop until condition is true
print("purple")
print("yellow")
You can use time module.
Ex:
import time
if (condition_if_True):
time.sleep(5) #Sleep 5 sec
if (condition_if_Still_True): #Check condition again
print("you did it")
Loops can have an else clause which is run if a break is not executed. You could get the current time and write a while loop that exits on timeout. If the condition is met early, do a break. Now you know that the else is the timeout.
import time
something = 10
end = time.time() + 5
while time.time() < end:
do_something()
if something < 5:
print("exit early")
break
else:
print("you did it")

Program still closing regardless of end clause (Python) [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 6 years ago.
Improve this question
I wrote a program to generate primes up to a limit; it works, but whenever I launch the program itself, which opens in the Python command line, it closes the second it finishes running. I added
print('Press enter to exit.')
at the end of the program and in other programs this stops it from closing, but this one closes anyway.
The program in full:
from __future__ import division
import math
def isprime(n):
x = 2
while(x >= 2 and x <= n**0.5):
if n%x == 0:
return False
x += 1
return True
print('Enter an upper bound.')
y = input()
print('Would you like place numbers? Y/N')
b = raw_input()
if b == 'Y' or b == 'y':
a = 0
elif b == 'N' or b == 'n':
a = 1
else:
print('Error. Enter Y or N.')
i = 2
c = 1
while(a == 1 and i <= y):
if isprime(i) == True:
print(i)
c += 1
i += 1
while(a == 0 and i <= y):
if isprime(i) == True:
print('Prime number ' + str(c) + '-->' + str(i))
c += 1
i += 1
print(str(c) + ' primes in total were generated between 0 and' + str(y))
print('Press enter to exit.')
Note: I'd rather you help me stop it closing.
The python "print" function displays text, but do not stop program execution.
So the interpreter print this line, but just after the program stops because there is no more instructions.
And on many OS, when command line program is finished, the console window is immediately closed.
But effectively, if you write instead raw_input("press enter to exit") , it won't close, because the "input" function waits user input, so the program is paused until the user press enter.
I hope it answered the question
`
I think you meant
input("Press enter to exit")
not print(...)

How do I write a function that repeatedly prompts the user for a number and then average the numbers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm pretty new to programming, and I have no idea how to go about this.
Basically I need a function that repeatedly prompts a user to input an integer until they enter a non-numerical characters, then it takes the numbers and averages them.
This what I have so far, the ave function is to average the numbers, that's not the problem
def ioAve():
L = input("Enter your number: ")
if L == int:
print(L)
if L != int:
ave(L)
The program doesn't return anything at all.
This is probably the most pythonic way I can think of to solve this. Your approach of checking if an entered number is of a certain type is less desirable than catching the exceptions that might be raised when trying to convert (e.g. in this case a ValueError is raised when an invalid value is passed to int() ). You can learn more about exceptions in Python at the Python wiki.
The solution below also uses a list, which is an object that can contain multiple values. You can learn more about lists at effbot.org.
numbers = list()
while True:
try:
number = int(input("Enter a number: "))
numbers.append(number)
except ValueError:
break
print ("The average is", sum(numbers) / len(numbers))
cont = True
nums = []
while cont:
entered = input("Enter a number: ")
cont = all(char.isdigit() for char in entered)
if cont:
nums.append(int(entered))
print("The average is:", sum(nums)/len(nums))
Something like this:
print('Average: ',(lambda x:sum(x)/len(x))
([x for x in iter(lambda:(lambda x:int(x)
if x and all(x.isdigit() for x in x)else
...)(input('Enter a number: ')),...)]))
Sorry, I couldn't resist.
Something like this maybe. I'm sure there is a more pythonic way thou.
#import sys instead of using sys for program termination
def main():
sum = 0
iterations = 0
while True:
try:
num = int(raw_input("Input an integer: "))
iterations += 1
sum += num
except:
print "Average: "+str(sum//iterations)
#sys.exit() use break to "jump" out of an infinite loop
break
if __name__ == "__main__":
main()

Categories

Resources