Program still closing regardless of end clause (Python) [closed] - python

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(...)

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.

I want to repeat a function indefinitely [duplicate]

This question already has answers here:
Are infinite for loops possible in Python? [duplicate]
(16 answers)
Closed 2 years ago.
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input.
My code looks like this, mind you I am new to all this.
print('Please enter a number:')
def numberCheck(c):
if c % 2 == 0:
print(c // 2)
elif c % 2 == 1:
print(3 * c + 1)
c = int(input())
numberCheck(c)
I want it to print "Please enter a number" only once. but after running I want it to wait for another number. How would I do this?
I tried a for loop but that uses a range and I don't want to set a range unless there is a way to do it to infinity.
If you want to run an infinite loop, that can be done with a while loop.
print('Please enter a number:')
def numberCheck(c):
if c % 2 == 0:
print(c // 2)
elif c % 2 == 1:
print(3 * c + 1)
while True:
c = int(input())
numberCheck(c)
So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop
print("Enter a number")
while True:
c = int(input(""))
numberCheck(c)
You could use a while loop with True:
while True:
c = int(input())
numberCheck(c)

While loop is not exiting even though variable is being updated [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 2 years ago.
Improve this question
I am trying to create a simple guessing game. Everything works absolutely fine, as it should. But, it can't seem to exit the first while loop which checks if the variable 'guessflag' is less than 15 or not. I also checked whether it is being updated or not by adding some print statements. Please help.
It even exits when it meets the condition which says to exit the program when the user guesses correctly. When I consulted some other queries regarding the same problem at stackoverflow, I tried to make sure that those mistakes don't happen to me. Also, I have to add some more finishing touches to reduce time taken by the program to run, but currently this works absolutely fine.
import random
point = 101
randomint = random.randint(0,100)
hintflag = 0
hintmessage = "To claim a hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***"
guessflag = 0
while guessflag <=15:
def init(param):
global guess, point, guessflag
if(param == 1):
global point,guessflag
point = point - 1
guessflag = guessflag + 1
print(hintmessage)
guess = int(input("Enter your guess. It should be between 1 and 100... "))
proceed()
def proceed():
global hintflag
global point
if (guess < 1 or (guess > 100 and guess != 102)):
print('')
print("Please enter a number between 1 and 100... ")
init(2)
elif ((guess == 102)and(hintflag < 2 and hintflag >= 0)):
if(hintflag == 0):
checkrandeven()
if(hintflag == 1):
checkrandmultiple3()
else:
match()
def checkrandmultiple3():
if (randomint % 3 == 0):
global israndmultiple3, point, hintmessage, hintflag
hintflag = hintflag + 1
israndmultiple3 = True
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is a multiple of 3.")
print("Points: "+str(point))
init(2)
else:
hintflag = hintflag+1
israndmultiple3 = False
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is not a multiple of 3.")
print("Points: "+str(point))
init(2)
def checkrandeven():
if (randomint % 2 == 0):
global israndeven, point, hintmessage, hintflag
hintflag = hintflag+1
israndeven = True
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print('')
print("Your hint is...")
print("The number to be guessed is even.")
print("***YOU HAVE SPENT 20 POINTS***")
print("Points: "+str(point))
init(2)
else:
israndeven = False
hintflag = hintflag+1
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print("The number to be guessed is odd.")
print("Points: "+str(point))
init(2)
def match():
global randomint, guess, point, guessflag, hintflag
if(randomint != guess):
if(randomint < guess):
print("Try Again! Your number was too high; Try a number lower than "+str(guess))
init(1)
if(randomint > guess):
print("Try Again! Your number was too low; Try a number higher than "+str(guess))
init(1)
if(randomint == guess):
print ("CONGRATULATIONS! You won!")
print ("It took you "+ str(guessflag) + " tries, "+ str(hintflag)+" hints to beat the game!")
print("The number of points you finished with are... "+ str(point))
exit()
init(1)
The 'init(1)' call in your while loop is only actually called once, and your 4 functions call each other recursively. In other words, you never actually finish the first iteration of your while loop, you just go further and further down a chain of:
init -> proceed -> checkrandeven (or checkrandmultiple3) -> init -> proceed -> checkrandeven -> init -> proceed ...
Basically you need to think about restructuring your code to avoid the recursion. Try returning outputs within the main loop and then calling subsequent functions from there.

How to make every 'beginner' shown at random during the run of the program [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 4 years ago.
Improve this question
Im currently in make of creating a math game that involves: addition, subtraction, multiplication and division. These parts with purple borders around them are the questions that i had created for the addition part when the user chooses to pick addition.
I dont know how to make these question be shown at random. When the user goes to select addition for addition questions everytime he does or goes back to do it again after he is done i want the questions not to be the same each time i want them to be in a different order. So its random each time.
#addition questions
def beginnerquestionsaddition():
os.system('clear')
score = 0
beginner1 = input("2 + 3 = ")
if beginner1 == ("5"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner2 = input("6 + 7 = ")
if beginner2 == ("13"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner3 = input("2 + 5 = ")
if beginner3 == ("7"):
print("Correct, Well Done!")
score += 1
os.system('clear')
time.sleep(1)
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
So this isn't exactly an answer for the specific way you decided to go about this program but this is a much simpler way:
from random import randrange
def beginner_addition():
A = randrange(1,11) # Increase range on harder questions
B = randrange(1,11) # Ex. for intermediate_addition(), randrange would be (10,21) maybe...
C = A + B
ans = input("What's the answer to " + str(A) + "+" + str(B) + "? ")
if ans == str(C):
print('Correct')
else:
print('Incorrect')
while True:
beginner_addition()
Of course, this is just example code. You could easily include your points system and perhaps move up in difficulty when the points hit a certain level. You could also randomize the operation. Sorry if this isn't what you want but I saw your code and I figured there is nothing wrong with simplifying your code...

Categories

Resources