So I can't really figure out why the variables "first" and "second" aren't defined even when returning them it doesn't work maybe I'm doing it wrong I honestly have no clue.
The assignment is to make a times table tester using only functions to give us an understanding of functions.
My teacher gave us what the functions are supposed to do so I will put these below.
def results_summary(right, answered):
""" right is int for number of correct questions
answered is int rep. total number of questions
display results of practice with ratio
and percentage correct """
def generate_question():
""" generate and display a random multiplication
questions with factors from 1 to 12
return the answer as an integer value """
def get_answer():
""" display = to prompt user to enter answer
returns input if valid integer entry is made
displays message and new prompt for invalid entry """
def goAgain():
""" Asks the user y/n if they want another question
returns True for 'y' and False for 'n'
displays message and new prompt for invalid entry """
Any help would be greatly appreciated!
import random
#defines important functions
def results_summary(num_correct, num_question):
percentage = num_correct / num_question * 100
correctCount = str(num_correct)
questionCount = str(num_question)
percentage = str(round(percentage))
print('You got ' + correctCount + '/' + questionCount + ' (' + percentage + '%).')
def generate_question():
first = random.randint(1,12)
second = random.randint(1,12)
correct_answer = second * first
return correct_answer
def get_answer():
try:
user_answer = input('What is ' + first + ' x ' + second + '?')
except ValueError:
print('Please Enter Integers Only.')
def goAgain():
input('Do you want another question? (y / n)')
try:
'y' == True
'n' == False
except ValueError:
print('Please Enter a valid response. (y / n)')
#MAIN PROGRAM
num_correct = 0
num_question = 0
#creates while loop to continuously ask questions
while True:
correct_answer = generate_question()
user_answer = get_answer()
#prints if the user answers correctly
if user_answer == correct_answer:
print('Correct')
num_question += 1
num_correct += 1
again = goAgain()
if goAgain == False:
break
results_summary(num_correct, num_question)
I'm so sorry budd :(
I got no time to explain ... [I'm in a hurry] but I don't want you to get disrespect from your teacher !, I been there :/
So here is the modified working code , hope it helps :)
import random
#defines important functions
def results_summary(num_correct, num_question):
percentage = (num_correct / num_question) * 100
print(f"You got {round(percentage)} %")
def generate_question():
global first
global second
first = random.randint(1,12)
second = random.randint(1,12)
correct_answer = second * first
return correct_answer
def get_answer():
try:
user_answer = int(input('What is ' + str(first) + ' x ' + str(second) + '?'))
return user_answer
except ValueError:
print('Please Enter Integers Only.')
def goAgain():
confo = input('Do you want another question? (y / n)')
if confo.lower() == 'y':
return True
elif confo.lower() == "n":
return False
else:
return
#MAIN PROGRAM
num_correct = 0
num_question = 0
#creates while loop to continuously ask questions
while True:
correct_answer = generate_question()
user_answer = get_answer()
#prints if the user answers correctly
if user_answer == correct_answer:
print('Correct')
num_question += 1
num_correct += 1
else:
num_question += 1
print("Wrong answer")
again = goAgain()
if again:
pass
else:
print("Have a great day!, bye")
break
if goAgain == False:
break
results_summary(num_correct, num_question)
The error shows variables first and second to be undefined because the variables you are using in:
user_answer = input('What is ' + first + ' x ' + second + '?')
command inside the get_answer() function, are undefined.
In order to use these variables, just change the function generate_question() to:
def generate_question():
global first, second
first = random.randint(1,12)
second = random.randint(1,12)
correct_answer = second * first
return correct_answer
and change the input command inside get_answer() function to:
user_answer = input('What is ' + str(first) + ' x ' + str(second) + '?')
Related
I am trying to limit the attempts in a quiz I am making, but accidentally created an infinte loop. What am I doing wrong here?
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(guess, answer):
global score
still_guessing = True
attempt = 3
while guess == answer:
print('That is the correct answer.')
score += 1
still_guessing = False
else:
if attempt < 2:
print('That is not the correct answer. Please try again.')
attempt += 1
if attempt == 3:
print('The correct answer is ' + str(answer) + '.')
guess_1 = input('Where was Hitler born?\n')
check_questions(guess_1, 'Austria')
guess_2 = int(input('How many sides does a triangle have?\n'))
check_questions(guess_2, 3)
guess_3 = input('What is h2O?\n')
check_questions(guess_3, 'water')
guess_4 = input('What was Germany called before WW2?\n')
check_questions(guess_4, 'Weimar Republic')
guess_5 = int(input('What is the minimum age required to be the U.S president?\n'))
check_questions(guess_5, 35)
print('Thank you for taking the quiz. Your score is ' + str(score) + '.')
Here is how you should handle it. Pass both the question and the answer into the function, so it can handle the looping. Have it return the score for this question.
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(question, answer):
global score
for attempt in range(3):
guess = input(question)
if guess == answer:
print('That is the correct answer.')
return 1
print('That is not the correct answer.')
if attempt < 2:
print('Please try again.')
print('The correct answer is ' + str(answer) + '.')
return 0
score += check_questions('Where was Hitler born?\n', 'Austria')
score += check_questions('How many sides does a triangle have?\n', '3')
score += check_questions('What is H2O?\n', 'water')
score += check_questions('What was Germany called before WW2?\n', 'Weimar Republic')
score += check_questions('What is the minimum age required to be the U.S president?\n', '35')
print(f"Thank you for taking the quiz. Your score is {score}.")
I'm very new to programming and am starting off with python. I was tasked to create a random number guessing game. The idea is to have the computer guesses the user's input number. Though I'm having a bit of trouble getting the program to recognize that it has found the number. Here's my code and if you can help that'd be great! The program right now is only printing random numbers and won't stop even if the right number is printed that is the problem
import random
tries = 1
guessNum = random.randint(1, 100)
realNum = int(input("Input a number from 1 to 100 for the computer to guess: "))
print("Is the number " + str(guessNum) + "?")
answer = input("Type yes, or no: ")
answerLower = answer.lower()
if answerLower == 'yes':
if guessNum == realNum:
print("Seems like I got it in " + str(tries) + " try!")
else:
print("Wait I got it wrong though, I guessed " + str(guessNum) + " and your number was " + str(realNum) + ", so that means I'm acutally wrong." )
else:
print("Is the number higher or lower than " + str(guessNum))
lowOr = input("Type in lower or higher: ")
lowOrlower = lowOr.lower()
import random
guessNum2 = random.randint(guessNum, 100)
import random
guessNum3 = random.randint(1, guessNum)
while realNum != guessNum2 or guessNum3:
if lowOr == 'higher':
tries += 1
import random
guessNum2 = random.randint(guessNum, 100)
print(str(guessNum2))
input()
else:
tries += 1
import random
guessNum3 = random.randint(1, guessNum)
print(str(guessNum3))
input()
print("I got it!")
input()
How about something along the lines of:
import random
realnum = int(input('PICK PROMPT\n'))
narrowguess = random.randint(1,100)
if narrowguess == realnum:
print('CORRECT')
exit(1)
print(narrowguess)
highorlow = input('Higher or Lower Prompt\n')
if highorlow == 'higher':
while True:
try:
guess = random.randint(narrowguess,100)
print(guess)
while realnum != guess:
guess = random.randint(narrowguess,100)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
elif highorlow == 'lower':
while True:
try:
guess = random.randint(1,narrowguess)
print(guess)
while realnum != guess:
guess = random.randint(1,narrowguess)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
This code is just a skeleton, add all of your details to it however you like.
Below I have created a Maths quiz in python. It consists of random equations to solve. The questions are generated using random numbers and functions that determine whether the question is add or subtract. I have completed the quiz, but I have tried adding a score counter so that if the user gets a question right, a point is added on. I am unsure how to do this, as I have tried implementing the score into the functions and it does not work. Here is the code:
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
questions = 0
a = random.randint(1,12)
b = random.randint(1,12)
def add(a,b):
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect! The answer is", result)
else:
print("Correct")
def multiply(a,b):
score = 0
multQ = int(input(str(a) + "X" + str(b) + "="))
results = int(int(a) * int(b))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
print("Correct")
def subtract(a,b):
subQ = int(input(str(a) + "-" + str(b) + "="))
resultss = int(int(a) - int(b))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
print("Correct")
for questions in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(random.randint(1,12), random.randint(1,12))
questions += 1
if questions == 10:
print ("End of quiz")
You can return a score for each task. An example for the add function:
if addQ != result:
print ("Incorrect! The answer is", result)
return 0
else:
print("Correct")
return 1
Of course you can give higher scores for more difficult tasks (e.g. 2 points for multiplications).
and then below:
score = 0
for questions in range(10):
Qlist = [add, subtract, multiply]
score += random.choice(Qlist)(random.randint(1,12),random.randint(1,12))
questions += 1
Use a global var and add +1 on every correct solution. The only negative is as soon as the programm is closed the score is lost.
something like this
You missed to define score globally and then access it within the function and updating it, Here's a working version:
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
score = 0
questions = 0
a = random.randint(1,12)
b = random.randint(1,12)
def add(a,b):
global score
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect! The answer is", result)
else:
score += 1
print("Correct")
def multiply(a,b):
global score
multQ = int(input(str(a) + "X" + str(b) + "="))
results = int(int(a) * int(b))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
score += 1
print("Correct")
def subtract(a,b):
global score
subQ = int(input(str(a) + "-" + str(b) + "="))
resultss = int(int(a) - int(b))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
score += 1
print("Correct")
for questions in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(random.randint(1,12), random.randint(1,12))
questions += 1
if questions == 10:
print ("End of quiz")
print('Score:', score)
Using return values of your functions as demonstrated by cello would be my first intuition.
But since you are already using a global variable to track your questions, you can introduce another one for the score.
questions = 0
score = 0
a = random.randint(1,12)
b = random.randint(1,12)
To use it (and not a local variable score, which would be only available in the function), your functions have to reference it by using globals:
def add(a,b):
global score
You can then increment it in the else-statements of your functions:
else:
print("Correct")
score += 1
At the end, you can print the score:
print("End of quiz")
print("Your score:", score)
Notice, that you are using questions variable in a strange fashion:
You first initialize it with 0:
questions = 0
Then you overwrite it during a loop:
for questions in range(10):
questions += 1
The for will give questions the values 0..9, so it is totally unneccessary to increase the number manually inside the loop. This increased value will immediately be overwritten by the next value of the loop.
After your loop exits, you are sure to have asked 10 questions. The following if-condition is superfluous (and only works, because you additionally increase questions in the loop). Just lose it:
print("End of quiz")
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having an issue with my decryption algorithm. It outputs to a text file a huge list of repeated ((((( and other things. What's wrong with my code, and how can I fix it? I think it has something to do with the last function of the decrypting process. But I am not sure.
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&()-_=+[]{}\\|;:\'",./<>?\n\t '''
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (evenChars >(oddChars)):
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
for ch in text: #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(ch)
else:
oddNums.append(ch)
index += 1
decrypted= []
if (evenNums >(oddNums)):
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line + "\n"
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
matrices = getMatrices(text)
for value in matrices:
encrypted_file.write(str(value) + "\n")
encrypted_file.close()
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()
Well this was a fun one!
in def convertToNum(ch): the alpha does not equal the alpha in def outPutString(text): (missing an *) causing (in my case) tabs instead of spaces and a ? to appear at the end of my decrypted string. I would recommend using a global variable to prevent things like this happening in the future.
Your encryption algorithm worked great and didn't need any adjustment. There were some incompatible variable types in the decryption phase but I managed to get everything to work and have included the working code (my comments marked with ##) I hope this helped.
Edit: As Eric points out in the comments, if (evenNum>(oddNum)) is probably not doing what you want it to do. According to the python docs:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
I Assume you want to compare the lengths of the two arrays to make sure they are equal. If this is the case then you would want to use if (len(evenNum)>len(oddNum))
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' #you forgot your asterix
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (len(evenChars) >len(oddChars)): ## comparing lengths instead of contents
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
newText = text[0].strip('[ ]') ## these two lines convert the string to an array
textArray = newText.split(',')
for ch in textArray: ## changed text to textArray(see above) #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(int(ch)) ## converting string number to int for later operations
else:
oddNums.append(int(ch))
index += 1
decrypted= []
if (len(evenNums) >len(oddNums)): ## comparing lengths instead of arrays
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
print(finalString)
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line ##+ "\n" ##you don't need to add a new line as '\n' is already included at the end of every line.
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
##matrices = getMatrices(text)
##for value in matrices:
##encrypted_file.write(str(value) + "\n")
##encrypted_file.close()
## I added the line below(and removed lines above) to be consistent with your later usage
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()
I am trying to make a game and I am really stuck. The problem is that I cant figur out how to use object oriented programming correctly. The program should launch gameboard function
everytime when the number doesnt equal to arv. It should return the new board with one "O"
less.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
def gameboard(self):
self.__board = ["O","O","O","O","O"]
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
arv = input()
self.arv__ = arv
while 5 > x:
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
return gameboard()
print(self.board())
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()
Using object-oriented programming when you only ever need one instance of the object tends to overcomplicate the program. I suggest having only one main function.
Nevertheless, I fixed your program. Try to find the changes yourself because I am too lazy to explain them, sorry.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
self.__board = ["O","O","O","O","O"]
def gameboard(self):
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
while 5 > x:
arv = input()
self.arv__ = arv
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
self.gameboard()
print(self.__board)
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()
Here is a version of your program that avoids OO and is much more simplified:
from random import randint
lives = 5
print("Guess a number from 1 to 20")
number = randint(1, 20)
while (lives > 1 and number != int(input())):
print("incorrect")
print("lives: " + "O" * lives)
lives -= 1
if lives == 0:
print("The number was actually " + str(number))
else:
print("You were right")