Display error message to users - python

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.

Related

Type two statements. The first reads user input into person_name. The second reads user input into person_age. Use the int() function to convert

[problem being presented]
I have tried every which way that I have learned, and nothing seems to be giving me the answer that zybooks wants. It wants me to use the int() function, but every time I run it, it pops up with the error code that I cannot use a built-in function. Any help or guidance would be greatly appreciated.
Type two statements. The first reads user input into person_name. The second reads user input into person_age. Use the int() function to convert person_age into an integer. Below is a sample output for the given program if the user's input is: Amy 4
In 5 years Amy will be 9
Note: Do not write a prompt for the input values, use the format: variable_name = input()
person_name = input()
age = input()
person_age = int(age)
enter image description here
Here is a snippet of code that should work.
name = input('Enter Name: ')
age = int(input('Enter Age: '))
print('Name entered: ', name, 'Age entered: ', age)
I just tried it out and it stored the name and age. Perhaps you weren't wrapping the age "input" inside the "int" function.
See if that helps.
Regards.
person_name = input('')
person_age = int(input(''))

i cant seem to break out of this while loop [duplicate]

This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed last year.
i took a comp class in my college and its in the real early stages. i was asked to make this little program which plays madlibs and now i cant seem to complete it.
import random
verb=input("Enter a verb: ")
celebrity= input("Enter name of a celebrity: ")
age=input("Enter an age: ")
while not age==int():
age=(input("C'mon man! Enter a number please: "))
madlibs=f"Coding is fun as if im {verb}. I feel like im {celebrity} and im just {age} years old"
print(madlibs)
again im really new at this so if you have any feedback how i can write the same code in lesser lines and feedback like that, its highly requested
input() function always return a string. It won't be dynamically casted,
you can use isdecimal() str method.
If you want to use age as a number don't forget to cast it.
You can replace this part:
while not age==int():
age=(input("C'mon man! Enter a number please: "))
by:
while not age.isdecimal():
age=input("C'mon man! Enter a number please: ")
age = int(age) # cast str > int
Furthermore, if you want to check your variable type, age==int() condition is not valid, use isintance function instead.
I would do something like this
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("ERROR, you must enter a number")
Bear in mind that this will only work if you introduce an integer number, which I think is what you tried to do in your code. If you want to allow decimal numbers #Felix has given an answer using .isdecimal()
You need to define seperate variables for age_target and age_guess.
Then
While not age_target == age_guess
Here is a working example:
import random
verb = input("Enter a verb: ")
celebrity = input("Enter name of a celebrity: ")
age = input("Enter an age: ")
while True:
try:
int(age)
break
except ValueError:
age=(input("C'mon man! Enter a number please: "))
madlibs=f"Coding is fun as if im {verb}. I feel like im {celebrity} and im just {age} years old"
print(madlibs)
What it does differently:
int(age) is trying to convert the string age to an integer. If this is not possible, it will throw a ValueError.
We catch that ValueError and prompt the user to try again.
If we don't have the while True (keep looping forever) statement, the flow would be the following:
Checking the age against integer. Fail.
Prompt the user again.
Go on to the madlibs statement.
With the while True loop we will stuck the user to the very same prompt till the int(age) doesn't succeed (or at least fail with another type of exception), than we break, which will exit the loop end procede to the next statement.

How to repeat the function when there is no user input

My program is supposed to store contacts. When I enter the number I need the program to keep asking for the number if there is no user input. For now my program considers the contact added even if there is no number entered by user input.
I tried to use a while True or if not. The closest I got to solving the problem was when the program asked a second time for to enter a number but that's all.
def add_contact(name_to_phone):
# Name...
names = input("Enter the name of a new contact:")
# Number...
numbers = input("Enter the new contact's phone number:")
# Store info + confirmation
name_to_phone[names]= numbers
print ("New contact correctly added")
return
Select an option [add, query, list, exit]:add
Enter the name of a new contact:Bob
Enter the new contact's phone number:
New contact correctly added
Select an option [add, query, list, exit]:
As I said the program should keep asking for a number if there is no user input and go to the next step only when there is a user input.
Use a loop.
def add_contact(name_to_phone):
while True:
name = input("Enter the name of a new contact: ")
if name:
break
while True:
number = input("Enter the new contact's phone number: ")
if number:
break
name_to_phone[name] = number
print("New contact correctly added")
You may want to do a more thorough check for the name and number beyond checking if the input is empty or not.
In Python 3.8 or later, you can simply each loop a bit. Maybe this will become an standard idiom; maybe not.
while not (name := input("Enter the name...: ")):
pass

How do you let user pick the range for for loop?

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]: ')

python - breaking out of nested conditional to top of original loop

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(",", ""))

Categories

Resources