How can I end while loop and skip for loop? - python

How do I make it where if the user enters 'no' the program won't go through the for loop either. I don't want it to tmpfile.write(line) if the user enters 'no'.
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
break # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')

Set a flag variable and then break out of the while loop. Then in the for loop, check if the flag is set, and then break.
PS: if is not a loop

The easiest way to do this is to create a function that gets user input:
def get_yes_or_no(message):
while True:
user_in = raw_input(message).lower()
if user_in in ("yes", "no"):
return user_in
And modify your original function like so:
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname.upper() in line:
answer = get_yes_or_no('Are you sure you want to remove ' + line.upper() + '?')
#answer logic goes here
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')

Python has exceptions, which you can use in place of a GOTO type of construction.
class Breakout(Exception):
pass
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
try:
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
raise Breakout()
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
except Breakout:
pass
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Notice where in exception is raised in the middle there.

You have to put the whole for loop in a function and use return to get out of it:
def find_and_remove(f,coname,tmpfile):
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
return # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
find_and_remove(f,coname,tmpfile)
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')

Instead of using an infinite loop and breaking when you skip a line, differentiate between the three cases (skip, remove, and invalid answer) using a flag in the loop condition. You set the flag to exit the loop in the skip case, break in the remove case, and leave the flag as-is in the invalid answer case. This lets you use the else clause of the while (which is triggered if the while exits because the condition became false) to detect the skip case. From there, you can jump ahead to the next iteration of the for loop using continue (or skip all the rest of the lines using break - it isn't quite clear from the question which you intend, but the difference is change of keyword):
for line in f:
if coname.upper() in line:
answered = False
while not answered:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
break
elif answer == 'no':
answered = True # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
continue
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'

Related

Read the 3 next lines in python file

I want to read the 3 next lines in a file but from a given point
If a user is in the phonebook I display the user and the 3 next lines -> code snippet
import re
phonebook_rule = re.compile(r'\'\D{3,6}\'\'\D{3,13}\'\'\d{10}\'')
def myFunction(phonebooke):
print(phonebooke)
if begin == 1:
firstname = input('enter a firstname:')
lastname = input('enter a lastname:')
phone = input('enter a number:')
imp = (f'\'{firstname}\'\'{lastname}\'\'{phone}\'')
if phonebook_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Fristname: ' + firstname + '\n')
phbook.write('Lastname: ' + lastname + '\n')
phbook.write('Phone: ' + phone + '\n')
phbook.close()
else:
print('Not a good format')
elif begin == 2:
search = input('Search a user:')
cnt = 1
if search in phbook.read():
print('This user is in the phonebook')
while True:
print(phbook.readlines())
cnt += 1
if cnt == 3:
break
else:
print('No user found')
else:
print('nothing')
begin = int(input('Chose a number 1 to 4:'))
print(myFunction(begin))
Don't know how to do this , especially the part when I need to start from "search" input and then display the 3 other lines...
Edit:
That's the only things I get with readlines()
There's a user called Matt in my phonebook or maybe I did something wrong ?
It might help to reinitialize the file object. I suspect that this is will do what you're looking for.
search = input('Search a user:')
phbook.close()
phbook = open('Phonebook','r')
for line in phbook:
line = line.strip()
if search in line:
print('This user is in the phonebook')
print(line) # print the line where you found the string
for _ in range(2):
print(phbook.readline()) # print the next 2 lines
break
else:
print('No user found')

Function is not getting called

I have below code where I have two functions print_menu() and pStockName()
def print_menu():
print ("\t\t\t\t 1. Get Stock Series ")
print ("\t\t\t\t 2. Invoke Stocks.")
print ("\t\t\t\t 3. Generate DC Stock List . ")
print ("\t\t\t\t 4. QUIT")
def pStockName():
global StockList, fStockList
pStockList = []
fStockList = []
StockList = str(raw_input('Enter pipe separated list of StockS : ')).upper().strip()
items = StockList.split("|")
count = len(items)
print 'Total Distint Stock Count : ', count
items = list(set(StockList.split("|")))
# pipelst = StockList.split('|')
# pipelst = [i.split('-mc')[0] for i in StockList.split('|')]
# pipelst = [i.replace('-mc','').replace('-MC','').replace('$','').replace('^','') for i in StockList.split('|')]
pipelst = [i.replace('-mc', '').replace('-MC', '').replace('$', '').replace('^', '') for i in items]
# pipelst = [Stock.rsplit('-mc',1)[0] for Stock in pipelst]
filepath = '/location/Stock_data.txt'
f = open(filepath, 'r')
for lns in f:
split_pipe = lns.split(':', 1)
if split_pipe[0] in pipelst:
index = pipelst.index(split_pipe[0])
pStockList = split_pipe[0] + "|"
fStockList.append(pStockList)
del pipelst[index]
# f.close()
for lns in pipelst:
print bcolors.red + lns, ' is wrong Stock Name' + bcolors.ENDC
if lns:
uResp = str(raw_input('Do You Want To Continue with option 0 [YES|Y|NO|N] : ')).upper().strip()
if uResp == "NO" or uResp == "N":
os.system("tput clear")
print bcolors.FAIL + "\n PLEASE USE OPTION 0 TO ENTER THE Stock NAMES BEFORE PROCEEDING." + bcolors.ENDC
# StockList = None
print_menu()
else:
pStockName()
f.close()
In above code you must be seeing in 4th last line I am calling print_menu() function. But it is just printing the content of print_menu() function not doing any operation and going to pStockName() function. Follow operation I want to execute from print_menu() function when I am calling it:
while choice >= 1 and choice < 4:
if choice == 4:
os.system("tput clear")
if StockList:
uResp = str(raw_input(
bcolors.FAIL + 'Do you need to move : ' + StockList + ' ? Press Y To Go Back to Main Menu and N to Quit [YES|Y|NO|N] : ')).upper()
if uResp == "NO" or uResp == "N":
print bcolors.HEADER + "GoodBye." + bcolors.ENDC
break
I mean to say when I am calling print_menu() function in pStockName() function in 4th last line from pStockName() function it should print the content of print_menu() function and when I press 4 it should perform the operation quit. But when I pressing any of the option from 1 to 4 it going to pStockName() function only.
Please help me what I am doing wrong here.
I'm a bit new here, but I do not see where you assign the keyboard input into variable "choice". Therefore, the program will not recognize what the end user input is. My suggestion is to assign "choice" into raw_input Like so:
choice = raw_input()
if choice == "4": # alternatively, perform int(choice) == 4
print ("yes")
I hope this helps!

completing a function fully

I AM NEW TO PYTHON AND CODING IN GENERAL.
So I have a program with a menu that has multiple functions in it. individually each function works fine on its own, however when i put them together they would usually not fully execute and instead stop half way or wont work at all.
EXAMPLE- the function remove wont remove what i tell it to.
def show_coffee will only show the first description and weight only and nothing else.
What can i do to make the functions fully execute?
import os
def main():
choice =''
fun=[]
while choice != 4:
menu()
choice=getUserChoice()
if choice !=4:
fun=process_choice(choice,fun)
print(fun)
print("Goodby!")
def process_choice(choice,fun):
#fun=fun1
if choice == 0:
fun=add_coffee(fun)
elif choice == 1:
fun=show_coffee(fun)
elif choice == 2:
fun=search_coffee(fun)
elif choice == 3:
fun=modify_coffee(fun)
else:
print(choice,"is not a valid choice.")
return fun
def add_coffee(fun):
another= 'y'
coffee_file=open('coffee.txt', 'a')
Description={}
while another == 'y' or another == 'Y':
print('Enter the following coffee data:')
descr=input('Description: ')
qty= int(input('Quantity (in pounds): '))
coffee_file.write(descr + '\n')
coffee_file.write(str(qty) + '\n')
print("Do you want to add another record?")
another = input("Y=yes, anything else =no: ")
return fun
coffee_file.close()
print('Data append to coffee.txt.')
def show_coffee(fun2):
coffee_file=open ('coffee.txt', 'r')
descr=coffee_file.readline()
while descr != "":
qty= str(coffee_file.readline())
descr=descr.rstrip('\n')
print('Description:', descr)
print('Quantity:', qty)
descr= coffee_file.readline()
fun=fun2
return fun
coffee_file.close()
def search_coffee(fun3):
found=False
search =input('Enter a description to search for: ')
coffee_file=open('coffee.txt', 'r')
descr=coffee_file.readline()
while descr != '':
qty= float(coffee_file.readline())
descr = descr.rstrip('\n')
if descr== search:
print('Description:', descr)
print('Quantity:', qty)
found=True
descr=coffee_file.readline()
fun=fun3
return fun
coffee_file.close()
if not found:
print('That item was not found in the file.')
def modify_coffee(fun4):
found=False
search=input('Which coffee do you want to delete? ')
coffee_file=open('coffee.txt', 'r')
temp_file=open('temp.txt', 'w')
descr=coffee_file.readline()
while descr != '':
qty=float(coffee_file.readline())
descr=descr.rstrip('\n')
if descr !=search:
temp_file.write(descr + '\n')
temp_file.write(str(qty) + '\n')
else:
found=True
descr=coffee_file.readline()
fun=fun4
return fun
coffee_file.close()
temp_file.close()
os.remove('coffee.txt')
os.rename('temp.txt', 'coffee.txt')
if found:
print('The file has been update.')
else:
print('The item was not found in the file.')
def menu():
print('''
0. Add or Update an entry
1. Show an entry
2. Search
3. remove
4. Remove number
''')
def getUserChoice():
choice=-1
while choice <0 or choice > 3:
print("Please select 0-3: ",end='')
choice=int(input())
return choice
You are defining functions but this does not call a function. The standard way to do this in Python is use the if __name__=="__main__": statement at the bottom of a file. When the file is executed (instead of functions/classes being imported by another script) the code block within the scope of if __name__=="__main__": is executed.
Get comfortable with this, it's useful and clean :) Good read - What does if __name__ == "__main__": do?
So, for example...
At the bottom of your file...
if __name__=="__main__":
main()

Anything other than the variable Python

I am very much new to Python and basically want anything other than d or o to rerun the question? Any help?
Myfile = raw_input( '''Specify filename (o) or use default chain (d)? ''')
if Myfile == 'd':
print 'default choosen '
Myfile = 'M:/test/testchains_a.csv'
if Myfile == 'o':
print 'own file choosen '
Myfile = raw_input('Enter absolute path to the .csv file:')
else:
print 'successful'
You could use a while loop to check whether or not the input is and 'o' or a 'd':
MyFile = None
while MyFile != 'o' and MyFile != 'd':
Myfile = raw_input( '''Specify filename (o) or use default chain (d)? ''')
You can do this the way squiguy suggested, but it might be more readable to put the whole thing into a loop, so you don't have to repeat the same checks twice:
while True:
Myfile = raw_input( '''Specify filename (o) or use default chain (d)? ''')
if Myfile == 'd':
print 'default choosen '
Myfile = 'M:/test/testchains_a.csv'
break
elif Myfile == 'o':
print 'own file choosen '
Myfile = raw_input('Enter absolute path to the .csv file:')
break
This will loop forever, until it hits a breakā€”in other words, until they select 'd' or 'o'.
You can use a loop:
wrong = True
while(wrong):
file = raw_input("My awesome prompt")
if file == "d":
file = '/some/path'
wrong = False
if file == "o":
file = raw_input("Where?")
wrong = False
# Continue your program...
I think your actual problem here is bad UI design. The first question is superfluous and can be easily eliminated:
myfile = raw_input('Enter absolute path to the .csv file (leave blank to use the default):')
myfile = myfile or 'M:/test/testchains_a.csv'
This "hit enter to use the default" approach is quite common in dialogue programs.
To answer the question as asked, I'd suggest using a function like this:
def prompt(message, choices):
while True:
s = raw_input(message)
if s in choices:
return s
and in your main code:
option = prompt('Specify filename (o) or use default chain (d)? ', 'od')
if option == 'd':
...
elif option == 'o':
...
use elif (elseif) and else
file = input("enter (d) to use the default file or enter (c) to specify a custom path: ")
if file.lower() == "d":
print("some code")
elif file.lower() == "c":
print("some code")
else:
print("invalid answer!")
input()

A simple IF statement in python

I'm having trouble getting an "Else" statement to work.
My code looks like this so far:
roomNumber = (input("Enter the room number: "))
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == (s['Room']):
yield(s)
rb_text.close()
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
So when i do a positive search and get multiple matches in my text file, i get well organised results.
However, i'm trying to get it to tell me if invalid input data is entered and re-ask for the room number until the correct data is input.
I tried using an "Else" statement about the "Yield(s)" but it wont accept it.
Any ideas?
Python blocks are delineated by indentation so the "else:" (note lowercase and with a colon to indicate the start of a block) should be at the same indent level as the if statement.
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == (s['Room']):
yield(s)
else:
print "this print will execute if d2find != (s['Room'])"
# ... also see DrTyrsa's comment on you question.
But I suspect you don't really want to use an else clause anyway, where would you go from there? This looks an awful lot like an assignment so I'm not going to post an exact solution.
You can do it like this:
def find_details(id2find):
found = False
with open('roombookings2.txt', 'r') as rb_text:
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == s['Room']:
found = True
yield(s)
if not found:
raise ValueError("No such room number!")
while True:
roomNumber = (input("Enter the room number: "))
try:
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
break
except ValueError as e:
print str(e)

Categories