How to break my loop? - python-3.x

I want to have the loop add integers to the list and break when the user hits return.
How do I manage to do this?
lstScore = []
count = 0
while count >= 0:
count = int(input("Enter a score :"))
if count != int:
break
elif:
lstScore.append(int(count))

This should help you,added exception handling for int conversion errors
lstScore = []
count = 0
while count >= 0:
try:
temp = input("Enter a score :")
if(temp != ''):
count = int(temp)
else:
break
lstScore.append(int(count))
except ValueError as x:
print("value error")
break

Related

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 ')

Count not incrementing properly in python while loop

Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.

collatz sequence infinte loop error

I am getting an infinite loop. I am not sure on how to covert the result as the new number variable and put it back in the while loop.
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except:
ValueError
print('Please type an integer')
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
**result = number**
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
The following works:
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except ValueError:
print('Please type an integer')
sys.exit(1)
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
number = result # set the number to the result
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
Notice that I set the number to the result, in your code the number never changed, and so kept hitting the same block of code over and over. I also added a sys.exit call in the exception, we don't want to continue if someone entered in a bad value.

Cannot keep certain numbers from averaging

I need help. I'm trying to run the program below. When I enter a number above 100 or below 0 I need it to disregard that input any advice?
total = 0.0
count = 0
data = int(input("Enter a number or 999 to quit: "))
while data != "":
count += 1
number = float(data)
total += number
data = int(input("Enter a number or 999 to quit: "))
try:
data = int(data)
except ValueError:
pass
average = round(total) / count
if data == 999:
break
elif data >= 100:
print("error in value")
elif data <= 0:
number = 0
print("error in value")
print("These", count, "scores average as: ", round(average, 1))
You could move the average = ... line behind the checking for invalid numbers and add continue to the checks for invalid numbers. So the last lines would end up like this:
if data == 999:
break
elif data >= 100:
print("error in value")
continue
elif data <= 0:
print("error in value")
continue
average = round(total) / count

Resources