I need to take multiple inputs from user and exit from the loop when the user hits the enter key.
this is what i am trying to do.
while True:
data = input("Enter name age and score:\t").split(",")
if data==' ':
break
else:
continue
try this
data = input("Enter name age and score:")
while data.strip() != '':
data = input("Enter name age and score:")
Just check for bool value:
while True:
data = input("Enter name age and score:\t")
if not data:
break
else:
continue
Related
I was trying to check if the username entered is equal to the second index of item in the list, and I tried to use !=, but it still keeps letting the same username to be registered. What's the problem with the code ?
Registering username :
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name != user[1]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)
Editted:
The results of != and == seems to be different, the == works.
Login username :
user_list = [['std1','Daniel'],['std2','Raymond'],['std3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name == user[1]:
break # break out for loop
else:
print("Unregistered username")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Logged in as",name)
You're very close!
What you're trying to do: break out of the loop if there are any names in user_list that match the new name.
What it's currently doing: breaking out of the loop if there are any names in user_list that don't match the new name.
I.e., if you enter Daniel, since Daniel != Raymond, you will break early.
Instead, what you should do is break if the newly entered name is not present in a list of names:
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
if name in [user[1] for user in user_list]: # existing names list
print("This username has been registered")
name = input("Please try another username : ")
else:
break
print("Username registered as",name)
This code below will sort a lot of things out. In your code, even if we fix the indentation mistake with the else which should be moved into the for loop, the code won't work if we type Raymond. So I have provided an example which checks if the entered usr is in all the names in your user_list.
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name not in [lst[-1] for lst in user_list]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)
so i have this project that I should make a program to add identify or delete data from an inventory.txt file
but when I ever try to print the inputs in the file I get messy text, what I'm looking for is a table-like structure printed inputs in the .txt file, I've tried to remove and readjust the place of \n and \t but still, I get stuff like this in the file
Samsung ide445 2154SS rams 120.0 14
Logetech Specture lid224 G502 230.0 8
here's my code for a closer look:
#This function is to get the parts information from the user
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n'+make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to export the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+'\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
You can import tabulate module and use it as below example:
from tabulate import tabulate
print(tabulate([['Saeed', 26], ['You', 24]], headers=['Name', 'Age']))
Result:
Name Age
------ -----
Saeed 26
You 24
You may use this module to reach what you want.
currently I am doing my assignment. The requirement is to test the format of Student ID. I wonder why is my while loop is not working properly..
My validation check is as below:
def isValidStudentIDFormat(stid):
# studentID must have a length of 9
if(len(stid) != 9):
# return the invalid reason
return "Length of Student ID is not 9"
# studentID must starts with a letter S
if(stid[0] != 'S'):
# return the invalid reason
return "First letter is not S"
# studentID must contains 7 numbers between the two letters
for i in range(1,8):
# anything smaller than 0 or bigger than 9 would not be valid.
# so does a character, will also be invalid
if((stid[i] < '0') or (stid[i] > '9')):
# return the invalid reason
return "Not a number between letters"
if((stid[8] < 'A') or (stid[8] > 'Z')):
# return the invalid reason
return "Last letter not a characer"
# return True if the format is right
return True
My function to insert a student record is below:
def insert_student_record():
#printing the message to ask user to insert a new student into the memory
print("Insert a new student \n")
fn = input("Enter first name: ")
#check if user entered space
#strip() returns a copy of the string based on the string argument passed
while not fn.strip():
print("Empty input, please enter again")
fn = input("Enter first name: ")
ln = input("Enter last name: ")
while not ln.strip():
print("Empty input, please enter again")
ln = input("Enter last name: ")
stid = input("Enter student id: ")
while not stid.strip():
print("Empty input, please enter again")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result == True
#append the student details to each list
#append first name
fName.append(fn)
#append last name
lName.append(ln)
#append student id
sid.append(stid)
#to check if the new student is in the lists
if stid in sid:
if fn in fName:
if ln in lName:
#then print message to tell user the student record is inserted
print("A new student record is inserted.")
However, I'm getting an infinite loop even if I key in the correct format for student ID. Anyone can help ?
You compare result == True when you should assign. Still, you don't check the new student id for validity, which could be done this way:
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
?
def validateStudentIDFormat(stid):
if len(stid) != 9:
raise RuntimeError("Length of Student ID is not 9")
if stid[0] != 'S':
raise RuntimeError("First letter is not S")
for char in stid[1:-1]:
if char.isnumeric():
raise RuntimeError("Not a number between letters")
if not stid[-1].isalpha():
raise RuntimeError("Last letter not a characer")
....
while True:
stid = input("Enter student id: ")
try:
validateStudentIDFormat(stid)
except RuntimeError as ex:
print(ex)
print("Invalid student id format. Please check and enter again.")
else:
break
So I have for example the following while statements and I would like to combine them. Because this can get tiresome if you have 20 of these with all different if statements.
while True:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
break
print("Please chars dude")
while True:
age = raw_input("Please type your age\n")
if age.isdigit():
break
print("Please digits only")
If I combine them and someone types a A-Z character with 'age' then the code restarts all over without having saved the 'name' statement. I would like it to save 'name' if it's correct and only start over from the if statement that was false.
while True:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
break
print("Please chars dude")
age = raw_input("Please type your age\n")
if age.isdigit():
break
print("Please digits only")
Use a function to encapsulate asking for information. You can pass in a validation test function:
def ask(question, validator, errormessage):
while True:
result = raw_input(question)
if not validator(result):
print(errormessage)
continue
return result
name = ask("NAME PLEASE\n", lambda s: s.isalpha(), "Please chars dude")
age = ask("Please type your age\n", lambda s: s.isdigit(), "Please digits only")
This is far more readable then any number of tests to see if the user already entered a correct name and you only need to ask for the age now.
Why not use functions and cut down on some duplication in the process?
def ask_input(prompt, error_msg, validation_fn):
while True:
data = raw_input(prompt)
if validation_fn(data):
return data
print(error_msg)
name = ask_input("NAME PLEASE\n", "Please chars dude", lambda x: x.isalpha())
age = ask_input("Please type your age\n", "Please digits only",
lambda x: x.isdigit())
In this case, the prompt (what to ask the user), an error message (what to provide on invalid input), and a validation function are provided to the ask_input() function. This hides the while loop behind the function call and gives you something more meaningful to read in the code.
The lambda functions are just an easy way to help do the validation. You could do this instead:
def isalpha(x):
return x.isalpha()
def isdigit(x):
return x.isdigit()
name = ask_input("NAME PLEASE\n", "Please chars dude", isalpha)
age = ask_input("Please type your age\n", "Please digits only", isdigit)
You can set the variables to None first, and then check them before assignment:
name, age = None, None
while True:
if name is None:
name = str(raw_input("NAME PLEASE\n"))
if not name.isalpha():
print("Please chars dude")
name = None
continue
if age is None:
age = raw_input("Please type your age\n")
if not age.isdigit():
print("Please digits only")
age = None
continue
print("input is valid")
break
continue will start the loop over again. This fits better in the logic of your code, since break actually stop and exit the loop code.
Just use flags to track weather valid input is given, if given then exit the loop.
name_input_required = True
name = ''
while name_input_required:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
name_input_required = False
else:
print("Please chars dude")
age_input_required = True
age = None
while age_input_required:
age = raw_input("Please type your age\n")
if age.isdigit():
age_input_required = False
else:
print("Please digits only")
Try this:
name = None
age = None
while requires_info:
if name is None:
temp_name = str(raw_input("NAME PLEASE\n"))
if temp_name.isalpha():
name = temp_name
continue
else:
print("Please chars dude")
continue
if age is None:
temp_age = raw_input("Please type your age\n")
if temp_age.isdigit():
age = temp_age
continue
else:
print("Please digits only")
continue
break
What we do here is use a single continuous loop and a few if statements/variables to track what still needs to be done. Note depending on how you want them to enter the data you may also add logic to not ask for age if the name was invalid.
So I have for example the following while statements and I would like to combine them. Because this can get tiresome if you have 20 of these with all different if statements.
I assume the actual problem is "How to reduce tiresome code?" instead of "How to merge two loops into one?". I think keeping two loops is a good idea.
def safe_input(prompt, err_message, validation_fn):
while True:
value = raw_input(prompt)
if validation_fn(value):
return value
print err_message
name = safe_input("NAME PLEASE\n", "Please chars dude", str.isalpha)
age = safe_input("Please type your age\n", "Please digits only", str.isdigit)
If you always want the used to enter text in a separate line, you might want to print prompt before raw_input and to not give an argument to raw_input. That way you don't have to supply "\n" in every call of safe_input.
Yes, you can combine both loops in one loop!
Always try to solve the problem line by line.
You will get to learn the language better and it is the most simple way to solve any problem too.
A line by line solution would look like this:
name = '' # define name outside while loop
while True:
if not name:
name = str(raw_input("NAME PLEASE\n"))
if not name.isalpha(): # validate name
print("Please chars dude")
# reset name
name = ''
else:
age = raw_input("Please type your age\n")
if age.isdigit(): # validate age
"""continue your code here"""
print('name: ' + name + ' and age: ' + age)
print('Ok! Goodbye!')
break # while loop
else:
print("Please digits only")
will print:
NAME PLEASE
Elis
Please type your age
30
name: Elis and age: 30
Ok! Goodbye!
This will help you understand while loop better and how to use it in more difficult cases.
Do not over design using redundant language features. It will make refactoring and debugging difficult.
I do need help in solving my code.
Below python code 'continue' is not working properly
dicemp = {'12345':''}
while(1):
choice = int(input("Please enter your choice\n"))
if (choice == 1):
empno = input("Enter employee number: ")
for i in dicemp.keys():
if i == empno:
print("employee already exists in the database")
continue
print("Hello")
Output:
Please enter your choice
1
Enter employee number: 12345
employee already exists in the database
Hello
So for the above code if I give same employee no. 12345 it is going into if block and printing the message"employee already exists in the database" after this it should continue from start but in this case it is also printing "hello".
Your continue is moving the for loop on to its next iteration, which would have happened anyway. If you need to continue the outer loop, you can do something like this:
while True:
choice = int(input("Please enter your choice\n"))
if choice == 1:
empno = input("Enter employee number: ")
found = False
for i in dicemp:
if i == empno:
print("employee already exists in the database")
found = True
break
if found:
continue
print("Hello")
Now the continue is outside the for loop, so it will continue the outer loop.
You could simplify this to:
while True:
choice = int(input("Please enter your choice\n"))
if choice==1:
empno = input("Enter employee number: ")
if empno in dicemp:
print("employee already exists in the database")
continue
print("Hello")
and get rid of the inner loop entirely.