Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm relatively new to python so I think this may be an easy question, but it has me confused. Here is my code:
# Mike Fitzgibbon CS4250 Project4 implement class diagram
# define the class
class Product:
# name is the name of the product
name = None
# price is how much the product costs
price = None
# discount percent is how much the discount is in percentages
discountPercent = None
# define the constructor
def __init__(self, n, p, d):
# initialize variables
self.name = n
self.price = p
self.discountPercent = d
# define get discount by returning the discount
def getDiscountAmount(self):
return self.discountPercent
# define discount price by returning the discount percent times the price
def getDiscountPrice(self):
return self.discountPercent*self.price
# define get description by creating description using field variables
def getDescription(self):
print("Name: "+self.name)
print("Price: "+self.price)
print("Discount: "+self.discountPercent+"%")
print("Discount price: "+self.getDiscountPrice())
def __main__():
p=Product("A",100,90.0)
print(p.getDescription())
Nothing prints out when I run this code. Why? How do I fix this?
To run your __main__() function, you can add to the end of your program:
if __name__ == "__main__":
__main__()
For printing the values, change print(p.getDescription()) to p.getDescription() because calling the function in class will output the values. BTW, you cannot concatenate int/float with str, so you should convert int/float to string, like print("Price: "+str(self.price))
you would need to add;
if name == '__main__':
main()
the reason for this is that you have defined the function main, but have not told the computer to run it.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I have been taking this class for a bit with python for a bit and I have stumbled into a problem where any time I try to "def" a function, it says that it is not defined, I have no idea what I am doing wrong and this has become so frustrating.
# Define main
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
Every time I try to test run this, I get
"builtins.NameError" name 'LIST SIZE' is not defined.
I cant take out the main function! It's required for the assignment, and even if I take it out I still run into errors.
Your MIN, MAX, and LIST_SIZE variables are all being defined locally within def main():
By the looks of it, you want the code below those lines to be part of main, so fix the indentation to properly declare it as part of main.
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
import random
# Define main
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
main()
Output:
[79]
NOTE: You will get another error message:
NameError: name 'findHighest' is not defined
Which I think findHighest should be a function in some part of your code.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
from replit import db
import os
def clear():
del db["hits"]
del db["ab"]
def save():
db["hits"] = hits
db["ab"] = ab
try:
hits = db["hits"]
ab = db["ab"]
avg = hits/ab
print(f"You're currently batting {avg}")
except:
hits = 0
ab = 0
input = input("press ENTER to continue.")
os.system("clear")
if input == clear:
clear()
else:
#the line of code below is the one in question
today_ab = input("How many at bats did you have today?")
ab += today_ab
The last line is where it is wrong.
Python doesn't have separate namespaces for variables and functions. This line
input = input("press ENTER to continue.")
replaces the built-in function input with the result of the call. When you try to call input later, you get the TypeError.
Use a different variable name:
x = input("press ENTER to continue.")
if x == "clear":
clear()
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Am very new to Python programming.Which am getting the naming error in my function with the object but without the object it works fine.
Hope to get a help from the community.
--Code works
def determine_grade(TestScore):
print("test")
def Mainfunction():
test1 = float(input('Enter the score for test 1: '))
print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction()
--Code doesnot works
class clsCalcScore_Ex6(object):
def determine_grade(TestScore):
print("test")
def Mainfunction():
test1 = float(input('Enter the score for test 1: '))
print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction(object)
The minimal problem with your code is that your definition of the class clsCalcScore_Ex6 is incomplete. If you add a single line to fully define the class, like this, your code will work:
class clsCalcScore_Ex6(object):
pass
If what you want to do is move your functions into the class as methods, then you have more work to do. Here's what doing that correctly might look like:
class clsCalcScore_Ex6(object):
def determine_grade(self, TestScore):
print("test")
def Mainfunction(self):
test1 = float(input('Enter the score for test 1: '))
print("Your Grade for Test 1 is : ", self.determine_grade(test1))
clsCalcScore_Ex6().Mainfunction()
Here's another way that uses static methods and avoids you having to instantiate an instance of the class (note the removal of the first set of parens in the last line):
class clsCalcScore_Ex6(object):
#staticmethod
def determine_grade(TestScore):
print("test")
#staticmethod
def Mainfunction():
test1 = float(input('Enter the score for test 1: '))
print("Your Grade for Test 1 is : ", clsCalcScore_Ex6.determine_grade(test1))
clsCalcScore_Ex6.Mainfunction()
The second way is functionally identical to your original code. It just adds a namespace, placing most of your code under the name clsCalcScore_Ex6.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I've actually already found a work around for my problem, but I feel as though there is still a better way. I can't seem to grasp why the program thinks I'm dealing with a method vs a float.
If I try to run the program, it says that I'm trying to add together two methods. However, when I run the line:
print(type(my.coins.add_coins()))
It tells me that it has returned a float.
Here's the code:
class Currency:
def __init__(self, pennies, nickles, dimes, quarters):
self.pennies = pennies
self.nickles = nickles
self.dimes = dimes
self.quarters = quarters
def penny_value(self):
return self.pennies * .01
def nickle_value(self):
return self.nickles * .05
def dime_value(self):
return self.dimes * .1
def quarter_value(self):
return self.quarters * .25
def add_coins(self):
return self.penny_value + self.nickle_value + self.dime_value + self.quarter_value
my_coins = Currency(1, 1, 1, 1)
#why does this work?
print(my_coins.penny_value() + my_coins.nickle_value())
#but not this?
print(my_coins.add_coins())
Because you are summing functions; Here is what you want to do:
def add_coins(self):
return self.penny_value() + self.nickle_value() + self.dime_value() + self.quarter_value()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Improve this question
The first code is:
string = "DBCABA"
#computing the first recurring alphabet
def compute_reccuring():
for a in string:
var = string.count(a)
if var > 1:
final = str(a)
print(str(final) + " is repeated first")
break
The second code is:
def recurring():
counts = {}
for a in string:
if a in counts:
print(a)
else:
counts[a] = 1
Both of these codes work but I don't know which one is better in performance.
Create a timer function as below and decorate your function with it and see the result yourself.
import time
def timeme(method):
def wrapper(*args, **kw):
startTime = int(round(time.time() * 1000))
result = method(*args, **kw)
endTime = int(round(time.time() * 1000))
print(endTime - startTime,'ms')
return result
return wrapper
You can then use this function as decorator for your function. Something like this:
#timeme
def recurring():
You can use below code to check time taken by your script to run.
import time
start = time.time()
'''
Your Code
'''
end = time.time()
print(start - end)