While loop not breaking even with the 'break' statement - python

I'm a beginner at python and programming in general so I've no idea what's wrong with my code. I'm trying to break out of the while loop but it's not working. Also, the fibonacci number code is not working as well. All the numbers between 1 to 1000 are interpreted as FIB numbers.
import collections
import threading
def main():
my_list = []
i = 0
time_second = int(input("Please input seconds\n"))
def sample():
threading.Timer(time_second, sample).start()
# Counts the frequency of number in a list
ctr = collections.Counter(my_list)
print(ctr)
sample()
first_number = int(input("Please enter the first number\n"))
my_list.append(first_number)
while True:
user_input = input("Enter number\n")
if user_input.isnumeric():
user_input = int(user_input)
# check for Fibonacci number
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 1
elif n > 2:
return fibonacci(n - 1) + fibonacci(n - 2)
if user_input in range(1, 1001):
print("FIB")
my_list.append(user_input)
if user_input == 'q':
print("Bye")
break
main()

Your function is in an odd place and I recommend you place it outside of the while loop.
There are a few ways to exit a loop. One of these ways is by satisfying a condition for the while loop to exit from.
import time
def in_loop(count):
print(f"Still in loop... on the {count} cycle")
def exited_the_loop():
print("Exited the loop")
count = 0
while count < 10:
time.sleep(.3)
count += 1
in_loop(count)
exited_the_loop()
Another way is to use python's break when a certain condition has been met within the loop. In this case I've used an if statement to check for this condition.
import time
def in_loop(count):
print(f"Still in loop... on the {count} cycle")
def exited_the_loop():
print("Exited the loop")
count = 0
while True:
time.sleep(.3)
count += 1
in_loop(count)
if count > 10:
break
exited_the_loop()

Related

Python Change variable inside a loop while looping through it

I just startet with Python and wanted to make a little countdown app, i am able to do it with seconds but when i try to do it with minutes it just goes into the negatives, i tried it with a if statement but instead it goes into the negatives. Any Ideas? Also anything I should change to make my code cleaner? Thanks in advance :)
import winsound
frequency = 1000
duration = 1000
def calc(num):
if dictionary["unit"] == "seconds":
for i in range(num):
print(num)
time.sleep(1)
num = num - 1
if num == 0:
winsound.Beep(frequency, duration)
elif dictionary["unit"] == "minutes":
num2 = 60
sum = 60
for i in range(num*60):
num2 = num2 -1
print(f"{num} Minutes {num2}")
time.sleep(0.005)
if num2 == 0:
num -1
num2 +60
def validation():
try:
number = int(dictionary["time"])
if number > 0:
calc(number)
except ValueError:
print("Do it again")
user = (input("Enter your Time\n"))
splitet = user.split()
dictionary = {"time": splitet[0], "unit": splitet[1]}
validation()
You can convert the minutes to seconds and do while loop for counting down. in for range loop, i already acts like a count down so you don't need to check if num is 0.
import time
import winsound
frequency = 1000
duration = 1000
def parse_time(input_str):
parts = input_str.split()
if len(parts) != 2:
raise ValueError("Wrong format.")
try:
number = int(parts[0])
except ValueError:
raise ValueError("Time is not integer")
if number <= 0:
raise ValueError("Negative Time")
return number, parts[1]
def calculate_seconds(count, measure):
if measure == "seconds":
return count
if measure == "minutes":
return 60 * count
def countdown(n_sec):
# A reversed range loop to count down
# i will decrease from n_sec to 0 in each iteration
for i in reversed(range(n_sec)):
print("%d minutes %d seconds" % (i / 60, i %60))
time.sleep(1)
winsound.Beep(frequency, duration)
if __name__ == "__main__":
# Use raw_input for raw string input.
input_str = raw_input("Enter your Time\n")
count, measure = parse_time(input_str)
seconds = calculate_seconds(count, measure)
countdown(seconds)

My loop is running endlessly even though i have an end condition after i run the code

