I have some code:
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
How can I keep asking for the player's name until they enter a name that is more than one character long, and tell them they must enter a valid name if they leave the field blank?
I tried
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
while len(PlayerName) < 1:
print("You must enter a name!")
but have been unsuccessful.
Use a while loop to get the input repetitively:
def get_player_name():
print()
player_name = ""
while len(player_name) <= 1:
player_name = input('Please enter your name: ')
print()
return player_name
The way you are currently using it, you use the while statement to only print the error message.
PS: I've converted your variable names etc to small_caps_format because that is what PEP recommends.
def GetPlayerName():
print()
while True:
PlayerName = input('Please enter your name: ')
if len(PlayerName) > 1:
break
print("Your name is too short! :c")
print()
return PlayerName
One solution amongst others, and doesn't require any variables outside of the while loop. As mentioned by #jme, the error message is rather easy to print with this solution. The issue with your code is that:
Your while loop is after the return statement is called, so it's affectively rendered mute.
Your while loop is infinite-- it doesn't give the user a chance to re-try!
Related
this is my first day of coding in python so I don't know how "clean" my code is. I am trying to make a fun piece of code, that makes you add your name, and correctly re-enter it right after
name = input ("Insert name:")
print ("re-enter your name")
answer = name
if answer == name
print ("excellent")
elif
print ("You have entered the wrong name")
exit()
since you create variable answer = name, the result will always be true because the answer variable and name variable will have the same contents in memory.
Oh yes, I ran your code and there was an error. After the code if some_condition must be added a colon after it in one line, elif is like that, in using elif you must have a conditional after elif and then a colon. If you only have one conditional for the if, then use else instead of elif.
Here's your code after fixing:
name = input("Insert name:")
answer = input("re-enter your name")
if answer == name:
print ("excellent")
else:
print ("You have entered the wrong name")
exit()
CMIWW
You need to take a second input to re-enter your name. answer=name is basically assigning answer name. So you will always end up with answer==name
Also, a colon missing after if.... The elif statement is completely useless. You might want to use else there because you only want answer==name else redirect them to You have entered the wrong name
name = input ("Insert name: ")
answer = input("re-enter your name: ")
if answer == name:
print ("excellent")
else:
print ("You have entered the wrong name")
Output 1:
Insert name: John
re-enter your name: jon
You have entered the wrong name
Output 2:
Insert name: Mike
re-enter your name: Mike
excellent
name = input("Insert your nme : ")
rename_name = input("Re-enter your name : ")
if name == rename_name:
print("excellent")
else:
print("You have entered the wrong name")
It's unclear whether objective is just to verify that second entry is same as first or make sure that they match. If latter then second input must be in loop ('while first answer is not equal to second print warning and ask again, if answers match print Excellent') :
first = input("Enter your name: ")
while first != input("Enter your name again: "):
print("Names entered don't match!")
else:
print('Excellent')
Here is one of the cleanest code you would likeπππ You don't have to exit from condition using any exit function. And in second line, you were just printing "re-enter your name: " not receiving any inputs.
name = input ("Insert name: ")
answer = input("re-enter your name: ")
print ("excellent" if answer == name else "You have entered the wrong name")
So I have an If-elif statement that I want to print some text and loop if the else condition is met. Here is the code:
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for specific user data\n3. kwin - Search a keyword in a specific user\n4. allin - Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
When people mess up and don't put one of the options properly, I want to loop back to the if statement so that when they put in the right one, the loop will end and the rest of the code will continue.
I tried a for loop and wrapped it all as a function but it would end up in an infinite loop of printing the error message. Is there a way to do it with a while loop? Do I need to block it ad a function to repeat it?
Thanks in advance!
In Python, the most idiomatic thing I see for this is while True:
while True:
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
continue
break
You can use a while loop and break statement. You can also reduce the elif statement as I see duplicate code.
Also, you can reduce the user error by converting the search_mode to lowercase.
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for
specific user data\n3. kwin - Search a keyword in a specific user\n4. allin -
Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
while True:
if "s" in search_mode.lower():
kwsearch = input("What Keyword do you want to use?: ")
break
elif search_mode.lower() in ('u','kwin','allin'):
username = input("What is the username?: ")
if "kwin" in search_mode.lower():
kwinword = input("What is the keyword?: ")
break
else:
print("Error. Please check spelling and capitalization")
search_mode = input("How would you like to search?: ")
The code enters the while loop after accepting value into variable search_mode.
If the value is 's', it asks for the keyword and breaks the loop.
if the value is not 's', then it checks if the value is 'u' or 'kwin' or 'allin'. If it is any of these, then it asks for the username. If the value is kwin, it also asks for keyword. Then it breaks the loop.
If the value is none of the above, it prints the error statement and asks the user the question again. It goes into the loop again with the new value from the user and checks the conditions again. It will exit only when the if or elif statement is true. Hope this helps.
I was messing around and wanted to see if I could get this simple program to work. I want to check the user input against my list and output whether or not it is in the list. How I have it setup up currently it will return for the 0 index but not the other two. What am I doing wrong?
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name == check_name[0]:
print("Welcome lisa")
if name == check_name[1]:
print("Welcome jim")
elif name == check_name[2]:
print("Welcome betty")
pass
else:
print("Sorry, Looks like you are not in the system")
pass
Your last two if statements are only evaluating nested inside of the first one. You need to unindent them so that they'll evaluate if the first does not.
Another solution:
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name not in check_name:
print("Sorry, Looks like you are not in the system")
You have an indentation problem.
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name == check_name[0]:
print("Welcome lisa")
elif name == check_name[1]:
print("Welcome Jim")
elif name == check_name[2]:
print("Welcome Betty")
else:
print("Sorry, Looks like you are not in the system")
You already got your answer above. Here is an alternate solution negating the need of multiple if statements making your code concise:
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name in check_name:
print("Welcome %s" %name)
else:
print("Sorry, Looks like you are not in the system")
The command if name in check_name: checks if the input name exists in the name list and welcomes the corresponding person. If the input name doesn't exist, it throws the Sorry... statement
My goal is to make sure when the user types in numbers in the userName input, then it should not accept it and make them try again.
Same thing with userNumber. When a user types in letters, they should be prompted with another line telling them to try again.
The problem is that when they do type in the correct input, the program will continue looping and listing the numbers indefinitely.
I'm new to coding, and I'm trying to figure out what I'm doing wrong. Thank you in advance!
userName = input('Hello there, civilian! What is your name? ')
while True:
if userName.isalpha() == True:
print('It is nice to meet you, ' + userName + "! ")
else:
print('Choose a valid name!')
userNumber = input('Please pick any number between 3-100. ')
while True:
if userNumber.isnumeric() == True:
for i in range(0,int(userNumber) + 1,2):
print(i)
else:
print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')
You never stop the loop. There's two ways to do this: either change the loop condition (while true loops forever), or break out from within.
In this case, it's easier with break:
while True:
# The input() call should be inside the loop:
userName = input('Hello there, civilian! What is your name? ')
if userName.isalpha(): # you don't need `== True`
print('It is nice to meet you, ' + userName + "! ")
break # this stops the loop
else:
print('Choose a valid name!')
The second loop has the same problem, with the same solution and additional corrections.
Alternative way: use a condition in your while loops.
userName = ''
userNumber = ''
while not userName.isalpha():
if userName: print('Choose a valid name!')
userName = input('Hello there, civilian! What is your name? ')
print('It is nice to meet you, ' + userName + "! ")
while not userNumber.isnumeric():
if userNumber: print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')
for i in range(0,int(userNumber) + 1,2):
print(i)
Firstly, I am new to Python so please go easy on me... Secondly, I've never used a forum before so if I paste too much code or don't give exactly what you need, forgive me, I shall try my best:
WHAT I NEED MY CODE TO DO:
I need my code to ask the user for an input called moduleName then after moduleName is entered I need it to ask the user for the grade for that specific module. After that is entered I need it to ask again for module then the grade until there are no more to enter where by the user will enter -1 into the module bit to end it. I also need each item to save to a global list I have created. So when I use teh function I have created to view the list it prints out all modules and grades.
MY CODE THUS FAR: (my global list is at top of code named students[])
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
**moduleName= 0
while moduleName != "-1":
moduleName = raw_input("Please enter module name: ")
grade = raw_input ("Please enter students grade for " + moduleName+": ")
students.append(student)**
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
THE OUTPUT I GET:
I have now fixed the loop so it breaks correctly... the only problem I have now is that the moduleName and grade fields save to my global list but only save the last input (being -1) as opposed to the multiple inputs entered... so confused.
The problem may also lie within this function I have created:
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
Again apologies I don't know what's needed on forums etc so go easy on me...
Thank in Advance! =D
I would suggest replacing the while moduleName != "-1": loop with a while True: loop, and then insert this code after asking for the module name:
if moduleName == '-1':
break
This will break out of the while loop when you want it to.
Addressing your second question, the append function is in the else bit of the whole while loop. This means that it only works when the function breaks. You need to put this in the main while loop after you get the input, and get rid of the else.
Also, I don't see student defined anywhere - what is it meant to be?
Here's the code you want:
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == '-1':
break
grade = raw_input("Please enter students grade for " + moduleName+": ")
students.append(student)