I am going to write a guessing game with the computer.
I choose one number in my head and the Computer is going to find it out, and it can guess between a range.
The problem is I don’t know how can I update this range during the program run.
import random
x = 1
y = 99
guess= random.randint(x,y)
print(guess)
play='true'
while play=='true':
a=x
b=y
results = input()
if results == 'd':
play='false'
else:
if results == 'b':
a=guess
print('My number is bigger!')
newguess= random.randint(a,b)
print (newguess)
elif results == 'k':
b=guess
print('My number is smaller!')
newguess= random.randint(a,b)
print (newguess)
print ('Wooow , computer you did it! ')
Sorry about all the explanations in the code but this is a version of the game that I did a while ago. What I did was I wanted to shrink the guessing range each time the user said high or low. e.g. if the computer chooses 50, and the user says 'High' then the program will not chose a number greater than 50, the same applies for 'Low". Enjoy
import random
count = 0 #Number of attemps. how many times while loop runs.
guess = random.randint(1,100)#The guess generator
(l,u) = (0,100)
lower_guess = l
upper_guess = u
n = 0
print('Chose a number between ', l, ' and ', u , '.' )
#The game. These are outside the function so that they don't print in every loop because they are unwanted for some Y inputs.
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')#User states
#The function
while n != 'guess':
count +=1 #adds 1 to count each time loop runs
if Y == 'L':
lower_guess = guess+1
guess = random.randint(lower_guess , upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'H':
upper_guess = guess - 1
guess = random.randint(lower_guess, upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'Y':
print('I guessed it in ' + str(count) + ' attempts')
break
else:
count = 0
lower_guess = l
upper_guess = u
guess = random.randint(1,100)
print('That input was invalid. The game has restarted.')
print('You can chose a new number or keep your old one.')
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
Related
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
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 ')
I am having difficulty keeping a track of the total number of inputs. I want my program to keep track of the total number of inputs and print it when my while loop breaks. Any help is appreciated!
r = float(input("enter r:"))
def main(r):
a = 3.14 * (float(r ** 2))
s_v = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
total += r
print("Total = " , total)
break
else:
print("Area = ", a)
continue
main(r)
I assume that you want your program to re-calculate the area with each iteration. As written, it will only be calculated the first time you run the mymian function. You don't need to pass any arguments to the function.
def mymian():
sentinal_value = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
print("Total number of r provided to this program" , total)
break
else:
print("Area = ", 3.14 * (float(r ** 2)))
total += 1
continue
I can't figure out what I am doing wrong. I have tried using a break, and tried setting what the variable !=, I am doing this on cengage and it is very finnicky.
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
while leftOrRight != "X":
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
your input() is outside the while loop, so leftOrRight never changes, never get to X so it will not exit the loop:
leftOrRight = None
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
According to your code you are not changing the value for leftOrRight after entering the loop so the condition for your while loop is never false I would suggest the following edit:
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = '' #anything random
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
so that you get a prompt every time the loop is executed and you can click X to exit
Your program just got the character that had the largest id in the ascii table.
And only doing the first string as the longString = max(n) wasn't even in the while loop.
also max returns the largest value, so in this case it was just converting the text into an ascii number.
instead you should use len(string) which returns the length of the string.
Unlike max() which is used like:
11 == max(11,10,1,2) as 11 is the largest character.
n = (input("Input: ")) #get initial input
longest = 0 #define the varible which we will keep the length of the longest string in
longest_str = "" #define the varible which stores the value of the longest string.
while n: #you don't need that other stuff, while n does the same as while n != ''
n = str(input("Input: ")) #get input
length = len(n) #gets the length of the input
if length > longest: #if the length of our input is larger than the last largest string
longest = length #set the longest length to current string length
longest_str = n #set the longest string to current string
#once the user hits enter (typing "") we exit the while loop, and this code runs afterwards.
print("Longest input was", longest_str, "at", longest, "characters long")
Because there are two specific counts we are accumulating for, and the outlying char is at the end of our input, we can set our while to True to break when we hit a char other that "L" or "R".
leftOrRight = ""
# Write your loop here.
while True:
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
if leftOrRight == "L":
leftTotal = leftTotal + 1
elif leftOrRight == "R":
rightTotal = rightTotal + 1
else:
break
# Output number of left or right-handed students.
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
I want to input a series of numbers and end with "stop", the while loop is to check if x is not equal to the 'stop', it continues add up the input number and output the sum for each loop, however the while loop falls into infinity. For example, my input is:
12
35
56
23
56
455
556
344
22
22
stop
#read the input
x = input()
#add up by a loop
T = 0
x_int = int(x)
while x != 'stop':
for i in range(1, 10):
T += x_int
print(i, T)
You need to prompt for the next input in the while loop. As stands, you never prompt for additional data and so you will never see the stop. I added a prompt so that it is more clear.
#add up by a loop
T = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
x_int = int(x)
for i in range(1, 10):
T += x_int
print(i, T)
Several of us are confused about how you want to enter data. If you don't want any prompts and want to read any number of lines from the user (or perhaps piped from another program) you could read stdin directly.
#add up by a loop
import sys
T = 0
for line in sys.stdin:
x = line.strip()
if x == 'stop':
break
x_int = int(x)
T += x_int
print(i, T)
Try this program and see if it works. The problem with your code was there is no need of a for loop. I didn't understand why it was used there in your program, hope you understood.
T = 0
i = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
else:
i =i+1
x_int = int(x)
T += x_int
print(i, T)