So i've set myself the goal of learning programming with Python. I've started about 3 days ago and decided to start with a random number generating game as a starting Project.
The problem i have with my code is that my make_try method isn't giving me the right outputs. It just always goes with the else statement, even if the comparison in the if statement should be right. I personally am very frustrated right now and i hope you can help me.
Greetings Marc
import random
class Test:
def __init__(self):
self.number1 = random.randrange(1, 20)
self.score = 100
def first_tip(self):
print(self.number1)
if(self.number1 % 2 == 0 and self.number1 <= 10):
print("Your number is even and smaller than 10")
elif(self.number1 % 2 == 0 and self.number1 >= 10):
print("Your number is even and bigger than 10")
elif(self.number1 % 2 != 0 and self.number1 <= 10):
print("Your number is uneven and smaller than 10")
elif(self.number1 % 2 != 0 and self.number1 >= 10):
print("Your number is uneven and bigger than 10")
def make_try(self):
print("My guess would be:")
testguess = input()
if(self.number1 == testguess):
new_score = self.score + 100
print("*****************")
print("*Congratulations*")
print("*****************")
print(f"Your final score: {new_score}")
else:
new_score = self.score -10
print("Wrong!")
print(f"Your new score: {new_score}")
x = input("Try again?(Yes/No)")
print(x)
if __name__ == "__main__":
T1 = Test()
T1.first_tip()
T1.make_try()
You have different types in your comparison
testguess = input() means that testguess is a string
self.number1 = random.randrange(1, 20) means that self.number1 is an integer
simplest way to fix this is by: testguess = int(input())
Problem is input types, thats why as a newbie I would probably recommend C# or C++ bc you have more or total control over your types,
To fix this problem of your I simply added a cast to this line, and it works properly
if(self.number1 == int(testguess)):
Related
Looking on for some guidance on how to write a python code
that executes the following:
The program will ask for math problems to solve.
The program will asks for the number of problems.
And asks for how many attempts for each problem.
For example:
Enter amount of programs: 4
Enter amount of attempts: 5
what is: 4x3 =?
Your answer: 16
and so goes on to another attempt if wrong if correct moves onto another problem, just like before and exits when attempts or problems are finished.
I have this code but I want to it only do multiplication ONLY and would like to know how to integrate how to put additional code to limit how many time one can solve the question and how many questions it asks
import random
def display_separator():
print("-" * 24)
def get_user_input():
user_input = int(input("Enter your choice: "))
while user_input > 5 or user_input <= 0:
print("Invalid menu option.")
user_input = int(input("Please try again: "))
else:
return user_input
def get_user_solution(problem):
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
return result
def check_solution(user_solution, solution, count):
if user_solution == solution:
count = count + 1
print("Correct.")
return count
else:
print("Incorrect.")
return count
def menu_option(index, count):
number_one = random.randrange(1, 21)
number_two = random.randrange(1, 21)
problem = str(number_one) + " + " + str(number_two)
solution = number_one + number_two
user_solution = get_user_solution(problem)
count = check_solution(user_solution, solution, count)
def display_result(total, correct):
if total > 0:
result = correct / total
percentage = round((result * 100), 2)
if total == 0:
percentage = 0
print("You answered", total, "questions with", correct, "correct.")
print("Your score is ", percentage, "%. Thank you.", sep = "")
def main():
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
main()
As far as making sure you're only allowing multiplication problems, the following function should work.
def valid_equation(user_input):
valid = True
for char in user_input:
if not(char.isnumeric() or char == "*"):
valid = False
return valid
Then after each user_input you can run this function and it will return True if the only things in the users string are numbers and the * sign and False otherwise. Then you just need to check the return value with a if statement that tells the user that their input is invalid if it returns False. You can add more "or" operations to the if statement if you want to allow other things. Like if you want to allow spaces (or char == " ").
As far as limiting the number of times a user can try to answer, and limiting the number of questions asked, you just need to store the values the user enters when you ask them these numbers. From there you can do nested while loops for the main game.
i = 0
user_failed = False
while ((i < number_of_questions) and (user_failed == False)):
j = 0
while ((j < number_of_attempts) and (user_correct == False)):
#Insert question asking code here
#In this case if the user is correct it would make user_correct = True.
j += 1
if j == number_of_attempts:
user_failed = True
i += 1
So in this situation, the outer while loop will iterate until all of the questions have been asked, or the user has failed the game. The inner loop will iterate until the user has used up all of their attempts for the question, or the user has passed the question. If the loop exits because the user used up all of their attempts, the for loop will trigger making the user lose and causing the outer loop to stop executing. If it does not it will add one to i, saying that another question has been asked, and continue.
These are just some ideas on how to solve the kinds of problems you're asking about. I'll leave the decision on how exactly to implement something like this into your code, or if you decide to change parts of your code to better facilitate systems like this up to you. Hope this helps and have a great one!
gone = []
turn = 0
def play(XO,player):
while 0 == 0:
num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
while ((str(num).isdigit() == False) or ((int(num) <= 9 and int(num) >= 1) == False)) or (num in gone):
num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
So, in the second while loop I'm having a problem. You see the (num in gone) part? I'm trying to make it so if num is found in the gone list then it will be true, but it isn't working. Instead it passes through it.
I've tested to see if (not num in gone) applies the opposite effect, and it does!
If you need to see my entire code I can post it... btw this is for a Tic-Tac-Toe program I am making.
You're putting too much logic in one condition. Splitting it up will help you a lot.
Try something like this:
gone = []
turn = 0
def play(XO, player):
while True:
num = input(
f"\n{player} enter an available number "
f"where you want to put an '{XO}'.\n > "
)
try:
num = int(num)
except ValueError:
print("Not a valid number, try again")
continue
if num < 1 or num > 9:
print("Number not in correct range, try again")
continue
if num in gone:
print("Number already gone, try again")
continue
gone.append(num)
turn += 1
I'm very new to programming and I've encountered a problem with a basic guessing game I've been writing.
x is a random number generated by the computer. The program is supposed to compare the absolute value of (previous_guess - x) and the new guess minus x and tell the user if their new guess is closer or further away.
But the variable previous_guess isn't updating with the new value.
Any help would be appreciated.
Here is the code so far:
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
while True:
previous_guess = 0 # Should update with old guess to be compared with new guess
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Your previous guess is being reinitialized every time you loop. This is a very common error in programming so it's not just you!
Change it to:
previous_guess = 0
while True:
#Rest of code follows
Things you should be thinking about when stuff like this shows up.
Where is your variable declared?
Where is your variable initialized?
Where is your variable being used?
If you are unfamiliar with those terms it's okay! Look em up! As a programmer you HAVE to get good at googling or searching documentation (or asking things on stack overflow, which it would appear you have figured out).
Something else that is critical to coding things that work is learning how to debug.
Google "python debug tutorial", find one that makes sense (make sure that you can actually follow the tutorial) and off you go.
You're resetting previous_guess to 0 every time the loop begins again, hence throwing away the actual previous guess. Instead, you want:
previous_guess = 0
while True:
guess = ....
You need to initialize previous guess before while loop. Otherwise it will be initialized again and again.
You have updated previous guess in multiple places. You can make it simpler:
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = 0 # Should update with old guess to be compared with new guess
while True:
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
print("Getting warmer...")
else:
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
previous_guess = guess #####
You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this:
Add before while { previous_guess = x }
Add After While { previous_guess += x }
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = x
while True:
# Should update with old guess to be compared with new guess
previous_guess += x
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Picture When u win
Picture When u loose
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if userInput > randomNumber:
print("Guess lower.")
elif userInput < randomNumber:
print("Guess Higher.")
else:
print("You got it!")
break
So this code currently takes the user input and says whether the user guessed the random integer, or if they should guess higher/lower. I want to edit the code to now say whether the user input is within 5,10,15, etc of the random integer.
So if the random integer was 30, and the user inputs 20, the program would say something like "You are within 10; guess higher."
Any advice? I'm extremely new to python, so please respond with more simple methods if possible.
Thanks.
PS: Oh, preferably without the use of modules, mainly because I'm still learning.
I think this does what you want, and it cuts down on the if chains a little:
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
break # We use break b/c changing correct would still run rest of loop
acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
guess_error = userInput - randomNumber
i = 0
while abs(guess_error) > acceptable_ranges[i]: # see how close they are
i += 1
if guess_error < 0: # let's figure out where they need to go
next_guess_direction = "higher"
else:
next_guess_direction = "lower"
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
Let's look. at the last if statement a little further and the final print line. We are checking to see if guess_error, defined above (line 15) guess_error = userInput - randomNumber is less than 0 (negative). If it is less than zero, then we make the variable next_guess_direction equal to the string "higher," because the next guess needs to be larger than the last one (randomNumber was larger than userInput. If guess_error is not negative, then it is positive, because we already eliminated the we eliminate the possibility of 0 using:
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
So, if guess_error is positive, we know that userInput was larger than randomNumber and we set next_guess_direction equal to the string "lower." Finally, we print out everything that we have found:
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
I am using an older version of formatting where %i and %s are placeholders for integer and string, respectively. I then define what should be formatted there using %(acceptable_ranges[i], next_guess_direction), which simply means to put acceptable_ranges[i] in for the integer and next_guess_direction in for the string. Keep in mind, we found i in acceptable_ranges[i] right above the if statement.
I know that is all long, but I did not know how much detail you needed!
Update: I see you ask to do it without modules. Here's a solution:
def ceil(xx):
if int(xx) < xx:
return int(xx) + 1
else:
return int(xx)
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / float(interval)
within = ceil(abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
-- original answer:
You can do this with numpy's ceil function.
For instance:
import numpy as np
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / np.float(interval)
within = np.ceil(np.abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
A solution using the modulo operator:
import random
randomNumber = random.randint(0,100)
def guess(divisor = 5):
while 1:
try:
print("Pick a number from 0-100")
userInput = int(input("Insert your number here: "))
except ValueError:
print("That is not a Number!")
continue
delta = randomNumber - userInput
if delta == 0:
print("You got it!")
return
remainder = delta % divisor
# this takes advantage of python truncating non-floating point numbers
rounded_delta = (abs(delta) / divisor) * divisor + divisor * bool(remainder)
high_or_low = 'higher' if delta > 0 else 'lower'
print("You are within %s. Guess %s." % (rounded_delta, high_or_low))
I am a beginer programming Python and for a evaluation assignment I was asked to program a Bulls and Cows game using very simple code.
I have some code already written, but can't seem to make the function work. The function should be able to compare the four digit number the user wrote (num_guess) to the random number generated by the program (stored in a list called num).
I can input the value, but have no further feedback from the program.
Could you please check my code and help me?
Thanks!
import random
guess = raw_input("What is your guess? ")
if (len(guess) != 4):
guess = raw_input("Your guess must be 4 characters long! What is your guess?")
num_guess = []
for c in guess:
num_guess.append(int(c))
def compare(num_guess):
num = []
for i in range(4):
n = random.randint(0, 9)
while n in num:
n = random.randint(0, 9)
num.append(n)
if num_guess == num:
print "Congratulations! Your guess is correct"
output = []
if num_guess[0] == num [0]:
output.append["B"]
else:
output.append["C"]
if num_guess[1] == num [1]:
output.append["B"]
else:
output.append["C"]
if num_guess[2] == num [2]:
output.append["B"]
else:
output.append["C"]
if num_guess[3] == num [3]:
output.append["B"]
else:
output.append["C"]
return output
nguesses = 0
while nguesses < 11:
nguesses = nguesses + 1, compare
Without giving you the corrected code you will want to call the function at the end of your code. If you want to see result do:
print compare(num_guess)
This will show you an additional issue with all of these parts
output.append[]
I'm not sure if it is just how you pasted it but you may want to clean up the indentation. Also:
while n in num:
n = random.randint(0, 9)
This above section is not needed. Have fun and figure out how to make it work well.