How to change condition from a while loop - python

I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :
book_list = []
def add_books(books):
book_record = {}
completed = "no"
while completed == "no":
title = input("Enter title : ")
author = input("Enter author : ")
year = input("Enter year of publication : ")
book_record.update({"title": title, "author": author, "year_publ": year})
books.append(book_record)
print(books)
completed = input("update completed ? yes/no")
return books
def display_books(books):
for book in books:
title = book["title"]
author = book["author"]
year = book["year_publ"]
print(f"{title}, {author}, {year}")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
while option != "q" :
if option == "a":
book_list = add_books(book_list)
elif option == "d":
display_books(book_list)
else:
print("Invalid Option")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.
What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?
Appreciate any help.
Thanks and Regards
Sachin

So the problem is with the option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :"). You are asking only one time for the option, what you need is an endless loop to continue asking for the new option. On your approach when the "user" chooses the "a" option he/she never gets asked again so the options still remains on "a" thus the add_books() function running endless!
You should change the last part to:
while True:
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
if option == "a":
book_list = add_books(book_list)
elif option == "d":
display_books(book_list)
elif option == "q":
quit()
else:
print("Invalid Option")

Did you tried this?:
def add_books(books):
book_record = {}
completed = "no"
while True:
title = input("Enter title : ")
author = input("Enter author : ")
year = input("Enter year of publication : ")
book_record.update({"title": title, "author": author, "year_publ": year})
books.append(book_record)
print(books)
completed = input("update completed ? yes/no")
if completed == 'yes':
break
return books

Your code keeps asking because option still is "a" after add_books has finished, and your "main" loop does not get a new value for option from the user.
Always make the "Do you want to continue?" question part of the loop.
I would recommend to use endless loops (while True:) with a conditional break for these kinds of tasks. It's easier to follow (in my opinion):
Like this - I've added a helper function input_letter that returns the trimmed, lower-case first letter of the user's response, for easier management later):
book_list = []
def input_letter(prompt):
return input(prompt).strip().lower()[0::1]
def add_books(books):
while True:
title = input("Enter title: ")
author = input("Enter author: ")
year = input("Enter year of publication: ")
books.append({"title": title, "author": author, "year_publ": year})
if input_letter("More? (y)es / (n)o ") == "y":
break
return books
def display_books(books):
for book in books:
title = book["title"]
author = book["author"]
year = book["year_publ"]
print(f"{title}, {author}, {year}")
while True:
option = input_letter("(a)dd book, (d)isplay books, (q)uit: ")
if option == "a":
add_books(book_list)
elif option == "d":
display_books(book_list)
elif option == "q":
break

if you whant to keep ypur code use:
another condintion to tell the loop that the completed have been updated and quit it!
book_list = []
def add_books(books):
book_record = {}
completed = "no"
while completed == "no":
title = input("Enter title : ")
author = input("Enter author : ")
year = input("Enter year of publication : ")
book_record.update({"title": title, "author": author, "year_publ": year})
books.append(book_record)
print(books)
completed = input("update completed ? yes/no")
if completed == "yes":
completed = completed
break
return books
def display_books(books):
for book in books:
title = book["title"]
author = book["author"]
year = book["year_publ"]
print(f"{title}, {author}, {year}")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
while option != "q" :
if option == "a":
book_list = add_books(book_list)
elif option == "d":
display_books(book_list)
else:
print("Invalid Option")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

Related

Python Shopping Cart with only outer while loop

