Mathematic questions in python - python

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!

Related

While loop is not exiting even though variable is being updated [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create a simple guessing game. Everything works absolutely fine, as it should. But, it can't seem to exit the first while loop which checks if the variable 'guessflag' is less than 15 or not. I also checked whether it is being updated or not by adding some print statements. Please help.
It even exits when it meets the condition which says to exit the program when the user guesses correctly. When I consulted some other queries regarding the same problem at stackoverflow, I tried to make sure that those mistakes don't happen to me. Also, I have to add some more finishing touches to reduce time taken by the program to run, but currently this works absolutely fine.
import random
point = 101
randomint = random.randint(0,100)
hintflag = 0
hintmessage = "To claim a hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***"
guessflag = 0
while guessflag <=15:
def init(param):
global guess, point, guessflag
if(param == 1):
global point,guessflag
point = point - 1
guessflag = guessflag + 1
print(hintmessage)
guess = int(input("Enter your guess. It should be between 1 and 100... "))
proceed()
def proceed():
global hintflag
global point
if (guess < 1 or (guess > 100 and guess != 102)):
print('')
print("Please enter a number between 1 and 100... ")
init(2)
elif ((guess == 102)and(hintflag < 2 and hintflag >= 0)):
if(hintflag == 0):
checkrandeven()
if(hintflag == 1):
checkrandmultiple3()
else:
match()
def checkrandmultiple3():
if (randomint % 3 == 0):
global israndmultiple3, point, hintmessage, hintflag
hintflag = hintflag + 1
israndmultiple3 = True
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is a multiple of 3.")
print("Points: "+str(point))
init(2)
else:
hintflag = hintflag+1
israndmultiple3 = False
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is not a multiple of 3.")
print("Points: "+str(point))
init(2)
def checkrandeven():
if (randomint % 2 == 0):
global israndeven, point, hintmessage, hintflag
hintflag = hintflag+1
israndeven = True
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print('')
print("Your hint is...")
print("The number to be guessed is even.")
print("***YOU HAVE SPENT 20 POINTS***")
print("Points: "+str(point))
init(2)
else:
israndeven = False
hintflag = hintflag+1
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print("The number to be guessed is odd.")
print("Points: "+str(point))
init(2)
def match():
global randomint, guess, point, guessflag, hintflag
if(randomint != guess):
if(randomint < guess):
print("Try Again! Your number was too high; Try a number lower than "+str(guess))
init(1)
if(randomint > guess):
print("Try Again! Your number was too low; Try a number higher than "+str(guess))
init(1)
if(randomint == guess):
print ("CONGRATULATIONS! You won!")
print ("It took you "+ str(guessflag) + " tries, "+ str(hintflag)+" hints to beat the game!")
print("The number of points you finished with are... "+ str(point))
exit()
init(1)
The 'init(1)' call in your while loop is only actually called once, and your 4 functions call each other recursively. In other words, you never actually finish the first iteration of your while loop, you just go further and further down a chain of:
init -> proceed -> checkrandeven (or checkrandmultiple3) -> init -> proceed -> checkrandeven -> init -> proceed ...
Basically you need to think about restructuring your code to avoid the recursion. Try returning outputs within the main loop and then calling subsequent functions from there.

I got stuck on this exercise can't figure the True/False part

I got some homework to do and I got stuck with this code. I have no idea how to continue.
This is what I'm suppose to do:
generate_sequence - Will generate a list of random numbers between 1 to 101. The list
length will be difficulty.
get_list_from_user - Will return a list of numbers prompted from the user. The list length
will be in the size of difficulty.
is_list_equal - A function to compare two lists if they are equal. The function will return
True / False.
play - Will call the functions above and play the game. Will return True / False if the user
lost or won.
(Sorry for copy/pasting. My English is not so good.)
import random
difficulty = 101
secret_number = 6
def generate_number():
global secret_number
secret_number = random.randint(0, difficulty)
def get_guess_from_user():
return input( "Please choose number between 1 to " + str(difficulty))
def compare_results(userInput):
isSame = False
if(secret_number == userInput):
isSame = True
return isSame
def play():
generate_number()
userInput = get_guess_from_user()
isSame = compare_results(userInput)
print("number generated is: " + str(secret_number))
print(isSame)
play()
Your "problem" is, that if(secret_number == userInput): is currently comparing an int to a str, because the result of input() is always a str, even if the input is numeric. An int and a str are never equal, thus isSame will always be False.
You have to cast the user input to int somewhere along the way before or during the comparison.
e.g.:
def get_guess_from_user():
return int(input( "Please choose number between 1 to " + str(difficulty)))
# ^^^
Otherwise, your program seems to do what you are describing.
You could save some lines of code by writing:
def compare_results(userInput):
return (secret_number == userInput)
I took the liberty to rewrite your application w/o global variables:
import random
def generate_number(difficulty):
return random.randint(1, difficulty)
def get_guess_from_user(difficulty):
return int(input( "Please choose number between 1 to {}".format(difficulty)))
def play(difficulty):
secret_number = generate_number(difficulty)
user_input = get_guess_from_user(difficulty)
is_same = (secret_number == user_input)
print("number generated is: {}".format(secret_number))
print("Your guess was {}".format( "correct :)" if is_same else "not correct :(" ))
play(5)
Note: I also changed random.randint(0, difficulty) to random.randint(1, difficulty), because the lower part is also inclusive, meaning that it could return 0. When prompting the user for a number between 1 and 5, the user might be surprised that the correct number was 0 instead.
See the docs:
random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

Skipped If Statement/unstripped input data in Python

I'm updating a crack the code game I made in Python so that you can play a single-player game against the computer. For some reason, the interpreter either doesn't use the data stripped from the input used to determine player count or skips the if statement that uses the stripped data from the input. Either way, after you input the player number it goes straight to the guessing code with an empty list of correct code characters.
My code for the player count determining and code creation is:
plyrs = 0
correctanswer = []
print('Welcome!')
plyrs = str(input('How many players are there? (minimum 1, maximum 2) '))
if plyrs == 2:
print("I'm gonna ask you for some alphanumerical (number or letter characters to make a code for the other player to guess.")
input('Press enter when you are ready to enter in the code!') #Like all of my games, it has a wait.
i = 0
while i < 4:
correctanswer.append(input('What would you like digit ' + str(i + 1) + " to be? "))
i = i + 1
print("Ok, you've got your code!")
i = 0
while i < 19: #Generates seperator to prevent cheating
print('')
i = i + 0.1
print("Now, it's the other player's turn to guess!")
elif plyrs == 1:
import random
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
i = 0
while i < 4:
correctanswer.append(characters[randint(0,36)])
i = i + 1
print('Time for you to guess!')
print('')
No other skipping if statement questions apply to this so please help.
plyrs is a string, and you're comparing it to an int. "2" == 2 will always be false. Same with plyrs == 1, this will be false throughout.

How to get python to go back to start of loop and not use random?

I'm a bit new to python and was giving myself a task, I wanted a number guessing game that gets you to guess four numbers and the program will keep telling you how many numbers you guess right till you guess the full list of numbers.
running = True
import random
def compareLists(a, b):
return list(set(a) & set(b))
def start():
rNums = random.sample(range(10), 4)
gNums = []
print("Get ready to guess 4 numbers!")
for i in range(0, 4):
x = int(input("Guess: "))
gNums.append(x)
print("You guessed: ", gNums)
comparison = len(compareLists(rNums, gNums))
while gNums and rNums:
if gNums != rNums:
print("You guessed " + str(comparison) + " numbers right, keep guessing!")
break
elif gNums == rNums:
print("What amazing luck!")
while running:
start()
The problem is that when I use a break a new list of 4 numbers is created, I want python to just go back to the start of the loop and not make a whole new list!
You want to use continue. Try it with a toy example:
i = 0;
while i < 10:
i += 1
if i % 2 == 0:
continue
print i
Output:
1
3
5
7
9
You can put the
rNums = random.sample(range(10), 4)
outside the loop and pass rNums to start. This way you will have the same four numbers in the list. Hope this helps
For the sake of minimizing the amount of loops going on in your code, I would probably first pop your random numbers in a dictionary.
Something like this (probably more efficient way of doing this...but it's the first thing that popped in my head):
from collections import Counter
d = Counter(random.sample(range(10), 4))
Start your while loop, and keep asking the user to guess. Every time they make a right guess, just perform this operation:
d.pop(correctly_guessed_num)
Once your dictionary is empty, you are done and you break the loop.
EDIT adding my quick stab at the implementation. Not fully thought through, might be some edge cases that break this...but this is the overall idea. Hope it helps.
from collections import Counter
import random
d = Counter(random.sample(range(1, 10), 4))
size = len(d) - 1
while True:
x = int(input("Guess: "))
if size == 0:
print("you guessed them all, way to go")
break
if x not in d:
print("keep going buddy")
continue
else:
d.pop(x)
size -= 1
print("A right guess")

inconsistent string to int error and response

I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P

Categories

Resources