I'm having issues with this part of my code:
if(input not in status_list):
print("Invalid Entry, try again.")
break
The break exits the whole program, I just want to go back to the beginning of the program (to while(1):) I've tried pass, continue, return can't think of anything else.. can anyone help??
Thanks :)
Also it's reading this variable income as a string still..: income = int(input("Enter taxable income: ")) The error message I get is "TypeError: 'str' object is not callable"
import subprocess
status_list = ["s","mj","ms","h"]
while(1):
print ("\nCompute income tax: \n")
print ("Status' are formatted as: ")
print ("s = single \n mj = married and filing jointly \n ms = married and filing seperately \n h = head of household \n q = quit\n")
input = input("Enter status: ")
if(input == 'q'):
print("Quitting program.")
break
if(input not in status_list):
print("Invalid Entry, try again.")
break
income = int(input("Enter taxable income: "))
income.replace("$","")
income.replace(",","")
#passing input to perl files
if(input == 's'):
subprocess.call("single.pl")
elif(input == 'mj'):
subprocess.call("mj.pl", income)
elif(input == 'ms'):
subprocess.call("ms.pl", income)
else:
subprocess.call("head.pl", income)
input = input("Enter status: ")
You rebind the name input from the input function to its result, which is a string. So the next time you call it, after continue does its work, input doesn't name a function any more, it's just a string, and you can't call a string, hence
TypeError: 'str' object is not callable
Use continue, and change your variable name so as not to clobber the function.
Your problem isn't continue, it's that you have an unresolved error further down in your code. Continue is doing exactly what it's supposed to (i.e. you want continue in that conditional).
You're renaming input as a string, so the name no longer points to the builtin input function in your code. This is why you don't use reserved keywords as variable names. Call your variable something other than "input" and your code should work fine.
Continue is working correctly. The problem with your script is that you're trying to call replace() on an int:
income = int(input("Enter taxable income: "))
# income is an int, not a string, so the following fails
income.replace("$","")
You can do something like this instead:
income = int(input("Enter taxable income: ").replace("$", "").replace(",", ""))
Related
I'm new to python and there's a video on Youtube that I watched. I do the exact same code as he but mine doesn't work and I don' understand why.
Here's the code:
MAX_LINES = 3
def deposit():
while True:
amount = input("What would you like to deposit? $")
if amount.isdigit():
amount = int(amount)
if amount > 0:
break
else:
print("Amount must be greater than 0. ")
else:
print("Please enter a number. ")
return amount
def get_number_of_lines():
while True:
lines = input("Enter the number of lines to bet on (1-" + str(MAX_LINES) + ")? ")
if lines.isdigit():
lines = int(lines)
if 1 <= lines <= MAX_LINES:
break
else:
print("Please enter a valid number of lines. ")
else:
print("Please enter a number. ")
return lines
There are 3 problems.
Unindent amount does not match previous indent. I have no idea what does that mean
"return" can be used only within a function. As far as I'm concerned I'm using it in the function, copied the first function then pasted it into the second function and somehow it doesn't work
"lines" is not defined. What dou you mean it's not defined, I define it in the first line of the function
https://www.youtube.com/watch?v=th4OBktqK1I
This video's code what I'm trying to do
I appreciate any help!
I just simply don't understand why it works in one and not the other
You have one space too much in front of while True in function get_number_of_lines().
Yes used in functions to return value
Because function don't get inside while loop (because of indent problem), lines is never defined, probably this was the problem.
So try fix indent and run again
I have to make this program:
Write a program that allows a teacher to input how many students are in his/ her class, then allow them to enter in a name and mark for each student in the class using a for loop. Please note you do not need to record all of the names for later use, this is beyond the scope of the course * so just ask them each name, have it save the names over top of each other in ONE name variable.
i.e.)
INSIDE OF A LOOP
name = input (“Please enter student name: “)
Calculate the average mark for the entire class – this will require you to use totaling.
Output the class average at the end of the program, and ask if they would like to enter marks for another class. If they say yes, re-loop the program, if no, stop the program there.
So I started writing the program and it looks like this
studentamount = int(input("Please enter how many students are in your class: "))
for count in range():
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark"))
I ran into the following problem: how would I allow the set of code under the for loop to loop for each student? I was thinking I could just enter in the studentamount variable as the range but I can't since python does not allow you to enter in a variable as a range.
How would I get the for loop to loop for the amount of students typed in? e.g. if 20 students for student amount was typed in, I would want the for loop to loop 20 times. Your help and knowledge is much appreciated.
Read the user input, convert it to int and pass it as a parameter to range:
studentamount = input("Please enter how many students ...: ") # this is a str
studentamount = int(studentamount) # cast to int ...
for count in range(studentamount): # ... because that's what range expects
# ...
Python does not allow you to enter in a variable as a range.
Python does allow you to enter variables as a range, but they must be numbers. Input () reads input in as string, so you need to cast it.
So, this is correct:
```Python
studentamount = int(input("Please enter how many students are in your class: "))
for count in range(studentamount):
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark)
```
P.S a try - except clause would be useful here to catch people entering a non-integer data in [TypeError]
P.S.P.S #schwobaseggl 's example is good too, it is possibly more pythonistic to use the nested function studentamount = int(input("Text") than
studentamount = input("Text")
studentamount = int(studentamount)
You can store each student name and mark in a dictionary or tuple and store each dictionary (or tuple) into a list, see code sample (at the end enter "no" to exit or any other value to re-loop the program):
response = None
while response != 'no':
student_count = int(input('Please enter the number of students: '))
students = []
mark_sum = 0
print('There are {} student(s).'.format(student_count))
for student_index in range(student_count):
student_order = student_index + 1
student_name = input('Please enter the name of student number {}: '.format(student_order))
student_mark = float(input('Please enter the mark of student number {}: '.format(student_order)))
students.append({'name': student_name, 'mark': student_mark})
mark_sum += student_mark
print('The average mark for {} student(s) is: {}'.format(student_count, mark_sum / student_count))
response = input('Do you want to enter marks for another class [yes][no]: ')
Hello I am creating a registration program and need to ask the user to input their age . However I want to make sure its not a letter by just consisting of numbers. How do I limit the user to only getting a number and if they input other character a error message shows up
while True:
age = int(input("Age: "))
if not (age) != int:
print ("Not a valid age")
continue
else:
break
You can use try and except statements here.
try:
age=int(age) #Do not typecast the age variable before this line
except ValueError:
print("Enter number")
If you do not want the program to proceed until the user enters a number, you can use a flag variable and put the code block mentioned above in a while loop.
Python isn't recognizing any number apart from 1 as an integer. When i enter a number to be multiplied the program will run the except ValueError even though i have entered an integer. This is the code i have.
Total = 0
Tsl = 100
receipt = open("Receipt.txt", "w")
while True:
try:
Prod_Code = input("Enter a code or Done to get your final receipt: ")
if len(Prod_Code) == 8:
int(Prod_Code)
with open("Data Base.txt", "r") as searchfile:
for line in searchfile:
if Prod_Code in line:
print(line)
Quantity = input("What quantity of this product do you want? ")
Total += float(line.split(",")[2] * int(Quantity))
print(Quantity)
print(Total)
receipt.write(line)
elif Prod_Code == "Done":
print("Bye Bye")
print(receipt)
receipt.close
exit()
else:
print("Incorrect length, try again")
except ValueError:
print("You must enter an integer")
The error occurs when i enter any other number than 1 when i enter the quantity. If anyone can see the problem any input will be appreciated
The problem is that
Total += float(line.split(",")[2] * int(Quantity))
multiplies the string line.split(",")[2] by the Quantity converted to integer. And then attempts to convert the resulting string to a float.
Eg, if line.split(",")[2] is '1.2' and Quantity is '3' then
line.split(",")[2] * int(Quantity)
results in '1.21.21.2', which can't be converted to float. :)
Instead do
Total += float(line.split(",")[2]) * int(Quantity)
BTW, you aren't actually closing the receipt file. You're just emitting the method name and discarding it. So change
receipt.close
to
receipt.close()
Even better: use with blocks to open all your files so they get closed automatically.
I should also mention that the plain exit() function is primarily intended for use in the interactive interpreter, and it's not guaranteed to exist in all environments. To ensure portability use sys.exit() instead. OTOH, it's not really needed here, you can just break out of that while loop.
One reason can be in inputing the Promo_Code , you are using input so if your promo code is abcdefgh then you must input it as 'abcdefgh' or "abcdefgh" because input in python 2 cannot take automatic decisions . For sake of simplicity always use raw_input() for inputting strings,
Also in your elif convert reciept.close to reciept.close().
I am trying to write to a text file and im having some issues. I want to write to a text file and on each line have a name, a rate, and hours worked each displayed on a line. I wan to display a error message, and have the user input another value, if the user doesn't input a string for the name, as well as if they don't input a value between 5-50 for the rate and 0-100 for the hours. I just cant think of what to do at this point.
Here is my code, Thanks
confirmation = (input("Would you like to add to the payroll file? Enter y for yes, or any other key to end operation: "))
while confirmation == "y":
name = f.write(str(input("What is the employees name?: ")))
while name != str:
name = f.write(str(input("Please enter a name: ")))
f.write(" ")
rate = f.write(input("What is the employees hourly rate?: "))
f.write(" ")
hours = f.write(input("How many hours did the employee work?: "))
hours = float (hours)
f.write(str("\n"))
confirmation = (input("Would you like to keep adding to the payroll file? Enter y for yes, or any other key to end operation: "))
print ("File Closed")
f.close()
input() function already returns a string. There's no need for you to str().
You syntax while name != str is wrong - if you need to check if it is a string you should use isinstance(name, str)
write() function doesn't return anything. When you equal something to your f.write() function you'll equal it to zero.