I'm new to python and programming in general.
I'm starting with my first mini project, a shopping cart.
I have everything working but I have been told I could get the whole loop going with just the outer one and that I do not require the second one. I've been wracking my brain all day trying to see how to get it to work, to no avail. Some pointers of how it can be achieved would be very much appreciated. Thank you.
shopping_list = []
print("Hi, Welcome to Jolly's Market.")
while True:
customer = input("To add to the shopping cart, press 1. To checkout and leave press 2.\n")
if customer == "1":
print("To return to the menu, type exit . To remove items, type r")
while customer != "exit" or customer != "r":
shopping_list.append(input("Add to cart: "))
print(shopping_list)
customer = input("").lower()
if customer == "exit":
print("Sending you back to the menu")
break
if customer == "r":
shopping_list.pop(int(input("Remove item ")))
print(shopping_list)
shopping_list.append(input("Add to cart: "))
print(shopping_list)
customer = input("").lower()
if len(shopping_list) == 10:
print("You have ten items, do you wish to add more? (y, n)")
customer = input(" ").lower()
if customer == "y":
shopping_list.append(input("Add to cart: "))
elif customer == "n":
print("Sending you back to the main menu")
break
The inner while loop is not required because it can be done with only the outer while loop.
Here's how you can modify the code:
shopping_list = []
print("Hi, Welcome to Jolly's Market.")
while True:
customer = input("To add to the shopping cart, press 1. To checkout and leave press 2.\n")
if customer == "1":
print("To return to the menu, type exit . To remove items, type r")
item = input("Add to cart: ")
shopping_list.append(item)
print(shopping_list)
customer = input("").lower()
if customer == "exit":
print("Sending you back to the menu")
continue
if customer == "r":
shopping_list.pop(int(input("Remove item ")))
print(shopping_list)
item = input("Add to cart: ")
shopping_list.append(item)
print(shopping_list)
customer = input("").lower()
if len(shopping_list) == 10:
print("You have ten items, do you wish to add more? (y, n)")
customer = input(" ").lower()
if customer == "y":
item = input("Add to cart: ")
shopping_list.append(item)
elif customer == "n":
print("Sending you back to the main menu")
continue
elif customer == "2":
break
Here, the inner while loop is not required because the menu options are already in the outer loop. When the user types 1, the shopping list is updated, and then the user is asked to either add or remove items. If the length of the shopping list reaches 10, the user is asked if they want to add more. If the user types exit or n, they are sent back to the main menu. If the user types 2, the while loop breaks and the program ends.
Here's a revised version of the code that will let you continuously add items to the shopping list without being taken back to the main menu after each item, until you reach 10 items or decide to exit:
shopping_list = []
print("Hi, Welcome to Jolly's Market.")
while True:
customer = input("To add to the shopping cart, press 1. To checkout and leave press 2.\n")
if customer == "1":
print("To return to the menu, type exit . To remove items, type r")
while True:
item = input("Add to cart: ")
shopping_list.append(item)
print(shopping_list)
if len(shopping_list) == 10:
print("You have ten items, do you wish to add more? (y, n)")
customer = input(" ").lower()
if customer == "n":
break
else:
continue
customer = input("").lower()
if customer == "exit":
print("Sending you back to the menu")
break
if customer == "r":
shopping_list.pop(int(input("Remove item ")))
print(shopping_list)
continue
elif customer == "2":
break

Unable to pass/exit a python function

Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!

How to continue running a loop in Python

