Why does my algorithm stop after a while? [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 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.

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 is my Python code ignoring my if-statement and quitting? [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 1 year ago.
Improve this question
I am trying to write a python word puzzle game which may have multiple players and points are given based on the length of the words found.
Here is my function which 'plays' the game, however, it always results in "Game over!" no matter if my answer is right or wrong. So it quits the game every time.
def play_game(players, board , words, answers):
found_words = []
num_remaining = num_words_on_puzzle - len(found_words)
player_num = 0
while num_remaining > 0:
print_headers(players, board, found_words, num_remaining)
guess_input = input("{player}, make a guess: ".format(
player=players[player_num % len(players)][0]))
# Allow player to quit
if guess_input.lower() == 'q' or 'quit':
break
# Determine if the guess is valid
guess = convert_guess(guess_input)
if is_valid_answer(answers, guess):
# Update a players score since answer is valid
update_score(players[player_num % len(players)], matching_answer(answers, guess))
# Add this word to found_words list
found_words.append(matching_answer(answers, guess))
print("Congratulations, you found '%s'." % matching_answer(answers, guess))
print("That's %d points(s)." % word_score(matching_answer(answers, guess)))
else:
print("Sorry, that is incorrect.")
num_remaining = num_words_on_puzzle - len(found_words)
player_num += 1
print("\nGame over!\n")
print("The final scores are: \n")
print_score(players)
print(answers)
I hope someone can help me see where my issue is.
The line:
if guess_input.lower() == 'q' or 'quit':
always evaluates to True, because it goes as
if (uess_input.lower() == 'q') or ('quit') which is (False) or (True) --> True as any String != '' is True
Change
if guess_input.lower() == 'q' or 'quit':
to
if guess_input.lower() in ['q', 'quit']

Number guessing Guessing Game [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 3 years ago.
Improve this question
I made a simple number guessing Game and it works perfectly fine, but I want to add something that says "The Number you have entered is too high/ low", because when I type in 100 as my upper bound it is much too difficult to guess the number.
import random
while True:
flag = True
while flag:
num = input('Enter an upper bound: ')
if num.isdigit():
print("Let's Play!")
num = int(num)
flag = False
else:
print('Invalid input! Try again!')
secret = random.randint(1,num)
guess = None
count = 1
while guess != secret:
guess = input('Please enter a number between 1 and ' + str(num) + ": " )
if guess.isdigit():
guess = int(guess)
if guess == secret:
print('Right! You have won!')
else:
print('Try again!')
count += 1
print('You needed', count, 'guess(es) ')
Alright, I'm not gonna solve it for you, but I'll give you a hint. This seems like a homework problem, so it would be unethical of me to provide you with a solution.
else:
print('Try again!')
count += 1
Look at this else statement here. What is the purpose of this else statement? To tell the user they got the guess wrong.
Think about how you can put an if/else condition inside this else condition, to tell the user if their input is too high, or too low.

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

Break function not working in Python 3.5! i dont know why. i need advise [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 6 years ago.
Improve this question
Ok, so i tryed making a number guessing game...didnt work so i turned to youtube.
i even tryed COPYING somone elses code! still didnt work for me. this is my code.
import random
import time
print('This is a guessing gamefrom 1-1000.')
num = random.randint(1, 1000)
time = time.time()
guess = int(input('what number do you guess? '))
playing = True
while(playing):
if guess < num:
print('Guess is too low!')
elif guess > num:
print('Guess is too High!')
elif guess == num:
break
print('Nice job!')
time2 = time.time()
totalTime = str(int(time2-time1))
print('you took ' + totalTime + 'seconds to guess the number')
and if i run it and enter a number it repeats either "answer is too high" or "answer is too low" i dont know what to do.
If you don't ask for a new guess, you will either get it right on the first try and break out of the loop, or you will loop forever because that wrong guess will be the same on every iteration. To fix this, reassign guess every time in your while loop:
time = time.time()
playing = True
while(playing):
guess = int(input('what number do you guess? '))
if guess < num:
# etc.

Categories

Resources