What is the best possible way to loop this program - python-3.5

count = 0
while (count >4):
fixedcosts = float(input("Enter fixed costs: "))
salesprice = float(input("Enter the price for one unit: "))
variablecosts = float(input("Enter the variable costs for one unit: "))
contribution = float(salesprice)-float(variablecosts)
breakevenpoint = float(fixedcosts)/float(contribution)
roundedbreakevenpoint = round(breakevenpoint)
#Finds break even point
if int(roundedbreakevenpoint) < float(breakevenpoint):
breakevenpoint2 = int(roundedbreakevenpoint) + 1
print("Your break even point is ",int(breakevenpoint2),"units")
else:
print("Your break even point is ",int(roundedbreakevenpoint),"units")
#Finds number of units needed to make a profit
if int(roundedbreakevenpoint) < float(breakevenpoint):
breakevenpoint3 = int(roundedbreakevenpoint) + 2
print("To make a profit you need to sell ",int(breakevenpoint3),"units")
else:
int(roundedbreakevenpoint) >= float(breakevenpoint)
breakevenpoint4 = int(roundedbreakevenpoint) + 1
print("To make a profit you need to sell ",int(breakevenpoint4),"units")
decision = input("Would you like to restart the program?")
if decision == 'yes' or 'Yes':
count = count + 1
print("This program will now restart")
else:
print("This program will now be terminated")
print("Press enter to stop the program")
quit()
What is the best way to loop this code? I have tried while loop but I can't seem to be able to get it to work with a yes no answer.

Related

Python Word guessing game, cannot get While loop to repeat program

I am trying to create a word guessing game in python. I can get the program to run once,
but I want it to run five times in a row keeping track of wins and losses, and this is where
I am running into issues. I have tried adding a counter and nesting the while loop but this does not seem to work. Any help or suggestions would be greatly appreciated. Thanks.
Here is the code I have written:
import random
print('Welcome to the word guessing game!')
input("What is your name? ")
print('Try to guess the word letter by letter, you have ten guesses, good luck!')
words = ['cowboy', 'alien', 'dog', 'airplane',
'trees', 'bridge', 'snake', 'snow',
'popcorn', 'apples', 'road', 'smelly',
'eagle', 'boat', 'runner']
word = random.choice(words)
print("Guess the word!")
guesses = ''
trys = 5
wins = 0
losses = 0
rounds = 0
while rounds < 5:
while trys > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("*")
failed += 1
if failed == 0:
print("You Win")
print("The word is: ", word)
wins = wins + 1
rounds = rounds + 1
break
print()
guess = input("Enter your letter:")
guesses += guess
if guess != word:
trys -= 1
print("Plesae try again, You have", + trys, 'more guesses')
if trys == 0:
print("You Loose, better luck next time")
losses = losses + 1
rounds = rounds + 1
print('Wins:', wins )
print('Losses:', losses)

Python multiply game. My script needs to have a arbitrarily number of players that each have to take turn in answering a multiplication question

Basically i need to make a game im python that can have a arbitrarily number of people that alternatly answers a multiplication question. But my issue is that i dont know how to keep it running until i hit 30 points. Ive tried to use dict's where the key is the player name and the value is the score. But it stops after the script only has ran once. I tried with a while loop but it went on forever. please help!
import random as r
n = int(input("Insert number of players: "))
d = {}
for i in range(n):
keys = input("Insert player name: ")
#to set the score to 0
values = 0
d[keys] = values
#to display player names
print("Player names are:")
for key in d:
print(key)
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
break
I think this will work
winner = False
while not winner :
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
winner = True
break

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

Python3: How to loop my dice roller program back to the start

Writing my first solo program with no help from teacher or group, a simple code that can act as a D&D dice roller for any type or number of dice a user requires.
I've been working on it for about four hours, and I'm stuck on the last thing I want to do which is loop it back to the beginning instead of just ending when a user doesn't reroll the already chosen dice, I'd like it so it starts again from the top so the player can input a new dice value and number of rolls generated without closing the program and rerunning it.
import random
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
You might try something like:
import random
while True:
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled or 0 to exit: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
if max == 0:
break
if max < 0:
continue
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
Also, I would suggest renaming "min" and "max" as they are reserved keywords

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Resources