I'm tasked with creating a program that simulates a scantron being turned on from an off state, once turned on it compares two arrays and displays a student's grade based on the comparison of the two arrays. I'm also tasked with creating classes.
I can get the machine to turn on but the grading part is where I'm having trouble. My program tells me that 'correct is not defined' in 'grade = Answers (correct, student, theGrade)'. I don't think I returned or didn't pass the variable correctly. Below is the code. Can anyone PLEASE help??
#this program creates a scantron grading system
#the machine will be turned on, scan the correct answers,
#then will grade the student's answers, and display results
#start class initializing machine off and then switching on
class quizGrader:
#initialize state of machine off
def __init__(self):
self.power = 'Off'
#create module to ask if the user would like to turn on the machine
def switch(self):
#ask user if they'd like to turn on the machine
powerOn = input('Would you like to turn the machine on? (enter Y for yes)')
#create if statement for system to be turned on or off
if powerOn == 'y' or powerOn == 'Y':
self.power = 'On'
else:
self.power = 'Off'
def get_power(self):
return self.power
#create class for correct answers, student answers, and
#for the student's scantron to be graded
class Answers:
#initialize the grades
def __init__(self, correct, student, theGrade):
#declare what each self. will be equal to
self.__correctAnswers = correct
self.__studentAnswers = student
self.__studentGrade = theGrade
#create set method for correctAnswers
def set_correctAnswers(self, correct):
self.__correctAnswers = correct
correct = ['A','B','C','D','E','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
print('Correct answers have been recorded...')
return correct
#create set method for studentAnswers
def set_studentAnswers(self, student):
self.__studentAnswers = student
student = ['B','B','C','D','A','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
return student
#create set method for student's scantron to be graded
def set_studentGrade(self, theGrade):
self.__studentGrade = theGrade
right = 0
index = 1
#create a for loop and if statement for the right answers
#to be counted and then calculate the % of the grade
for index in range(0,20):
if self.__correctAnswers [index] == self.__studentAnswers [index]:
right += 1
percent = float(right/20)
percent = theGrade
return theGrade
#return all the methods previously created
def get_correctAnswers(self, correct):
return self.__correctAnswers
def get_studentAnswers(self, student):
return self.__studentAnswers
def get_studentGrade(self, theGrade):
return self.__studentGrade
#start main module
def main():
#create an object from the quizGrader class
machine = quizGrader()
#display that the machine is off
print('The machine is powered:', machine.get_power())
#ask the user if they'd like to turn the machine on
machine.switch()
#display the user's choice to turn on or leave machine powered off
print('The machine is now/still powered:',machine.get_power())
#create an object from the Answers class
grade = Answers(correct, student, theGrade)
#display that the correct answers have been recorded and display the answers
print('Correct answers have been recorded:',grade.get_correctAnswers())
print()
print()
#display that the student's answers have been recorded and display the answers
print('Student answers have been recorded:', grade.get_studentAnswers())
print()
#grade the student's answers
grade.studentGrade()
#display the amount of answers student answered correctly
#and the percentage of their grade based on correct answers
print('The student grade is',right,'out of 20 or',percent,'%.')
#close main function
main()
You have not defined what correct or student or even theGrade are
grade = Answers(correct, student, theGrade)
You need to instantiate the classes you've created, but you need to actually have those variables available in the main() function.
For example:
def main():
#create an object from the quizGrader class
machine = quizGrader()
correct = ['A','B','C','D','E','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
student = ['B','B','C','D','A','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
will get you a little farther...
Just because you declare them in the classes above doesn't mean they're available.
The variable correct is not defined in your main function.
For example, you could simply add the line correct = 'C' before the line grade = Answers(correct, student, theGrade) to show that the correct answer is C.
The finished product would look something like this:
...
correct = 'C'
grade=Answers(correct, student, theGrade)
...
Related
I'm making a game in which the player works for a certain amount of money. But I'm running the code on a discord server which means that there will be multiple users? If I can get a unique ID for each user then how can I store information for each user?
This is some code I made that basically reflects my other one. How can I store money as well as returning money if they enter a username that's been used before.
def start():
name = input("What is your name?")
main()
def main():
print('1. New Player')
print('2. Work')
answer = input()
if answer == '1':
start()
if answer == '2':
work()
def work():
print("You work for $100")
money += 100
main()
main()
(Sorry if my question is too broad... ask any questions if want more details.)
A simple suggestion would be to create a class that describes a player, their attributes and any functions associated with the player. For example:
class Player:
def __init__(self, id):
self.money = 0
self.items = []
self.level = 1
# Initialize other player attributes here
def add_money(self, amount_added):
self.money += amount_added
def main():
player_1 = Player(id=1)
player_1.add_money(100)
player_2 = Player(id=2)
This is a very generic example, but defining a class for a player will allow you to easily create an object for which you can associate each player. If you add 100 to player 1's money then that will be completely independent of player 2's money. I suggest searching up tutorials/examples on classes and you'll get a feel!
I'm absolutely brand new to Python unit test. I need to use it for a project I have to submit. I sort of have an idea of where to begin, it looks like we basically put in test parameters to functions we have defined in our program and we enter the expected result. If the expected result is output, we get OK, otherwise we will get Failure, or an error.
So my problem is that I have multiple user inputs stored into variables that are within for loops or while loops. I don't know where to even begin with this to set test values in for them.
Here is all of my code:
studentTripExpenses = {}
def dictCreate(studentAmount):
for i in range(0, studentAmount):
studentName = input("What is the name of the student? ")
expenseList = []
print("Enter 'done' to move to the next student.")
while True:
expense = input("What is the cost of this expense? ")
if expense.lower() == 'done':
break
elif (float(expense) >= 0) or (float(expense) < 0):
expenseList.append(float(expense))
elif not expense.isdigit():
print("Please enter a number or enter 'done' to move on.")
studentTripExpenses[studentName] = expenseList
return studentTripExpenses
def studentCost(dct):
for i in dct:
#Variable for individual costs of student
personalCost = 0
#Determines the total cost for each student
for x in dct[i]:
personalCost = personalCost + x
#Sets each students value to their total cost to two decimal places
dct[i] = float("%.2f" % personalCost)
return dct
def amountsDue(expenseLst, studentAvgPrice):
#Runs through the dictionary of students and individual total trip costs
for key in expenseLst:
maxPerson = max(expenseLst, key=expenseLst.get)
costDifference = 0
#Determines who owes who how much money
if max(expenseLst.values()) > expenseLst[key]:
costDifference = studentAvgPrice-expenseLst[key]
if (costDifference < 0):
costDifference = costDifference * -1
print("%s owes %s $%.2f" % (key, maxPerson, costDifference))
def main():
numOfStudents = int(input("How many students are going on the trip? "))
studentCostDict = dictCreate(numOfStudents)
studentTripExpenses = studentCost(studentCostDict)
totalCost = 0
#Gets the total cost for all students
for key in (studentTripExpenses):
totalCost = totalCost + studentTripExpenses[key]
#Changes the total cost to 2 decimal places
totalCost = float("%.2f" % totalCost)
#Determines the average amount spent per student
avgCost = float("%.2f" % (totalCost/len(studentTripExpenses)))
amountsDue(studentTripExpenses, avgCost)
main()
You can use mocking, where you replace a function or class with a test-supplied version. You can do this with the unittest.mock() module.
In this case, you can patch the input() name in your module; instead of the built-in function, the mock object will be called:
from unittest import mock
from unittest import TestCase
import module_under_test
class DictCreateTests(TestCase):
#mock.patch('module_under_test.input', create=True)
def testdictCreateSimple(self, mocked_input):
mocked_input.side_effect = ['Albert Einstein', '42.81', 'done']
result = dictCreate(1)
self.assertEqual(result, {'Albert Einstein': [42.81]})
Because input doesn't exist in your module (it is a built-in function), I told the mock.patch() decorator to create the name; now this input will be used instead of the built-in function.
The side_effect attribute lets you state multiple results; each time the mock is called, it'll return the next value in that list. So the first time 'Albert Einstein' is returned, the next time '42.81', etc.
Together, this lets you simulate actual user inputs.
If you do your test right, you'll notice that there is a bug in your function; the float() call will throw a ValueError exception when anything other than done or a valid numeric value is entered. You need to rework your code to account for that. Try with mocked_input.side_effect = ['Albert Einstein', 'Not an expense', '42.81', 'done'] to trigger the bug.
In case we do not have classes.
In the names.py file, we have the get_names function.
def get_names() -> list:
names = [str(input("Enter name: "))]
while str(input("Do you want to add another name")) == "Y":
names.append(str(input("Enter name: ")))
return categories
In the test_names.py file, we can write test like the following
import numpy as np
from unittest import mock
from src.main.names import get_names
#mock.patch('src.main.names.input', create=True)
def test_should_get_names_from_users(mocked_input):
mocked_input.side_effect = ["John", "Y", "Robert", "N"]
actual_names = get_names()
expected_names = ['John', "Robert"]
assert actual_names == expected_names
This question already has answers here:
What should I do with "Unexpected indent" in Python?
(18 answers)
Closed 5 years ago.
I am going through a textbook and learning Python very successfully; more successfully than I would have imagined. While going through the current chapter of the book I am on, I have been instructed to create a module "games" to use for import in a program "Simple Game". I have done everything to the T that the book has said to do, yet I am constantly arriving at an indent error. I am not claiming that the author of this book has screwed up (since he is a lot more experienced than I), but I have done everything to the letter of instruction and it is not working correctly whatsoever.I have tried unindenting then unindenting the following lines accordingly,indenting the line above the error, and various other things, and I cant get this to work correctly. Please help.
Here's the "games" module:
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_y_n(question):
""" Ask a yes or no question. """
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
""" Ask for a number within a range. """
response = None
while response not in range(low, high):
response = int(input(question))
return response
if __name__ == "__main__":
print("You ran this module directly (and did not 'import' it).")
input("\n\n\t\t\tPress the ENTER key to exit.")
And next i will show you the code of the program that utilizes my created "games" module:
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_y_n("\nDo you want to play again? (y/n): ")
input("\n\n\t\t\tPress the ENTER key to exit.")
The indentation error occurs in the main program at the point where it says: for i in range(num). that line is getting the error, but why?
This line: num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5) should be indented. I suggest you look into a basic Python tutorial. Essentially, every time you type : and start writing code on the next line, you need to increase your indentation level.
I'm trying to create a text game that presents scenarios in a random order. Based upon a user's answer, certain pre-defined statistics should increase. I took a stab at it, but my loop function will not work (among other things). I attempted to incorporate information from this thread: call list of function using list comprehension
Here is my code:
import random
# A class for the user character. Each character has four stats, which start at zero.
class Character(object):
def __init__(self, sass, intuition, despotism, panache):
self.sass = sass
self.intuition = intuition
self.despotism = despotism
self.panache = panache
sass = 0
intuition = 0
despotism = 0
panache = 0
# a function to check the current stat level of the character.
def all_check(self):
print "Your level of sass is %s." % self.sass
print "Your level of intuition is %s." % self.intuition
print "Your level of despotism is %s." % self.despotism
print "Your level of panache is %s." % self.panache
# I assume that these four "Event" functions should be instances of a class due to each Event's commonalities, but I can't understand how to implement.
def Event1():
print """An attractive woman smiles at you and your friend
from across the bar. Your friend confesses that his passions are arouse, but that he is too shy to do anything. What do you do?"""
print "1. Convince the woman to talk to your friend." #intuition
print "2. Tell the woman to talk to your friend... or else." #despotism
print "3. Inform the woman that your friend has herpes, but that you'd love to take her out." #sass
print "4. Why fight? Let's all go back to her place and get weird." #panache, intuition
inp = raw_input(">>> ")
if inp == '1':
Character.intuition += randint(2,4)
elif inp == '2':
Character.despotism += randint(2,4)
elif inp == '3':
Character.sass += randint(2,4)
elif inp == '4':
Character.panache += randint(1,3)
Character.intuition += randint(1,3)
else:
print "You fail."
# To save space, I'm leaving out Events2~4. They have the same structure as Event1
# Put all the Event functions into a list.
events = [
Event1,
Event2,
Event3,
Event4,
]
# A function to cycle through all the Events in random order.
def play(self):
list = shuffle(events)
for x in list:
x()
# Call a class function to create a unique user.
userName = raw_input("What's your name? ")
# Call function to begin the game.
play()
Character.all_check()
I also realize that the Events are more appropriate as instances of a class, but I'm having trouble understanding Zed's (LPTHW) explanation of classes. Any thoughts are welcome.
I am trying to print a variable of a score and name to a .txt file using python.
import random
import csv
import operator
import datetime
now = datetime.datetime.now() ## gets the exact time of when the user begins the test.
def main():
global myRecord
myRecord = []
name = getNames()
myRecord.append(name)
record = quiz()
def getNames(): ## this function grabs first and lastname of the user
firstName = input ("Please enter your first name") ## asks for users name
surName = input("Please enter your surname") ## asks for users suername
space = " "
fullName = firstName + space +surName ## puts data of name together to make full name
print("Hello")
print (fullName)
myRecord.append(fullName)
return fullName ## this is a variable returned to main
def quiz():
print('Welcome. This is a 10 question math quiz\n')
score = 0 ## sets score to 0.
for i in range(10): ## repeats question 10 times
correct = askQuestion()## if the statement above if correct the program asks a question.
if correct:
score += 1## adds one to the score
print('Correct!\n')## prints correct if the user gets a question correct.
else:
print('Incorrect!\n') ## prints incorrect if the user gets a question wrong.
return 'Your score was {}/10'.format(score)
def randomCalc():
ops = {'+':operator.add, ## selects one of the three operators
'-':operator.sub, ## selects one of the three operators
'*':operator.mul,} ## selects one of the three operators
num1 = random.randint(0,12) ## samples a number between 0 and 12
num2 = random.randint(1,10) ## zero are not used to stop diving by zero
op = random.choice(list(ops.keys()))
answer = ops.get(op)(num1,num2)
print('What is {} {} {}?\n'.format(num1, op, num2)) ## puts together the num1, the operator and num2 to form question
return answer
def askQuestion():
answer = randomCalc()
guess = float(input())
return guess == answer
def myfileWrite (myrecord):
with open('Namescore.txt', 'w') as score:
score.write(fullName + '\n')
main()
here is the full code it should ask the users name, print 10 maths questions and then save the time name and score to a txt file
if you can help please do
many thanks
Your indentation is incorrect and you never actually call the function:
with open('Namescore.txt', 'w') as score:
score.write(fullName + '\n')
the code you wrote would IIRC re-make the file each time you ran the code. I believe this is the correct way to do it:
with open("Namescore.txt", "a") as file:
file.write(name, score, "\n") # I don't know what your vars are called
This will append to the file rather than rewrite :)
If you want to do it your way, the correct way would be:
def writeScore(name, score):
file = open("Namescore.txt", "a")
file.write(name, score, "\n")
file.close()
writeScore("Example Examlpus", 201)