I'm trying to break the loop once Enter is pressed, while writing data to a file. This is what I have so far. I also don't want to limit the number of time the loop is run either... (example output is below)
def main():
myfile = open('friends.txt','w')
friend = input('Enter first name of friend or Enter to quit')
age = input('Enter age (integer) of this friend')
while friend != '':
for n in range():
friend = input('Enter first name of friend or Enter to quit')
age = input('Enter age (integer) of this friend')
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
myfile.close()
main()
This is how to output is supposed to be when its ran right.
Enter first name of friend or Enter to quit Sally
Enter age (integer) of this friend 20
Enter first name of friend or Enter to quit Sam
Enter age (integer) of this friend 24
Enter first name of friend or Enter to quit
File was created
def main():
myfile = open('friends.txt','w')
while True:
friend = input('Enter first name of friend or Enter to quit: ')
if not friend:
myfile.close()
break
else:
age = input('Enter age (integer) of this friend: ')
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
main()
Output:
Enter first name of friend or Enter to quit: Mack
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit: Steve
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit:
Process finished with exit code 0
You had a couple of errors in your code, such as using range() and indentation and using input for a string, when raw_input may have been a better choice.
To do what you want, you should put the write at the beginning of your loop, and after asking for the name, check if it's empty and, if it is, break. Code is below:
def main():
myfile = open('friends.txt','w')
friend = raw_input('Enter first name of friend or Enter to quit')
age = int(raw_input('Enter age (integer) of this friend'))
while friend != '':
while True:
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
friend = raw_input('Enter first name of friend or Enter to quit')
if not friend:
break
age = int(raw_input('Enter age (integer) of this friend'))
print('File was created')
myfile.close()
main()
Related
I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:
while True:
cust_name = input("Please enter primary customer name: ")
if cust_name.isalpha():
break
else:
print("Please enter valid name")
continue
while True:
cust_phone = input("Please enter phone number: ")
if cust_phone.isnumeric() and len(cust_phone) == 10:
break
else:
print("Error! Please enter correct phone number")
continue
while True:
num_travellers = input("How many people are travelling? ")
if int(num_travellers) >= 2:
break
else:
print("Please enter at least two passengers")
continue
Output:
Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2
For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:
for i in range(int(num_travellers)):
travellers = []
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
else:
print("Please enter valid name")
continue
for j in range(int(num_travellers)):
travel_age = []
age = input("Please enter passenger age: ")
if age.isnumeric():
travel_age.append(age)
else:
print("Please enter valid age")
continue
Output:
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk
I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks
You have missed while True: loop when asking for passenger data. Try something like below:
travellers = []
for i in range(int(num_travellers)):
while True:
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
break
else:
print("Please enter valid name")
continue
BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.
I have been trying to write this code and I need a way of stopping the code if a certain input is incorrect, here is what I have so far:
first_name = input('PLEASE ENTER YOUR FIRST NAME: ')
last_name = input('PLEASE ENTER YOUR SURNAME: ')
print(f'Hello {first_name} {last_name}, before you enter.')
def age_det():
age = input(f'How old are you?')
converted_age = [int(age)]
for num in converted_age:
while num>=18:
print(f'Awesome, {first_name}, welcome to Blablabla')
num += 100
while num <= 18:
break
print(f'Sorry, {first_name}, but we require you to be at least 18 to enter Blablabla.')
num += 100
age_det()
#I want the code to stop here if the age entered is under 18
username = input('Before we start, please pick a username: ')
print(f'Woah! {username}, good choice!')
Import the sys object and use an if statement to check if the age is valid. If not call sys.exit().
import sys
age = 17
if age < 18:
sys.exit()
print("Still going") # Doesn't get printed
if the age is at least 18:
import sys
age = 25
if age < 18:
sys.exit()
print("Still going") # Gets printed
First import these :-
import sys
Then add this after that "sorry we don't allow under 18" line
input('Press Enter to Continue...')
sys.exit()
Plus use if instead of while
Your code can be simplified as :-
import sys
first_name=input('PLEASE ENTER YOUR FIRST NAME: ')
last_name=input('PLEASE ENTER YOUR SURNAME: ')
print(f'Hello {first_name} {last_name}, before you enter.')
def age_det():
age = int(input(f'How old are you?'))
if num>=18:
print(f'Awesome, {first_name}, welcome to Blablabla')
else :
print(f'Sorry, {first_name}, but we require you to be at least 18 to enter Blablabla.')
input('Press Enter to Continue...')
sys.exit()
age_det()
I create a few class about pet, the following code was part of my main() function, First, ask the user to select one thing they want to do. that is if use input '1' they will add some pet instance. At the same time, I want to append part of the pet instance's information to a list. Then if the user chooses to read this information. I want to print it in another if statement branch. that is when the user input '2'. the problem occurs when I input 2 after already generating some pet instance. the list called l_weight always be void. How could I fix it? I already try to use the global list but is not work
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
return main()
elif a==2:
for i in l_weight:
print(i)
return main()
The reason l_weight() isn't appending is because in your code, you named the list l_weight and then in the rest of your code it's written as l_weigh
It should be:
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
elif a==2:
for i in l_weight:
print(i)
Doing an assignment, this is my first program so bear with me. I cant get the while loop to end although i have broke it. I need a way to get out of the loop, and what I'm doing isn't working. Any suggestions would be very helpful thank you.
def main(): #Calls the main function
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")
The problem with your code is your indentation. You have told the program to break when the marker_name is an empty string. I am assuming that you would like the code to finish when all three values are correct, so as such the following code should work for you:
def main():
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")
main()
I am a little confused why you have used a try and except? What is the purpose of it?
May I ask why the code block is wrapped in the try-except?
Some suggestions:
remove the try-except as you shouldn't be raising any errors
remove the break statement (after marker_name) as the loop should end when the input is valid
ensure the indentation of all the input while-loop code blocks are identical (your formatting is messed up so I'm not sure if you have nested while loops)
Let me know how this works
Well first of all you break out of a while loop in python with break as you did already. You should only break if a condition you set is met in the loop. So lets say you wanted to break in a while loop that counts and you want to break if the number reaches 100, however, you already had a condition for your while loop. You would then put this inside your while loop.
if x == 100:
break
As you have it now you just break in your while loop after a couple lines of code without a condition. You will only go through the loop once and then break every single time. It defeats the purpose of a while loop.
What exactly are you trying to do in this code? Can you give more detail in your question besides that you would like to break in a while loop? Maybe I can help you more than giving you this generic answer about breaking in a loop.
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