I am trying to create a phone book and I have everything except I need to run the entire code over and over instead an individual if statement. I am not sure how to continue any advice?
I have used a while loop.
#Intro
print("Address book to store friends contact")
print("-" * 50)
print("-" * 50)
#Display of options
print("Select an option: ")
print("1-Add/Update contact")
print("2- Display all contacts")
print("3- Search")
print("4- Delete contact")
print("5- Quit")
#Selection
option = input("Select which one you would like to choose. Ex. Select an
option. Type here: ")
#Map
contacts = {}
#Main program
for i in range(0,1):
if option == "Add/Update contact":
person_added = input("Who would you like to be updated or added")
next_question = input("What is there contact information")
#The code below will add the person to the list or update them
contacts [person_added] = next_question
elif option == "Display all contacts":
print(contacts)
elif option == "Search":
search_question = input("Who are you looking for: ")
for search in contacts.items():
if search == search_question:
print("I found" + search)
else:
print("Contact not found")
elif option == "Delete contact":
person_deleted = input("Who would you like to be deleted ")
del(contacts[person_deleted])
else:
print("Thank You! Goodbye")

When logged in Start Quiz

I would like a little bit of help because Im confused and also really stuck on this. I would like to point out that I am a bigger on python so please take it easy.
I am trying to create a simple quiz with a login/register dictionary system. I am also trying to keep all my "Registered Users" in a .txt file but i can't do that unfortunately so if anyone can help I would be delighted!
The problem is, when a users logs in or -registers i would like the quiz bit to run, but instead the login/register runs in a loop unless i take away the while statement, but if I do take it away the login/register script does not run at all. So what i need is.....
When my program runs, I want it to run the login/register script but
then when the user has registered or logged on I want it to start the
quiz.
Here is my code,
#Login & Register
users = {}
status = ""
def displayMenu():
status = input("Are you a registered user? y/n? Say quit to exit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print ("\nLogin name already exist!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = input("Enter login name: ")
passw = input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print ("\nLogin successful!\n")
else:
print ("\nUser doesn't exist or wrong password!\n")
while status != "q":
displayMenu()
# Defining Score variables
x = 0
score = x
# Question One
print("When did WW2 finish?")
answer1 = input("a)2001\nb)1945\nc)1877\nd)1940\n:")
if answer1.lower() == "b" or answer1.lower() == "2":
print("Correct")
x = x + 1
else:
print("Incorrect, the second Worl War ended in 1945")
# Question Two
print("Who was responsilbe of most deaths in World War 1 & 2 ")
answer2 = input("a)Donald Trump\nb)Adolf Hitler\nc)Tom Cruisend\nd)There were no WAR\n:")
if answer2.lower() == "b" or answer1.lower() == "Adolf Hitler":
print("Correct")
x = x + 1
else:
print("Incorrect, It was Adolf Hitler who took around 12 to 14 million lives")
# Question Three
print("True or False... Hitler was a painter")
answer3 = input(":")
if answer3.lower() == "true" or answer3.lower() == "t":
print("Correct")
x = x + 1
else:
print("Incorrect")
# Question Four
print("What happened in Chernobyl")
answer4 = input("a)Nuclear Plant exploaded\nb)Water Flood\nc)Alien Envasion\nd)War\n:")
if answer4.lower() == "a" or answer4 == "1967":
print("Correct")
x = x + 1
else:
print("Incorrect, the nuclear plant exploaded")
# Question Five
print("True or False... Everybody knew the reactor will explode")
answer5 = input(":")
if answer5.lower() == "false" or answer5.lower() == "f":
print("Correct")
x = x + 1
else:
print("Incorrect, no one knew it will explode")
#Total Score
score = float(x / 5) * 100
print(x,"out of 5, that is",score, "%")
At the end of the while loop add a break statement:
while status != "q":
displayMenu()
break
your status does not exist beyond the scope of the function DisplayMenu()
What you can do is use status as a return value for this function, adding
return status
in the end, and then using a condition on this :
dm=""
while dm != "q":
dm=displayMenu()

Limit the amount of inputs in a Python list

I want to set a limit to which the user can input names. This is where I got to and got stuck. How would I set a limit of 10 to the names the user can input into the list and restrict them from entering anymore?
names = []
print ('1 = Add Name ')
print ('2 = Display List ')
print ('3 = Quit ')
while True:
option = input('What would you like to do: ')
if option == '1':
name= input('Enter name: ')
names.append(name)
you can do :
if option == '1':
names = [input('Enter name:') for _ in range(10)]
I hope that following script can help you:
# libraries
import sys
# list variable to store name
names = []
# limits to save name
limit = 10
# function to display menu
def menu():
print("Enter 1 to add Name")
print("Enter 2 to show list")
print("Enter 3 to quit")
choice = int(raw_input("Enter your choice : "))
return choice
# running for infinite times till user quits
while(True):
choice = menu()
if(choice == 1):
name = raw_input("Enter name to add in list : ")
if(len(names) > 10):
print("You cannot enter more names")
else:
names.append(name)
print(name + " - Name saved successfully.")
if(choice == 2):
print("List of names : ")
print(names)
if(choice == 3):
sys.exit()

Categories

Resources