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
Related
The prompt for the problem goes as follows:
Create an interactive student records system.
Prompt the user for a student name.
Then prompt the user for a numeric grade
Repeat this until the user enters 'done' in place of a name.
Then print each student and the average of their grades
I have come up with the following code (I'm a beginner guys, sorry if this is obvious)
# I am creating a dictionary so I can store multiple values that are associated with one name
lst = []
dict = {}
while True:
try:
name = str(input("Please enter student's name."))
grade = int(input("Please enter grade student recieved."))
if (name not in list(dict.keys()) and name != "done"):
lsst = []
lsst.append(grade)
dict[name] = lsst
print(lsst)
continue
elif name in list(dict.keys()):
lsst.append(grade)
print(lsst)
continue
elif name == "done":
break
except ValueError:
print("Try Again")
pass
for i in range(list(dict.keys())):
print(f"{name}: {grade}")
I am trying to print the averages after I type 'done' for the name input, but it just moves on to the next input inquiry. Why is this, and how do I fix it?
There are many mistakes in the code but I will break them down in my corrected version.
names_and_grades = {} # I renamed this variable because there is a built in type called dict in Python.
while True: # Using while True is usually discouraged but in this case, it's hard to avoid that.
try:
name = input("Please enter student's name.") # No need to convert to string as it takes the input as a string by default.
if name == "done": # After you prompted for a name immediately check whether the user entered done. This way, you can break right after that.
break
grade = int(input("Please enter grade student recieved."))
if name not in names_and_grades.keys():
names_and_grades[name] = [grade] # We don't actually need a separate list as the entry in the dictionary will be the list itself (that's why it's put between brackets).
elif name in names_and_grades.keys():
names_and_grades[name].append(grade) # Once the list was declared, you can simply append it.
print(names_and_grades[name]) # No need to repeat this twice in the if-else statements, you can just write it after them. And a very important thing, there is no need to use continue, since you are using if-elfe. When you are using if-else, only one of the blocks will be used, the first block where the condition evaluates as true.
except ValueError:
print("Try Again")
for k in names_and_grades.keys():
print(f"{k}: {names_and_grades[k]}") # This is the simplest way to iterate through a dictionary (if you want to format the entries), by iterating through the keys of the dictionary and with the help of the keys, calling the appropriate values.
I hope this helps, let me know if something is unclear.
#I8ACooky - there are some logic and syntax errors, so I will suggest you to run this and see if you can get some ideas to work out your own later:
from collections import defaultdict
grades = defaultdict(list) # in case for multiple scores for a student
print('Welcome to the simple Scoring program. ')
while True:
try:
name = input("Please enter student's name.")
score = int(input("Please enter grade student recieved: "))
if name == 'done' and score == 0:
break
grades[name].append(score)
except ValueError:
print('Try Again....?')
print(dict(grades))
#------------------------
# average scores leave as an exercise...
Outputs:
Welcome to the simple Scoring program.
Please enter student's name.Adam
Please enter grade student recieved: 100
Please enter student's name.Bob
Please enter grade student recieved: 60
Please enter student's name.Cindy
Please enter grade student recieved: 80
Please enter student's name.Adam
Please enter grade student recieved: 80
Please enter student's name.Bob
Please enter grade student recieved: 100
Please enter student's name.Cindy
Please enter grade student recieved: 90
Please enter student's name.done
Please enter grade student recieved: 0
{'Adam': [100, 80], 'Bob': [60, 100], 'Cindy': [80, 90]}
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]: ')
I'm taking an intro Python course and a little stuck on an assignment. Any advice or resources would be greatly appreciated!
Here's the problem:
Write a program in Python that will prompt the user to enter an account number consists of 7 digits.
After getting that account number from user, verify if the account is valid or not. You should have a list called current_accts that hold all valid accounts.
Current valid accounts are shown below and you must use them in your program.
5679034 8232322 2134988 6541234 3984591 1298345 7849123 8723217
Verifying the account number entered should be done in a function called check_account() that will accept the account entered by the user and also the list current_accts. This function should return a 1 if account is valid otherwise return 0 if account is not valid.
Here's what I've written so far, but I'm stuck and also receiving syntax errors for indentation in lines 6-15. I'm also receiving error messages saying that variable 'current_accts' is not defined.
prompt = "Please, enter the 8 digit account number: "
current_accts = current_accts[1:]
current_accts [-1] = "valid"
while True:
try:
userinput = current_accts(prompt)
if len(userinput ) > 8:
raise ValueError()
userinput = int(userinput)
except ValueError:
print('The value must be an 8 digit integer. Try again')
else:
break
userinput = str(userinput)
a =int(userinput[7])+int(userinput[5])+int(userinput[3])+int(userinput[1])
b1 = str(int(userinput[6])*20)
b2 = str(int(userinput[4])*20)
b3 = str(int(userinput[2])*20)
b4 = str(int(userinput[0])*20)
y = int(b1[0])+int(b1[1])+int(b2[0])+int(b2[1])+int(b3[0])+int(b3[1])+int(b4[0])+int(b4[1])
x = (a+y)
if x % 10 == 0:
print('The account number you entered is valid!')
else:
print('The account number you entered is invalid!')
NOTE: If you are looking for cooked up code then please do not read the answer.
I can tell you the logic, I guess you are doing that wrong.
Logic:
Check whether the account number is 7 digit or not.
if condition 1 is true then Check if it is in the list of given accounts or not.
You can check condition 1 by checking is the condition 1000000<= user_input <10000000.
You can check the condition 2 by looping through the list.
You really have to go back and learn some of the basic syntax of python, because there are many problems with your code. Just google for python tutorials, or google specific issues, like how to get a user's input in python.
Anyway, I don't mean to insult, just to teach, so here's my solution to your problem (normally i wouldn't solve all of it, but clearly you made some effort):
current_accts = ['5679034', '8232322', '2134988', '6541234', '3984591', '1298345', '7849123', '8723217']
user_input = input("Please, enter the 7 digit account number: ")
if user_input in current_accts:
print('The account number you entered is valid!')
else:
print('The account number you entered is invalid!')
I didn't place it in a function that returns 0 or 1 like your question demanded, I suggest you adapt this code to make that happen yourself
So I was given a problem by my Computer Science teacher, but I have been sat here for ages and cannot for the life of me figure it out. There are plenty of tasks within the problem, but there is only one I'm having trouble with.
So, I am coding a program for a carpet shop, and the part that I am stuck on is this.
2: For each floor you need to carpet, ask the user for the name of the room that the floor is located in.
Basically X number of rooms; need to loop a sentence asking for the name of the room multiplied by X. So if the user has 3 rooms they need carpeted, I would end up with the name of 3 rooms (Lounge, Bedroom etc.), and be able to display these results back to the user later. Here is what I have so far...
#Generating An Estimate.
#Welcome message + setting base price to 0 + defining "getting_estimate" variable.
def getting_estimate ():
overallPrice = 0
print("Welcome!")
#Getting the information about the customer.
custID = input ("\n1. Please enter the customer's ID: ")
estimateDate = input ("\n2. Please enter the date: ")
numberOfRooms = input (int("\n3. Please enter the number of rooms that need to be carpeted: "))
#Add input allowing user to enter the
#name of the room, looped by the integer entered
#in the Variable "numberOfRooms", and possibly
#adding 1st room, 2nd room etc??
If someone can work this out they are helping me loads. Thanks :)
Perhaps using a for loop perhaps?
for i in range(numberOfrooms):
roomName = input("Blah blah")
Full code:
def getting_estimate ():
overallPrice = 0
print("Welcome!")
custID = input ("\n1. Please enter the customer's ID: ")
estimateDate = input ("\n2. Please enter the date: ")
numberOfRooms = int (input("\n3. Please enter the number of rooms that need to be carpeted: "))
cust_roster = {custID:[]}
for i in range(numberOfRooms):
roomName = input("Enter the name of room number "+str(i+1))
cust_roster[custID].append(roomName)
print("{} has {} rooms called: {}".format(custID,
len(cust_roster[custID]),
cust_roster[custID]))
Btw I'm doing a similar task for my OCR computing coursework ;) so good luck!
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.