This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I am trying to do a simple calculation but once the user inputs the weight it wont print out the remaining weight left. comes with the error code
unsupported operand type(s) for -: 'str' and 'int'
here is my code. is there something i am missing?
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = input("Please enter weight: ")
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = input("Please enter weight: ")
print("Allowance" + weight-definedMass)
You are trying to do minus operation between str and int
First convert input string to int and then do operation.
weight = int(input("Please enter weight: "))
Updated code will be like
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
input() gives you strings, you can't subtract a string from a number - that doesn't make sense. You should turn the input string into a number with int or float
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
The 'input' method takes a 'String' as an input. So whenever the user inputs a number it is directly converted to a 'string'. Since you cannot substact a string with an integer, you get the error. This should be a simple fix:
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 11 months ago.
I'm trying to use list in this one but I had the bug in the last line stumarks[CourseID] = [(StuID,marks)]
Here is my code :
courselist = []
class course:
def __init__(self,id,name):
self.id = id
self.name = name
#classmethod
def CourseInfo(cls):
return cls(
input("Enter the course ID : "),
input("Enter the course name : ")
)
def cif():
for i in range(getNumOfCourses()):
cse = course.CourseInfo()
courselist.append(cse)
stumarks = []
def MarkInput():
CourseID = input("Enter the course's ID : ")
if CourseID not in [CourseInfo.id for CourseInfo in courselist]:
print(" The course's id isn't founded! Please try again!")
else:
nm = int(input("Number of student that you want to enter marks: "))
for i in range(nm):
while True:
StuID = input("Enter a student's ID : ")
if StuID not in [StudentInfo.id for StudentInfo in studentlist]:
print("The student's ID isn't founded! Please try again! ")
continue
break
marks = float(input("Enter the mark: "))
if CourseID in stumarks:
stumarks[CourseID].append((StuID,marks))
else:
stumarks[CourseID] = [(StuID,marks)]
Could anyone help me with this one? Thank you!
The problem is that CourseId is not cast to an integer and is hence treated as a string. Try changing:
CourseID = input("Enter the course's ID : ")
to
CourseID = int(input("Enter the course's ID : "))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 10 months ago.
This program calculates depreciation
I want to keep asking user for input until it gives the valid input.
def CalculateDep(amount,nofYears,rate,yearOfPurchase):
for i in range(nofYears):
if (mop.lower() == "n" and i == 0):
percentile = rate * 0.005
elif(mop.lower() == "y" or mop.lower() == "n"):
percentile = rate * 0.01
dep = round((percentile)*amount, 2)
print("") # print blank line for readiblity
print("Dep Charge #" + str(percentile*100) + " % : " + str(dep))
print("On 31-03-" + str(yearOfPurchase+1))
amount = amount - (dep)
yearOfPurchase += 1
print("Value After Depreciation : " + str(round(amount, 2)))
amt = int(input("Enter the Amount : ")) #Initial value of asset
y = int(input("Enter the Number of years : "))
r = float(input("Enter The depreciation Rate : "))
yop = int(input("Enter The Year in Which The Asset is purchased : "))
mop = input("Purchased asset before 1st October ? Answer y or n : ")
CalculateDep(amt, y, r, yop)
Typically this can be accomplished with a while loop
while True:
try:
amt = int(input("Enter the Amount : "))
except ValueError:
print('please enter an int')
else:
break
I keep getting syntax error highlighted on "m" in second row on the variable "mark2".
This is the code I have:
print("Please enter your 5 marks below")
mark1 = float(input("enter mark1: ")
mark2 = float(input("enter mark2: ")
mark3 = float(input("enter mark3: ")
mark4 = float(input("enter mark4: ")
mark5 = float(input("enter mark5: ")
marksList = [mark1, mark2, mark3, mark4, mark5]
print(marksList)
sumofMarks = mark1 + mark2 + mark3 + mark4 + mark5
averageOfMarks = sumofMarks/5
print("The sum of your mark is: "+str(sumofMarks))
print("The sum of your mark is: "+str(averageOfMarks))
mark1 = float(input("enter mark1: "))
^ you missed this
In the next 4 lines as well. It is better to use an IDE (Eg: PyCharm) to catch these errors.
This question already has answers here:
Comparing numbers give the wrong result in Python
(4 answers)
Closed 3 years ago.
so I need to make sure the information I am inputting shows if its less than, greater than, or equal too.
not sure if the variable is messed up or not.
here is the code:
#the main function
def main():
print #prints a blank line
age = getAge ()
weight = getWeight()
birthMonth = getMonth()
print
correctAnswers(age, weight, birthMonth)
#this function will input the age
def getAge():
age = input('Enter your guess for age: ')
return age
#thisfunction will input the weight
def getWeight():
weight = input('Enter your guess for weight: ')
return weight
#thisfunction will input the age
def getMonth():
birthMonth = raw_input('Enter your guess for birth month: ')
return birthMonth
#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
if age <= 25:
print 'Congratulations, the age is 25 or less.'
if weight >= 128:
print 'Congatulations, the weight is 128 or more.'
if birthMonth == 'April':
print 'Congratulations, the birth month is April.'
#calls main
main()
input() function returns a string. Before performing the integer comparison you are trying to do, you have to convert string.
For example:
def getAge():
age = input('Enter your guess for age: ')
return int(age)
I have edited your code so that it will work correctly.
def main():
print #prints a blank line
age = getAge()
weight = getWeight()
birthMonth = getMonth()
print()
correctAnswers(age, weight, birthMonth)
#this function will input the age
def getAge():
age = input('Enter your guess for age: ')
return age
#thisfunction will input the weight
def getWeight():
weight = input('Enter your guess for weight: ')
return weight
#thisfunction will input the age
def getMonth():
birthMonth = raw_input('Enter your guess for birth month: ')
return birthMonth
#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
if int(age) <= 25:
print('Congratulations, the age is 25 or less.')
if int(weight) >= 128:
print('Congatulations, the weight is 128 or more.')
if birthMonth == 'April':
print('Congratulations, the birth month is April.')
#calls main
main()
I'm trying to understand how to use functions properly. In this code, I want to return 2 arrays for pupil names and percentage scores. However I am unable to return the array variables from the first function.
I've tried using different ways of defining the arrays (with and without brackets, both globally and locally)
This is the relevant section of code for the program
#function to ask user to input name and score
def GetInput():
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
I'm expecting to be asked to enter the values for both arrays.
I'm instead getting:
Traceback (most recent call last):
File "H:/py/H/marks.py", line 35, in <module>
name, mark = GetInput()
File "H:/py/H/marks.py", line 7, in GetInput
names[counter] = input("Please enter the student's name: ")
NameError: global name 'names' is not defined
You need to use dictionary instead of list if your want to use key-value pairs. furthermore you need to return the values outside of for loop. You can try the following code.
Code:
def GetInput():
names = {} # Needs to declare your dict
percentages = {} # Needs to declare your dict
for counter in range(0, 3):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages # Return outside of for loop.
name, mark = GetInput()
print(name)
print(mark)
Output:
>>> python3 test.py
Please enter the student's name: bob
Please enter the student's score %: 20
Please enter the student's name: ann
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{0: 'bob', 1: 'ann', 2: 'joe'}
{0: 20, 1: 30, 2: 40}
If you want to create a common dictionary which contains the students' name and percentages, you can try the following implementation:
Code:
def GetInput():
students = {}
for _ in range(0, 3):
student_name = input("Please enter the student's name: ")
valid = False
while not valid:
student_percentages = int(input("Please enter the student's score %: "))
if student_percentages < 0 or student_percentages > 100:
print("Please enter a valid % [0-100]")
continue
valid = True
students[student_name] = student_percentages
return students
students = GetInput()
print(students)
Output:
>>> python3 test.py
Please enter the student's name: ann
Please enter the student's score %: 20
Please enter the student's name: bob
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{'ann': 20, 'bob': 30, 'joe': 40}
You forgot to set the names and percentages as empty dictionaries so you can use them. Also the "return" should be outside of the for loop.:
def GetInput():
names={}
percentages={}
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
Probably this may help to you.
#function to ask user to input name and score
def GetInput():
names=[]
percentages=[]
for counter in range(0,3):
names.append(input("Please enter the student's name: "))
valid = False
while valid == False:
percentages.append(int(input("Please enter the student's score %: ")))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
print(name,mark)
This is implemented by using two lists. (Not suggested for keeping records. Better use dictionary as done below.)
counter = 10
def GetInput():
names = []
percentage = []
for i in range(counter):
names.append(input("Please enter the student's name: "))
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
return names, percentage
students, marks = GetInput()
The following is implemented by using dictionary, and for this, you do not need the variable counter.
def GetInput():
records = dict()
for i in range(counter):
name = input("Please enter the student's name: ")
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
#percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
records[name] = percent
return records
record = GetInput()
Change the value of counter to how many records you want. This takes care of marks to be between 0 and 100 (included) and to be integer. Its better if you implement it with dictionary.
Wouldn't it be better to have name and percentage in one dict?
#function to ask user to input name and score
def GetInput():
name_percentage = {}
for counter in range(0,10):
name = input("Please enter the student's name: ")
valid = False
while not valid:
percentage = int(input("Please enter the student's score %: "))
if percentage < 0 or percentage > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
name_percentage[name] = percentage
return name_percentage
name_percentage = GetInput()
print(name_percentage)