I have been trying to create a calculator and i had for practical reasons i tried to import functions from a separate python file. It works at some extent but it breaks when it tries to do the calculations. The bug is is that the add is not defined but i did defined it while importing the function. Here is the code:
class Calculator(object):
import a10 as add
import d10 as div
import m10 as mult
import s10 as sub
def choice(self):
print("A. Addition\l B. Substraction\l C. Division\l D. Multiplication")
xn = input("What do you want to do? ")
if xn == "a":
addition = add.addition
x = self.addition()
self.x = x
return x
elif xn == "b":
subtraction = sub.subtraction
z = self.subtraction()
self.z = z
return z
elif xn == "c":
division = div.division
y = self.division()
self.y = y
return y
elif xn == 'd':
Multiplication = mult.multiplication
v = self.Multiplication()
self.v = v
return v
objcalc = Calculator()
print(objcalc.choice())
Here is the a10
def addition(self):
try:
n = int(input("enter number: "))
n_for_add = int(input("What do you want to add on " + str(n) + " ? "))
except ValueError:
print("you must enter an integer!")
n_from_add = n + n_for_add
print(str(n) + " plus " + str(n_for_add) + " equals to " + str(n_from_add))
s10
def subtraction(self):
try:
nu = int(input("enter number: "))
nu_for_sub = int(input("What do you want to take off " + str(nu) + " ? "))
except ValueError:
print("you must enter an integer!")
nu_from_sub = nu - nu_for_sub
print(str(nu) + " minus " + str(nu_for_sub) + " equals to " + str(nu_from_sub))
m10
def Multiplication(self):
try:
numb = int(input("enter number: "))
numb_for_multi = int(input("What do you want to multiply " + str(numb) + " on? "))
except ValueError:
print("you must enter an integer!")
numb_from_multi = numb * numb_for_multi
print(str(numb) + " multiplied by " + str(numb_for_multi) + " equals to " + str(numb_from_multi))
d10
def division(self):
try:
num = int(input("enter number: "))
num_for_div = int(input("What do you want to divide " + str(num) + " off? "))
except ValueError:
print("you must enter an integer!")
num_from_div = num / num_for_div
print(str(num) + " divided by " + str(num_for_div) + " equals to " + str(num_from_div))
In the if statements, like this:
if xn == "a":
addition = add.addition
x = self.addition()
self.x = x
return x
addition is created as a variable local to the function choice, but you're then setting x to be self.addition(), which isn't defined.
If you mean to write x = add.addition() then be warned that your addition function doesn't return anything, it just prints out a value. The same for the other functions - none of them return anything. So self.addition is not defined, and x will be a NoneType object
Your addition, subtraction and other functions also take self as an argument, when they're not methods in a class, so this doesn't make much sense.
Related
I am making a number guessing game for a project as a part of my intro to the coding class. I am trying to calculate the total earnings for the user, but I keep getting a type error and I have no idea what I am doing wrong.
print("To begin the game pay two dollars")
print("You can collect your winnings when you stop playing")
import sys
count = 0
Jackpot_wins = 0
Reversed_digits = 0
Digit_WrongPlacement = 0
Digit_RightPlacement = 0
Digit_RightPlacement_two = 0
Digit_WrongPlacement_two = 0
JackpotValue = 100
Reversed_digitsValue = 10
Digit_RightPlacementValue = 10
Digit_WrongPlacementValue = 5
Cost_Per_Play = 2
Game_start = input("Would you like to play? enter 'y' for yes and 'n' for no: ")
if Game_start == "n":
print("Thats ok, maybe next time")
sys.exit()
while Game_start == "y":
count = count + 1
Money_Spent = count * Cost_Per_Play
Player_Number = int(input("Enter a number 0-99: "))
print(Player_Number)
import random
Hidden = random.randint(0,99)
Reversed_digits = (str(Hidden)[::-1])
print(Hidden)
Jackpot = Hidden == Player_Number
PN = int(Player_Number / 10)
RN = int(Hidden / 10)
PN1 = int(Player_Number % 10)
RN1 = int(Hidden % 10)
if Jackpot:
print("Jackpot!!! You win 100 dollars!!!")
Jackpot_wins = int(Jackpot_wins + 1)
elif Player_Number == Reversed_digits:
print("Right digits, wrong order!... You win 10 dollars!")
Reversed_digits = int(Reversed_digits + 1)
elif PN == RN:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement = int(Digit_RightPlacement + 1)
elif RN1 == PN1:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement_two = int(Digit_RightPlacement_two + 1)
elif PN1 == RN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement = int(Digit_WrongPlacement + 1)
elif RN1 == PN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement_two = int(Digit_WrongPlacement_two + 1)
else:
print("Completely wrong")
Game_start = input("To continue type 'y' to end type anything: ")
JP_money = Jackpot_wins * JackpotValue
RD_money = Reversed_digits * Reversed_digitsValue
DRP_money = Digit_RightPlacement * Digit_RightPlacementValue
DRP1_money = Digit_RightPlacement_two * Digit_RightPlacementValue
DWP_money = Digit_WrongPlacement * Digit_WrongPlacementValue
DWP1_money = Digit_WrongPlacement_two * Digit_WrongPlacementValue
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
Total_earnings = Winnings - Money_Spent
if Game_start != "y":
print("See you next time! You played ", count, "rounds.")
print("you spent $ ", Money_Spent)
print("Wow you won the Jackpot", Jackpot_wins, "times!")
print("Your total earnings are", Total_earnings, "Congrats!")
I expected the code to keep tally of the wins and their varying values but I am either getting a type error or a value that is unbelievable like 72727171723
Yes, I tested the code, in your Winning calculation RD_Money is returning string number,
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
For resolving this you can just convert it in the calculation like this
Winnings = JP_money + int(RD_money) + DRP_money + DRP1_money + DWP_money + DWP1_money
or you can do this
RD_money = int(Reversed_digits) * Reversed_digitsValue
This will solve your problem
I'm making a guessing game and i need to know how to stop it from putting my answers in lexicographical order as that makes a bug in my game.
I've tried instead of having elif Guess < str(value): making it elif Guess < int(value): but i get the error message "'<' not supported between instances of 'str' and 'int'" and i'm having no luck with anything else
Here is the code im working with
from random import *
from random import randint
import os
numbers = []
Guesses = []
dif = []
os.system('CLS')
print("I want you to guess my number")
print("\n \n \n \nIf you give up type 'give up' word for word")
f = open("Data.txt", "a")
print("Say 'yes' If You're Ready")
YN = input()
if YN == "yes":
os.system('cls')
print("Select a difficulty")
print('impossible 1 - 10000')
print('annoying 1 - 1000')
print('hard 1 - 500')
print('medium 1 - 200')
print('easy 1 - 99')
print('beginner 1 - 10')
diff = input()
if diff == 'easy':
os.system('CLS')
value = randint(1, 99)
numbers.append(value)
dif.append(diff)
elif diff == 'beginner':
os.system('CLS')
value = randint(1, 10)
numbers.append(value)
dif.append(diff)
elif diff == 'medium':
os.system('CLS')
value = randint(1, 199)
numbers.append(value)
dif.append(diff)
elif diff == 'hard':
os.system('CLS')
value = randint(1, 499)
numbers.append(value)
dif.append(diff)
elif diff == 'annoying':
os.system('CLS')
value = randint(1, 1000)
numbers.append(value)
dif.append(diff)
elif diff == 'impossible':
os.system('CLS')
value = randint(1, 10000)
numbers.append(value)
dif.append(diff)
os.system('cls')
while True:
Guess = input()
if Guess == "give up":
print("The Number Was " + str(numbers))
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("[USER GAVE UP] \n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
break
elif Guess < str(value):
print("Higher")
Guesses.append(Guess + " - Higher")
elif Guess > str(value):
print("Lower")
Guesses.append(Guess + " - Lower")
elif Guess == str(value):
os.system('CLS')
length = len(Guesses)
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("Number Of Guesses [" + str(length) + "]\n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
print("That Was Correct!")
for x in Guesses:
print(x)
break
input()
You may try to convert Guess from str to int, and compare in integer.
elif int(Guess) < value:
As maruchen notes you should be casting the Guess variable and not the value variable.
However, that alone is still going to leave you with problems. The user isn't forced to enter an integer and indeed string answers such as "give up" are expected. If you try an cast a string to an integer and the string contains non-numerics, then you will be faced with a ValueError. So best is to define a function like this:
def guess_less_than_value(guess, value):
try:
return int(guess) < int(value)
except ValueError:
return False
Then you can but in the body of your code:
if guess_less_than_value(Guess, value):
....
And likewise with greater than.
Building a simple to-do list app to teach myself classes. Nearly everything works (so far, you can add items, view the list, and remove items). But, I can't seem to figure out how to implement a change item feature. This is supposed to change the name of an already created item, but the code I'm working on isn't doing it.
# counters for telling if a slot is empty or not
a = 0
b = 0
c = 0
d = 0
e = 0
# overarching class for entire program
# outlines how a list item is structured
class Item():
def __init__(self, thingToDo, dueDate, priority):
self.thingToDo = thingToDo
self.dueDate = dueDate
self.priority = priority
def thingChange(self):
thingChange = input("What would you like to change it to? ")
self.thingToDo = thingChange
def whatToChange():
global whatToChange
whatToChange = input("What in the item would you like to change (1. thing, 2. due date, 3. priority)?")
if "1" in whatToChange:
itemChange = input("What would you like to change it to? ")
item1.thingToDo = itemChange
printCurrentList()
# takes inputs to add an instance of to do item
def getItem():
global thing
thing = input("What do you want to do?")
global time
time = input("When do you need to do it by?")
global importance
importance = input("Priority (rate out of 5): ")
# each of these takes the inputs from getItem(), and puts them into the slots
def runItem1():
getItem()
global item1
item1 = Item(thing, time, importance)
print("1. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
global a
a = a + 1
def runItem2():
getItem()
global item2
item2 = Item(thing, time, importance)
print("2. You need to " + item2.thingToDo + " by " + item2.dueDate + ", and the priority is " + item2.priority + "/5.")
global b
b = b + 1
def runItem3():
getItem()
global item3
item3 = Item(thing, time, importance)
print("3. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
global c
c = c + 1
def runItem4():
getItem()
global item4
item4 = Item(thing, time, importance)
print("4. You need to " + item4.thingToDo + " by " + item4.dueDate + ", and the priority is " + item4.priority + "/5.")
global d
d = d + 1
def runItem5():
getItem()
global item5
item5 = Item(thing, time, importance)
print("5. You need to " + item5.thingToDo + " by " + item5.dueDate + ", and the priority is " + item5.priority + "/5.")
global e
e = e + 1
# pretty self explanatory, prints out the current slots in a list-type format
def printCurrentList():
if a > 0:
print("1. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
else: print("Slot 1 is empty.")
if b > 0:
print("2. You need to " + item2.thingToDo + " by " + item2.dueDate + ", and the priority is " + item2.priority + "/5.")
else:
print("Slot 2 is empty.")
if c > 0:
print("3. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
else:
print("Slot 3 is empty.")
if d > 0:
print("4. You need to " + item4.thingToDo + " by " + item4.dueDate + ", and the priority is " + item4.priority + "/5.")
else:
print("Slot 4 is empty.")
if e > 0:
print("5. You need to " + item5.thingToDo + " by " + item5.dueDate + ", and the priority is " + item5.priority + "/5.")
else:
print("Slot 5 is empty.")
# adds an item to the list, but first, checks to see if list slots are already used -- uses a,b,c,d,e
def add():
printCurrentList()
if a > 0 and b > 0 and c > 0 and d > 0 and e > 0:
print("You need to empty a slot before you add another item.")
whichToRemove = input("Which slot would you like to remove?")
if input == "1":
print("What would you like to add in its place?")
runItem1()
else:
slot = input("Which slot would you like to use?: ")
if slot == "1":
runItem1()
elif slot == "2":
runItem2()
elif slot == "3":
runItem3()
elif slot == "4":
runItem4()
elif slot == "5":
runItem5()
else:
print("Error. Please try again.")
add()
# main loop of the program
def main():
prompt = input("What do you want to do (add, remove, change, or view)?: ")
if prompt == "add":
add()
elif prompt == "remove":
printCurrentList()
whichToRemove = input("Which one would you like to remove?: ")
if whichToRemove == "1":
print("Item 1, " + item1.thingToDo + ", has been removed.")
global a
a = 0
elif whichToRemove == "2":
print("Item 2, " + item2.thingToDo + ", has been removed.")
global b
b = 0
elif whichToRemove == "3":
print("Item 3, " + item3.thingToDo + ", has been removed.")
global c
c = 0
elif whichToRemove == "4":
print("Item 4, " + item4.thingToDo + ", has been removed.")
global d
d = 0
elif whichToRemove == "5":
print("Item 5, " + item5.thingToDo + ", has been removed.")
global e
e = 0
printCurrentList()
elif prompt == "view":
print("Here is your current list: ")
printCurrentList()
elif prompt == "change":
whichToChange = input("Which one would you like to change?: ")
if "1" in whichToChange:
oldItem = item1.thingToDo
whatToChange()
thingChange()
print("Item 1, " + oldItem + ", has been changed to " + item1.thingToDo)
elif "2" in whichToChange:
print("Item 2, " + item2.thingToDo + ", has been changed to _____________.")
elif "3" in whichToChange:
print("Item 3, " + item3.thingToDo + ", has been changed to _____________.")
elif "4" in whichToChange:
print("Item 4, " + item4.thingToDo + ", has been changed to _____________.")
elif "5" in whichToChange:
print("Item 5, " + item5.thingToDo + ", has been changed to _____________.")
printCurrentList()
main()
main()
Is there a way to get this working?
It looks like you're mixing procedural methods with object orientated methods.
One of the principles of object orientated design is determining where the functions belong ... which functions belong to which class.
Once I had that sorted out for myself moving from thinking just procedurally to thinking in terms of objects became much easier for me.
I suggest creating a list [], or a dictionary {} to store your items.
Then print current list can be handled by
item_list = []
# ... create items and add to item_list using item_list.append(item)
for item in item_list:
print(item)
or
item_dictionary = {}
# create items and add to item_dictionary using item_dictionary[some_key] = item
for key in item_dictionary:
item = item_dictionary[key]
Then add whatever functions you need for your item class and use methods to add/remove/edit those items in the list of the dictionary.
I'd also drop the globals as the commentators suggested. I don't use globals at all in the python code I write.
x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
while True:
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
I'm trying to get my program to go back to the top while loop if "Y" or "y" is entered for 'Would you like to make another calculation?'. So far what I have returns me to the bottom while loop. Any help? Thanks!
It looks like your second loop should actually be an outer loop (in this case often called a "game loop"). The entire application loops until the user specifies to end the application. Something like this:
a = "Y"
while (a == "Y"):
##########
# All of your "first loop" logic goes here.
# This is the primary "step" of any given instance of the "game".
##########
# Then, prompt the user to continue or not...
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
(Note: This is freehand code and I'm not entirely familiar with Python, so there may need to be some tweaking on the specifics. This is meant to demonstrate the structure, not to be copied/pasted as production code.)
Try nesting the first while loop inside of the second. It'll run your calculation code first, check to see if you'd like to do another, and then return to the top of the while True: loop to do another calculation.
Like this:
while True:
x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
Hope that helps
Depending on what you're trying to do, and where this particular code appears in your program, it's usually advised to wrap your code inside of functions. That way, it doesn't automatically run when you import your module. You have to call a function to make the code run.
If you want to make this an executable script, you'd want to wrap the main loop code in a if __name__ == '__main__: block so that it only executes if it's being executed directly.
e.g.:
def perform_calculation():
while True:
x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
def run_loop():
while True:
perform_calculation()
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
if __name__ == '__main__':
run_loop()
keep on getting error report
File "/home/hilld5/DenicaHillPP4.py", line 72, in main
gradeReport = gradeReport + "\n" + studentName + ":\t%6.1f"%studentScore+"\t"+studentGrade TypeError: cannot concatenate 'str' and 'NoneType' objects
but can't seem to figure out why student grade is returning nothing
studentName = ""
studentScore = ""
def getExamPoints (total): #calculates Exam grade
total = 0.0
for i in range (4):
examPoints = input ("Enter exam " + str(i+1) + " score for " + studentName + ": ")
total += int(examPoints)
total = total/.50
total = total * 100
return total
def getHomeworkPoints (total):#calculates homework grade
total = 0.0
for i in range (5):
hwPoints = input ("Enter homework " + str(i+1) + " score for " + studentName + ": ")
total += int(hwPoints)
total = total/.10
total = total * 100
return total
def getProjectPoints (total): #calculates project grade
total = 0.0
for i in range (3):
projectPoints = input ("Enter project " + str(i+1) + " score for " + studentName + ": ")
total += int(projectPoints)
total = total/.40
total = total * 100
return total
def computeGrade (total): #calculates grade
if studentScore>=90:
grade='A'
elif studentScore>=80 and studentScore<=89:
grade='B'
elif studentScore>=70 and studentScore<=79:
grade='C'
elif studentScore>=60 and studentScore<=69:
grade='D'
else:
grade='F'
def main ( ):
classAverage = 0.0 # initialize averages
classAvgGrade = "C"
studentScore = 0.0
classTotal = 0.0
studentCount = 0
gradeReport = "\n\nStudent\tScore\tGrade\n============================\n"
studentName = raw_input ("Enter the next student's name, 'quit' when done: ")
while studentName != "quit":
studentCount = studentCount + 1
examPoints = getExamPoints (studentName)
hwPoints = getHomeworkPoints (studentName)
projectPoints = getProjectPoints (studentName)
studentScore = examPoints + hwPoints + projectPoints
studentGrade = computeGrade (studentScore)
gradeReport = gradeReport + "\n" + studentName + ":\t%6.1f"%studentScore+"\t"+studentGrade
classTotal = classTotal + studentScore
studentName = raw_input ("Enter the next student's name, 'quit' when done: ")
print gradeReport
classAverage = int ( round (classTotal/studentCount) )
# call the grade computation function to determine average class grade
classAvgGrade = computeGrade ( classAverage )
print "Average class score: " , classAverage, "\nAverage class grade: ", classAvgGrade
main ( ) # Launch
You have two errors in your computeGrade function:
You do not reference the function's single parameter (total) anywhere in the function.
The function has no return statement.
A corrected version might look like:
def computeGrade (studentScore): #calculates grade
if studentScore>=90:
grade='A'
elif studentScore>=80 and studentScore<=89:
grade='B'
elif studentScore>=70 and studentScore<=79:
grade='C'
elif studentScore>=60 and studentScore<=69:
grade='D'
else:
grade='F'
return grade