im doing a small "mastermind" game for a project, seems to run fine up until my last while loop, i thought i have an end statement but it seems to run on repeat. I've been stuck on this for some time now and i would appreciate any and all help on this, thanks! Here is the code:
import random
def generate_code():
"""Create a random code as a list"""
for i in range(0,4):
i = random.randint(0,5)
code.append(i)
print(code)
def make_guess():
"""Let's the user input a guess"""
while len(guess) < 4:
element = input("your guess, one at the time: " )
if element.isnumeric():
element = int(element)
global amountOfGuesses
if element in range(0,6):
guess.append(element)
amountOfGuesses = amountOfGuesses +1
else:
print("number has to be between 0 and 5")
else:
print("has to be a number between 0 and 5")
def right_position(guess, code):
"""Calculate how many correkt numbers on right position the guess have"""
howManyRight = 0
for i in range(4):
if guess[i] == code[i]:
howManyRight = howManyRight +1
return howManyRight
def wrong_position(guess, code):
"""Calculate how many numbers are corret but wrong position"""
howManyWrongPosition = 0
tempCode = code[:]
for i in guess:
if i in tempCode:
tempCode.remove(i)
howManyWrongPosition = howManyWrongPosition +1
howManyWrongPosition = howManyWrongPosition - right_position(guess, code)
return howManyWrongPosition
code = []
guess = []
wrongPosition = []
rightPosition = []
codeCopy = code.copy()
amountOfGuesses = 0
print("Welcome to Mastermind.\nYou get seven guesses to gues a random 4 digit code with 6 different numbers between 0 and 5.")
generate_code()
while amountOfGuesses <= 7:
make_guess()
print("you have", right_position(guess, code), "right numbers on the right position")
print("you have", wrong_position(guess, code), "numbers on that is right but on the wrong posiotion")
if guess[:] == code[:]:
print("Congratulation you won!!! you used", amountOfGuesses, "guesses.")
From what I understand you want one try to be one input of 4 numbers, so I also fixed that. The reason you're getting an infinite loop is because you haven't broken out of the loop at end. You should also clear the guess array, otherwise the for loop inside the make_guess() will just skip due to the length being 4 (in case the guess was wrong and want to try again).
The fixed code (assuming one try is input of 4 numbers):
import random
def generate_code():
"""Create a random code as a list"""
for i in range(0,4):
i = random.randint(0,5)
code.append(i)
print(code)
def make_guess():
"""Let's the user input a guess"""
global amountOfGuesses
while len(guess) < 4:
element = input("your guess, one at the time: " )
if element.isnumeric():
element = int(element)
if element in range(0,6):
guess.append(element)
else:
print("number has to be between 0 and 5")
else:
print("has to be a number between 0 and 5")
amountOfGuesses = amountOfGuesses +1
def right_position(guess, code):
"""Calculate how many correkt numbers on right position the guess have"""
howManyRight = 0
for i in range(4):
if guess[i] == code[i]:
howManyRight = howManyRight +1
return howManyRight
def wrong_position(guess, code):
"""Calculate how many numbers are corret but wrong position"""
howManyWrongPosition = 0
tempCode = code[:]
for i in guess:
if i in tempCode:
tempCode.remove(i)
howManyWrongPosition = howManyWrongPosition +1
howManyWrongPosition = howManyWrongPosition - right_position(guess, code)
return howManyWrongPosition
code = []
guess = []
wrongPosition = []
rightPosition = []
codeCopy = code.copy()
amountOfGuesses = 0
print("Welcome to Mastermind.\nYou get seven guesses to gues a random 4 digit code with 6 different numbers between 0 and 5.")
generate_code()
while 1:
make_guess()
print("you have", right_position(guess, code), "right numbers on the right position")
print("you have", wrong_position(guess, code), "numbers on that is right but on the wrong posiotion")
if guess == code:
print("Congratulation you won!!! you used", amountOfGuesses, "guesses." if amountOfGuesses > 1 else "guess.")
break
elif amountOfGuesses > 7:
print(f"You have lost by using {amountOfGuesses} tries!")
break
guess = []

Python: how to increment number and store in variable every time function runs

