I want to make a game that will generate multipication equations. I want to make it that you will get a simple multipication equation (ex: 5*6) and when you answer it, the program will tell you if you are correct, and then will go to the next random equation.
I know how to make it with a lot of different random numbers, but this will make the code very long and not ellegant.
I need a way to generate two different random numbers every time, without having to make a data base of let's say 20 different random numbers. Does anyone know how to do it?
Thanks!
This is the code I've wrote so far:
import random
import sys
import os
random_num1 = random.randrange(1, 10)
random_num2 = random.randrange(1, 10)
print(random_num1, 'X', random_num2, '=', )
def multiplication(random_num1, random_num2):
sumNum = random_num1 * random_num2
return sumNum
one = input()
if(int(one) == multiplication(random_num1, random_num2)):
print('true')
else:
print('false')
Put all of your code into a while loop that never ends using while True: (and don't forget to move everything inside by one tab to the right).
It's advisable to move def multiplication out of the while loop though.
You could easily do it with a function and a while loop. Let's say, you want to play 10 times and want the score at the end.
def multiplication(random_num1, random_num2):
sumNum = random_num1 * random_num2
# Indentation fixed
return sumNum
def play() :
random_num1 = random.randrange(1, 10)
random_num2 = random.randrange(1, 10)
print(random_num1, 'X', random_num2, '=', )
one = input()
if(int(one) == multiplication(random_num1, random_num2)):
return 1
else:
return 0
if __name__ == '__main__' :
number_of_play = 10
cpt = 0
result = 0
while cpt < number_of_play :
cpt+=1
cpt += play()
print "Wow you perform {} out of {}".format(result, number_of_play)
Here it is a simple example made by me (EDITED with "try" statement):
from random import randint
while 1:
numA = randint(0,9)
numB = randint(0,9)
result = numA * numB
print("\nFirst number:", numA)
print("Second number:", numB)
while 1:
try:
userResult = int(input("Insert your multiplication result: "))
break
except:
print("Error! The given digit is not a number. Retry :")
if userResult == result:
print("Bravo! That's right!")
else:
print("Damn! That's wrong!")
I've tried to be as clear as possible. I hope it was useful for you.
Related
I keep getting stuck in an infinite loop with this program. I know I need to assign separate values for each random number but I don't know how and my TAs aren't answering their emails. Here's my code:
import random
random_num = random.randint(0, 10) #generates random numbers between 0 and 10
user_input = input('Play again?(Y or N):')
while user_input != 'N':
print('Python Slot Machine')
print(random)
if random_num != random_num and random_num != random_num:
print('Uh oh! No match this time!')
print(user_input)
elif random_num == random_num and random_num != random_num:
print('You matched two! So close!')
print(user_input)
elif random_num == random_num and random_num == random_num and random_num == random_num:
print('Jackpot!! You matched all 3!')
print(user_input)
You are getting stuck in an infinite loops because your input function is outside of the loop, so the user never gets to decide whether they want to continue or not.
What you've done in your code above is generated a random number, and then made several references to that random number. Each time you place the variable randon_num into your function, it does not generate a new number. Instead, it keeps referencing back to when you defined random_num.
A simple way to do this would be to create a function that generates a random number so you don't have to copy the random.randint() code every time.
if else statments dont work the way you think they do.
If you have multiple loops, you can't check the value multiple times to address the loops. Also you checked random_num against random_num.
Let me show you another way to do this. Instead of giving the user a way to exit, have him play until the end. After 3 guesses it's game over anyways. For each time the user matched the random_number you give him a point.
You also have to refresh the random number after each try, otherwise it will stay the same. And as you show the number after a loop, the user knows the number from there on.
After three loops you end the while loop and print one of the messages from the messages list using the earned points as index for the list.
import random
points = 0
counter = 0
messages = [
'Uh oh! No match this time!',
'You only matched one',
'You matched two! So close!',
'Jackpot!! You matched all 3!'
]
while counter < 3:
random_num = random.randint(0, 10) # generates random numbers between 0 and 10
user_input = input('Please enter your guess: ')
print('Python Slot Machine')
print(f'random number: {random_num}')
if random_num == int(user_input):
points += 1
counter += 1
print(messages[points])
Your Logic don't make sense anyway. but, Correct structure is
import random
random_num = random.randint(0, 10)
while True:
user_input = input('Play again?(Y or N):')
if user_input == "Y":
#your code
#your code
#Your code
else:
print("User want to quit")
break
Your going to need to restart your project. You are telling the program to check if the same number equals the same number multiple times.
Ex. if the random number is 6, all of the random numbers are going to be 6.
You need to use the random.sample function in order to get multiple random numbers differently.
You also need to use functions in order to organize and optimize your code
Here is an example:
import random
random_num = random.sample(range(0,10),4)
#generates random numbers between 0 and 10
def playAgain():
user_input = input('Play again?(Y or N):')
if user_input.startswith('y'):
print('Python Slot Machine')
main()
else:
quit()
def main():
#your code
import random
import itertools as it
def guessthenumber():
play = input("do you want to play ?\nanswer yes or no :")
while play != "yes" :
if play == "no" :
quit()
else:
guessthenumber()
break
guessthenumber()
answer = random.randint(1, 5)
def random_func():
gusse = int(input("choose a number between 0 and 10"))
count = 3
while gusse != answer and count != 0 :
count -= 1
print(count)
print("wrong")
random_func()
break
random_func()
print("won")
Why does the guess count stop at 2 even with for loop?
The primary issue is as pointed out by #quamrana. When you call random_func you are adding a new stack frame that has a new count variable initialized to 3, so it immediately decrements, but then you add another call to random_func. You never return and pop this call off the stack, so there is no way to continue.
I don't see why ask if the caller wants to play. If it is the only thing the program does, running it is a pretty good indication. Also, is "gusse" a thing or just a misspelling of "guess".
You should avoid using quit() unless you are in an interpreter. You can use sys.exit, but in simple scenarios like this, returning and finishing the program is more simple.
Consider the following implementation with some slight improvements.
import random
def start(answer, tries):
while tries: # Continue while tries remain.
guess = int(input("choose a number between 0 and 10: "))
if guess == answer:
print("won")
return # Just return from the function.
tries -= 1 # Otherwise, decrement and continue.
print(f"wrong; tries remaining: {tries}")
if __name__ == "__main__":
answer = random.randint(1, 5)
start(answer, 3) # Begin the guessing part of the game.
The code creates a random addition problem and spits out "Congratulations" if correct and "sorry...." if the inputted value is wrong. The while loop repeats this process until the user inserts "N" for the question "continue (Y/N):, at the same time it keeps track of how many questions have been answered, and which ones are correct. The code works fine, my problem is it has repetitive code. I was wondering if there is a way to shrink it.
**I appreciate everyone one's help and advice. I"m a noob that's just learning python **
import random
correct=0
count=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
A first start, would be eliminating the code before the while, by initializing the count variable (which keeps track of the turns), in zero, and allowing the while loop to run the first turn, we just need to have a variable like want_to_play and by default it's True, so the first time we'll be playing, and at the end of the game If I don't input Y or y it will asume I don't want to play any more and set the variable to false, that way I can have all the turns ran by the while loop.
and you'll be getting something like this.:
from random import sample
correct = 0
count = 0 # STartint in turn zero
want_to_play = True # Control Variable
while want_to_play:
count += 1
# First turn this is zero, and adds one.
[num1, num2] = sample(range(0, 101), 2)
# Just another way of getting two random numbers from 1 up to (including) 100.
# Printing could be done in one line.
print(format(num1, '5d') + '\n+' + format(num2, '4d'))
answer = int(input('= '))
# The comparison really doesn't really hurt if you do it this way.
if answer == num1 + num2:
print('Congraulations!')
correct += 1
else:
print('Sorry the correct answer is', sum)
# HERE you ask if you want to play again or not, using a one line if
# you decide.
want_to_play = (True if 'y' == input('Continue (Y/N).lower():')
else False)
else:
print('Your final score is',correct,'/',count)
By initializing the variable c as "Y", the condition is met and the loop can be executed:
import random
correct=0
count=1
c = "Y"
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
c = c.upper()
else:
print('Your final score is',correct,'/',count)
I also added the method upper() to the Y/N input so the user can also type it in lowercase
Try to move as much of the processing as possible into the loop. The first "paragraph" of your code was basically a duplicate of the main-loop. By creating the continuation variable c so that it drops straight into the loop, most of that first block could be removed.
import random
correct=0
count=0
c = 'Y'
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congratulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
The two formula printing statements can also be reduced to a single one:
print(format(num1,'4d'))
print('+',num2)
could be
print( format(num1,'4d') + '+', num2 )
The variable sum could be removed, but it does make the code self-documenting, which is a good thing.
`So I am just making something to test if I can make certain outputs based on inputs
Each time I try to enter an answer, nothing happens here
I used if elif statements with the in range() in them.
Nothing shows up when I type the answer
from random import randint
from termcolor import colored
repeat = True
from termcolor import colored
import time
import sys
import multiprocessing
print colored("Hello, this is a program to help you practice algebraic
expressions.","magenta")
print("")
time.sleep(4)
print colored("Alright let's start with something very basic...\nWhat is x
if
2x
= 32?","magenta")
prob = int(raw_input())
if int(prob) in range (16, 16):
print colored("Well done, you got the warmup correct","yellow")
elif int(prob) in range(1, 15):
print colored("Incorrect answer try again","red")
This line if int(prob) in range(16,16): is problem. Function range(x,y) generates list equals to [x,y), which means starting with x and including x, ending with y excluding y, so by that, you are asking if your number is in empty array.
Example:
list_of_numbers = range(12,16) gives us list with elements list_of_numbers = [12,13,14,15]
I have written this code removing all the functions that you haven't used and the coloured text which seemed to always error. range is generally used in "for" loops but in conditionals you need to use == if it is equal to > for greater than < less than != not equal to e.t.c.
import time
print ("Hello, this is a program to help you practice algebraic
expressions.")
print("")
time.sleep(4)
prob =int (input("Alright let's start with something very basic What is
x if 2x = 32? "))
if prob ==16:
print("Well done, you got the warmup correct")
else:
print("Incorrect answer try again")
`
I am currently working on a battleship game to practice my programming skills. I have functional code but was wondering if anyone can help me break my code down into a for loop?
import random
def main():
board = []
for i in range(0,5):
board.append(random.randint(1,50))
print(board) #test purposes
guess=int(input("enter number between 1-50"))
if guess == board[0]:
print("hit")
board[0]="hit"
elif guess != board[0]:
print("miss")
board[0]="miss"
Note i want to carry out the if statement multiple times to check for board[0-5].
Instead of repeating it 5 times I was thinking of doing something like this:
for x in range(0,5):
if guess == board[x]:
print("hit")
board[x]="hit"
else:
print("miss")
board[x]="miss"
But this is not working as it takes just 1 input whereas I want it to take 5. For each input it has to check if input is equal to board[0-5]
Thank You in advance for any help.
write guess in a for loop,be careful about indentation
import random
def main():
board = []
for i in range(0, 5):
board.append(random.randint(1, 50))
guess = int(input("enter number between 1-50 : "))
print(board) # test purposes
if guess == board[0]:
print("hit")
board[0] = "hit"
elif guess != board[0]:
print("miss")
board[0] = "miss"
I'm not quite sure what you are trying to achieve, but I believe it to be this:
import random
def main():
board = []
for i in range(0,5):
board.append(random.randint(1,50))
print(board) #test purposes
guesses = []
try_nr = 0
while try_nr < 5:
try_nr += 1
guess = int(input("enter number between 1-50"))
guesses.append(guess)
for i in enumerate(guesses):
i = i[0]
if guesses[i] in board:
print("hit")
# board[0]="hit" --> not quite sure what you want to achieve here?
else:
print("miss")
# board[0]="miss" --> not quite sure what you want to achieve here?
NB1: There are other more neat/dense ways to code this, but this helps you to get going. See if you can perfect it for yourself if needed.
NB2: I have changed your elif statement into else. Your equation can only have two possible answers (either a hit or a miss). By using elif you are forcing python to reconsider/re-calculate your if-statement fully while using else it only considers the if-statement once.
You can use the enumerate() function to add a counter to your for loop. This will be useful.
board = [12, 4, 76, 2]
for index, number in enumerate(board):
print index, number
#output
# 0 12
# 1 4
# 2 76
# 3 2
You said you want to take 5 guesses? You could do something like this:
for i in range(5):
guess=int(input("enter number between 1-50"))
for index, number in enumerate(board):
if guess == number
print("hit")
board[index] = "hit"
else:
print("miss")
board[index] = "miss"