This question already has answers here:
How to compare multiple variables to the same value?
(7 answers)
Closed 3 years ago.
I want this program to be in a loop until the user puts DONE
import datetime
fileName =input('file name :')
fileName = fileName+'.csv'
access ='w'
currentdate=datetime.date.today()
with open (fileName,access)as newFile :
newFile.write('Name,Age,Nationality,Date\n')
while True:
name=input('Name:')
age=input('Age: ' )
nationality=input('Nationality: ')
newFile.write(name+','+age+','+nationality+',%s'%currentdate+'\n')
if name or age or nationality == 'DONE':
break
In the following IF statement in your code, nationality is the only variable being compared to the string value 'NONE'.
if name or age or nationality == 'DONE':
break
Try either of the following
if any(x == 'DONE' for x in [name, age, nationality]):
break
if 'DONE' in [name, age, nationality]:
break
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 months ago.
I’m having an issue with part of my code.
I’ve created a dictionary below
names_meaning = {
"Taiwo": "First of a twin",
"Tariro": "Hope" ,
"Joseph": "God will add",
"Joel": "YHWH (or LORD) is God",
"Jude": "Praised",
"Hannah": "Favour or Grace"
}
I created a new list from the keys in the dictionary above.
family_names = list(names_meaning.keys())
Then I’m asking the user for an input and I’ve called it below.
name = input("Please type a name to know the meaning: ").capitalize()
From the user’s input, I am checking to see if it is in a family_names.
if name not in family_names:
print(f"You can only pick a name from this list of names {family_names}.")
name = input("Please type a name to know the meaning: ").capitalize()
else:
print(f"{name} means: {names_meaning[name]}\n")
The check works only once. I need the check to continue saying "Please type a name to know the meaning: " until the user types in the correct name.
What am I doing wrong?
use a while loop to continue asking for input until it is valid, then break out of the loop.
names_meaning = {
"Taiwo": "First of a twin",
"Tariro": "Hope",
"Joseph": "God will add",
"Joel": "YHWH (or LORD) is God",
"Jude": "Praised",
"Hannah": "Favour or Grace",
}
family_names = list(names_meaning.keys())
name = input("Please type a name to know the meaning: ").capitalize()
run = True
while run:
if name not in family_names:
print(f"You can only pick a name from this list of names
{family_names}.")
name = input("Please type a name to know the meaning: ").capitalize()
if name in family_names:
print(f"{name} means: {names_meaning[name]}\n")
break
else:
print(f"{name} means: {names_meaning[name]}\n")
break
I am trying to make a script that asks for user input in Python, it is supposed to error with the response "Please enter first name", and then return the user back to the initial input question prompt.
This isn't working, instead after asking for both the first and last name if no name is given for both I am thrown into an infinite loop of the first error.
# User input for first name
first_name = input('Enter FIRST name here: ')
# User input for last name
last_name = input('Enter LAST name here: ')
def print_name():
# store user input in separate variable
fname = first_name
lname= last_name
while True:
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()
Please can someone help me understand whats going wrong here? It should only loop back to asking for a first name (or last name) when nothing is given, other wise it should print the users name to console. both names should be given too, if first name is not given then id expect an error in the first while loop, like wise if last name is not given.
Also is there a better way to do this? using 2 while loops seems wrong?
Don't repeat yourself. If you copy and paste a section of code, stop and think. It should either be a function, or a loop.
def wait_for_input(prompt):
data = ""
while data == "":
data = input(prompt).strip()
return data
def print_name(fname, lname):
print(f'your name is {fname} {lname}')
first_name = wait_for_input('Enter FIRST name: ')
last_name = wait_for_input('Enter LAST name: ')
print_name(first_name, last_name)
Also, don't use comments to repeat what the code says.
The issue is with your infinite loops, you can simplify your function like:
def print_name():
first_name = ""
last_name = ""
# User input for first name
while first_name == "":
first_name = input('Enter FIRST name here: ')
# User input for last name
while last_name == "":
last_name = input('Enter LAST name here: ')
print(f'your name is {first_name} {last_name}')
I have the impression you are new at this:
While-loops generally look as follows:
while <condition>
...
<check_condition>
...
This means that in most cases, at every time the loop is executed, the condition is re-calculated and checked again by the while.
In your case, this would become something like:
while (len(fname) == 0)
<show_error_message>
<get fname again>
The case you have written here (while true) also exists and is used regularly, but in very different cases, like in multi-threaded event-based programs:
while true
<get_event>
This means that a part of the program (a so-called thread) is waiting for an event (like a buttonclick) to be catched and then something happens. This, however, is mostly done in multi-threaded applications, which means that the "main" program is doing something, while a subprogram is handling the events, which are coming in.
I am not fully understanding why you need so many loops. Something like this should do:
def print_name():
fname = input('Enter FIRST name here: ')
if len(fname) == 0:
raise Exception('No FIRST name entered...')
lname= input('Enter LAST name here: ')
if len(lname) == 0:
raise Exception('No LAST name entered...')
print(f"your name is {fname} {lname}")
And if all you wanted is to repeat this loop all you need to do is nest your print_name() function in a loop.
EDIT: Now that I seen other answers, I believe #Tomalak answer is better, was not getting what you really wanted.
Try this code:
def print_name():
# store user input in separate variable
first_name = input('Enter FIRST name here: ')
fname = first_name
while True:
fname = first_name
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
first_name = input('Enter FIRST name here: ')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
last_name = input('Enter LAST name here: ')
lname= last_name
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()
This question already has answers here:
How can I add new keys to a dictionary?
(19 answers)
Closed 4 years ago.
I am creating records in dict data type in python. How can I add new items in the dict by using while loop as we do in tuples by using:
tuple += (rec)
When I use this code it will add elements in the tuple no matter how much. How to perform the same task with a dict
while True:
name = input('Student Name: ')
while True:
course = input('Course Name: ')
courses.append(course)
print('You have entered', len(courses), 'course(s)')
ch_course = input('Would you like to add a new course [Y]or[N]: ')
if ch_course == 'y' or ch_course == 'Y':
continue
else:
stdrec = ({name : courses})
break
ch_name = input('Would you like to add a new record [Y]or[N]: ')
if ch_name == 'n' or ch_name == 'N':
print(stdrec)
break
To add to a dict named stdrecs, you would store a new key/value pair, i.e stdrecs[name] = courses. This would look like:
stdrecs = {}
while True:
name = input('Student Name: ')
courses = []
while True:
course = input('Course Name: ')
courses.append(course)
print('You have entered', len(courses), 'course(s)')
ch_course = input('Would you like to add a new course [Y]or[N]: ')
if ch_course.upper() == 'Y':
continue
else:
stdrecs[name] = courses
break
ch_name = input('Would you like to add a new record [Y]or[N]: ')
if ch_name.upper() == 'N':
print(stdrecs)
break
I am attempting to create a program that asks for the user to enter his/her name and records the input into a list (Was working towards dictionary but seems like I made a boo boo!) but it is returning with "TypeError: can only concatenate list (not "str") to list". The following is the code.Thanks in advance.
namedic = []
while True:
print ("Please, enter your name:")
name = input()
if len(name) > 3:
print ("Welcome")
else:
print ("Ew, your name have less than 4 letters! Gross! Try a new one")
continue
namedic = namedic + name
print ("Ah, your name have at least 4 words, good name.")
for name in namedic:
print (name)
Your erroring line is namedic = namedic + name. What you're trying to do is add a list (namedic) to a string (name). You should do namedic.append(name) instead.
The + operator isn't used to append elements to a list, as the error shows. You can use the append method for that:
namedic.append(name)
#your code should rather be like this;
namedic = []
while True:
print ("Please, enter your name:")
name = input()
if len(name) > 3:
print ("Welcome")
else:
print ("Ew, your name have less than 4 letters! Gross! Try a new one")
continue
namedic.append(name)
print ("Ah, your name have at least 4 words, good name.")
for name in namedic:
print (name)
I am new to Python. I am trying to run the following code. But every time I try to run it, the IDE says that the break is outside the loop
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Can you please help me?
Thanks
You use break when you want to break free from a loop, to exit the loop, to jump to the nearest code after the loop.
Your code doesn't contain a loop, so nothing to break free from, hence the error.
I think you meant exit() instead of break
You use "break" just inside the loop ("for" or "while"), you are trying use brake inside the "if"
How about this:
if name != '':
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Your break statement is not in a loop, it's just inside an if statement.
But maybe you want to do something like the following.
If you want to let the user enter an random number of names and print the names out, when the user entered nothing, you can do the following:
# Here we declare the list in which we want to save the names
catnames = []
# start endless loop
while True:
# get the input (choose the line which fits your Python version)
# comment out the other or delete it
name = input("Enter the name of a cat\n") # input is for Python 3
# name = raw_input("Enter the name of a cat\n") # raw_input is for Python 2
# break loop if name is a empty string
if name == '':
break
# append name to the list catnames
catnames.append(name)
print("The cat names are :")
# print the names
for name in catnames:
print(name)
What you are looking for is exit().
However, your code has also other problems, here is a piece of code that does what you probably want (when prompted, enter the names separated by spaces, like: Cat1 Cat2):
name = raw_input("Enter the name of the cats: ")
if len(name) == 0:
exit()
print("\nThe cat Names are:")
for c_name in name.split():
print(c_name)
If this is the entirety of your code, then it's telling you exactly what the problem is:
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
You have a break statement in the code that's not contained inside a loop. What do you expect the code above to do?