(I'm a beginner in Python, just so you know)
What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.
My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.
Part of the code:
choice = int(input("> "))
if choice == 1:
print("This is the wrong hall.")
increment()
elif choice == 2:
print("This is the wrong hall.")
increment()
elif choice == 3:
hall_passage()
else:
end("You failed")
COUNT = 0
def increment():
global COUNT
COUNT += 1
increment()
print(COUNT)
The increment part is from this thread and read using global scope is not a good practice.
The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.
What is the best way to do this?
maybe something like this...
class Counter():
def __init__(self):
self.counter = 0
def increment(self):
self.counter += 1
def reset(self):
self.counter = 0
def get_value(self):
return self.counter
mc = Counter()
while mc.get_value() < 3:
v = int(input('a number: '))
if v == 1:
print('You won!')
mc.counter = 3
else:
print('Wrong guess, guess again...')
if mc.counter == 2:
print('Last guess...')
mc.increment()
Adapting this answer you could utilize the functions own __dict__. Note: if you didn't come across the # syntax yet search for "python", "decorator":
import functools as ft
def show_me(f):
#ft.wraps(f)
def wrapper(*args, **kwds):
return f(f, *args, **kwds)
return wrapper
#show_me
def f(me, x):
if x < 0:
try:
me.count += 1
except AttributeError:
me.count = 1
print(me.count, 'failures')
f(0)
f(-1)
f(1)
f(-2)
Output:
1 failures
2 failures
What do you think about this solution?
If you put here while loop you will forced on user to put correct answer.
Also i placed between if/elif/else statements input function.
count - That variable is counting wrong options
choice = int(input("> "))
count =0
while choice !=3:
if choice == 1:
print("This is the wrong hall.")
count += 1
choice = int(input("> ")) # Also i place in the if/elif/else statements input function
elif choice == 2:
print("This is the wrong hall.")
count +=1
choice = int(input("> "))
elif choice == 3:
hall_passage()
else:
end("You failed")
count += 1
choice = int(input("> "))
print(count)

Issue with Python Slot Machine

import random
balance = 50
def generator():
slot = 0
count = 0
gen = random.random()
while count < 3:
count = count + 1
if gen <= 0.01:
slot = 'Cherry'
elif gen <= 0.06:
slot = 'Diamond'
elif gen <= 0.16:
slot = 'Heart'
elif gen <= 0.36:
slot = 'Spade'
elif gen <= 0.66:
slot = 'Club'
elif gen <= 1:
slot = 'Monkey'
else:
break
return slot
def win(generator):
if generator() == 'Monkey' and generator() == 'Monkey' and generator() == 'Monkey':
balance = balance + 2122
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
print generator()
print generator()
print generator()
print ""
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
I'm trying to make a very basic slot machine.
My question is: How do I make the generator function repeat 3 times and return 3 outputs, and then how do I make it recognise certain combinations?
Is this possible at all, keeping with my current format?
Also, how could I incorporate arrays into my code?
Thanks
Make the generator return a list or tuple of three values after generating three values, also it would be easier to use random.choice() rather than random.random() . random.choice() randomly selects a element for a list of values/iterable with equal probability for all elements. Example -
def generator():
ret = []
for _ in range(3):
ret.append(random.choice(['Cherry','Diamond','Heart','Spade','Club','Monkey']))
return tuple(ret)
If you want to have different probabilities for different elements, you can keep the current method, just loop over that three times and append to ret like done above and return ret from it.
Then in your win function, keep a dictionary such that the key is the tuple of combination and the value is the amount the user wins, then you can simply use .get() with a default value of 0 , to get how much the user won. Do not pass in generator as an argument. Example -
def win():
roll = generator()
d = {('Monkey','Monkey','Monkey'):21222,...}
return d.get(roll,0)
Then in your main loop, call this win() function to roll and see how much the user won.
Use the range function to choose 3 times and store it in a list.
import random
choices_list=[]
for ctr in range(3):
gen = random.choice(['Cherry', 'Diamond', 'Heart',
'Spade', 'Club', 'Monkey'])
choices_list.append(gen)
print choices_list

Trying to find the next prime number

MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1

Categories