How to accept input from an enumerated list in Python? - python

So I have a list that I want to number using enumerate(), then have the user choose an item from the list using the corresponding number. Is there a way to do this?
(This is broken code but hopefully, you get an idea of what I want to do)
print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = input("> ")
if userSell in enumerate(market['addresses']):
print(f"Sold {address}")
else:
print("Address not found...")

IIUC, you can use the inputted number to index your list directly:
print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = int(input("> "))-1 # you might need a loop/check here to ask again on incorrect input
try:
# assuming market['addresses'] is a list
print(f"Sold {market['addresses'][userSell]}")
except IndexError:
print("Address not found...")

It's always a good idea to validate user input - especially when you're expecting numeric values.
If you do that in this case there's no need to lookup the address after user input because you will already have validated it.
market = {'addresses': ['1 Main Road', '2 Long Street', '100 Pall Mall']}
addresses = market['addresses']
print("Which house do you want to sell?")
for number, address in enumerate(addresses, 1):
print(number, '->', address)
while True:
try:
userSell = int(input("> "))
if 0 < userSell <= len(addresses):
break
raise ValueError('Selection out of range')
except ValueError as ve:
print(ve)
print(f'Sold {addresses[userSell-1]}')
Output:
Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 2
Sold 2 Long Street
With invalid user input:
Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 0
Selection out of range
> 4
Selection out of range
> foo
invalid literal for int() with base 10: 'foo'
> 1
Sold 1 Main Road

Try changing
if userSell in enumerate(market['addresses']):
to
if userSell in range(1, len(market['addresses'])):
This will loop through the values in the range (indexes) of the addresses at the end.

To make the original code work as intended, I believe you also need to convert the user input to int type and subtract 1 because you specified start=1 when printing the options.
market= {'addresses': ["This Street", "That Street"]}
print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = int(input("> ")) - 1
if userSell in range(len(market['addresses'])):
print(f"Sold {address}")
else:
print("Address not found...")
Having to subtract 1 to make the input match the options does not feel very robust as you will have to remember to adjust the index any time you look up elements in the list later in the code. It is a good idea to store the numbered options and reference the same object later. Converting to a dict makes the code nice and readable and understandable.
market= {'addresses': ["This Street", "That Street"]}
numbered_options = dict(enumerate(market['addresses'], 1))
print("Which house do you want to sell")
for number,address in numbered_options.items():
print(number, '->', address)
userSell = int(input("> "))
if userSell in numbered_options:
print(f"Sold {numbered_options[userSell]}")
else:
print("Address not found...")
What I would really recommend, though, is using one of the many pre-built libraries for displaying lists of options and getting choices from users in the command line. You can choose from the ones mentioned in this thread and consult library documentation to implement them. No need to redo something somebody else has already done for you.

Related

airline reservation def help python

for my homework I am asked to create a airline reservation system. It asks if they would like to either create, cancel, display reservations, or exit the program. I am having trouble figuring out how to add the seats to the dictionary and still have them there when the code runs again. here is the basics of my code so far.
def reservation():
print("Please choose an option: ")
print("1. Reserve a Seat")
print("2. Cancel a Reservation")
print("3. Display Reservations")
print("4. Exit")
plane={}
co=int(input("Enter a choice: "))
#choose an option
if co==1:
seat=row+col
#check if seat has been taken if not reserve
if seat in plane:
plane[seat]=name
print("Seat row col has already been reserved by "+plane[key])
reservation()
else:
plane[seat]=name
print("Seat "+seat+" has been reserved for "+name)
print (seat+" "+plane[seat])
reservation()
elif co==2:
row=input("Row (1-25): ")
seat=row+col
if seat in plane:
del plane[seat]
print("The reservation for seat "+seat+" has been cancelled.")
input("Press enter to continue...")
else:
print("Seat "+seat+" is not currently reserved by anyone.")
input("Press enter to continue...")
elif co==3:
print("Reservations:")
for key in plane:
print(key+"\t"+plane[key])
elif co==4:
exit()
reservation()
In your program, I noticed that you attempt to continue calling your reservation function recursively in order to keep in acting like a loop. As noted in the comments you probably would be better off utilizing a loop for this exercise. Recursive function calls are good for things such as factorials, producing an exploded bill of materials, and such.
Also, I noticed that a few value assignments appeared to be backwards and actually would probably throw an error such as the following line of code.
if seat in plane:
plane[seat]=name
The "name" variable doesn't appear to be defined yet so that probably was cause the program to halt. With that in mind, I took a swing at doing some revisions and additions to the program in order for it to function in the spirit I believe you are after. Following is the sample code.
def reservation():
plane={}
while True:
#Choose an option
print("Please choose an option: ")
print("1. Reserve a Seat")
print("2. Cancel a Reservation")
print("3. Display Reservations")
print("4. Save Reservations")
print("5. Exit")
co=int(input("Enter a choice: "))
if co == 1:
row = int(input("Please enter a row: "))
col = int(input("Please enter a seat number (1 -6)"))
# Since lists start at index 0, the formula will be adjusted to accomodate
seat = (row - 1) * 6 + col - 1
# Check if seat has been taken if not reserve
if seat in plane:
name = plane[seat]
print("Seat", (seat + 1), "has already been reserved by " + plane[seat])
else:
name = input("Please enter your name ")
plane[seat] = name
print("Seat", (seat + 1), "has been reserved for", name)
print ((seat + 1)," ", plane[seat])
elif co == 2:
row = int(input("Row (1-25): "))
col = int(input("Seat# (1 - 6): "))
seat = (row - 1) * 6 + col - 1
if seat in plane:
del plane[seat]
print("The reservation for seat", (seat + 1), "has been cancelled.")
input("Press enter to continue...")
else:
print("Seat", (seat + 1), "is not currently reserved by anyone.")
input("Press enter to continue...")
elif co == 3:
print("Reservations:")
for key in plane:
print((key + 1), "\t", plane[key])
elif co == 4:
with open('plane.txt', 'w') as f:
for line in plane:
record = plane[line] + " " + str(line + 1)
f.write(record)
f.close()
elif co == 5:
break
reservation()
First off, I encapsulated the reservation logic within a "while" loop as suggested in the comments above. That replaces the recursive calls and replaces the "exit()" call with a simple "break" call for option #4. Next, since the plane seats are being treated like a list, I did some sleight of hand calculations to insure that the possible seat list would start at index "0". I subtracted "1" where needed for deriving and index value and added "1" back in for viewing purposes.
Here is just a brief bit of text from my terminal testing out the program.
#Una:~/Python_Programs/Reservations$ python3 Reservations.py
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 1
Please enter a row: 4
Please enter a seat number (1 -6)2
Please enter your name Craig
Seat 20 has been reserved for Craig
20 Craig
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 4
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 5
Also, since you indicated that there was a need to save the reservations, I added a selection to the choices and a simple write to a text file for that. It is over simplified and you probably can find better solutions for that. Plus you will also probably want to add in some functionality to read the data back in. That could be a further embellishment to be worked on.
Anyway, please examine this code. Hopefully this will both clarify things for you plus give you ideas on how you might further embellish the functionality.
Regards.

Check element in list of array Python [duplicate]

This question already has answers here:
Check if element exists in tuple of tuples
(2 answers)
Closed 1 year ago.
I want to check if there is an element in a list of array
for example, I have:
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
So if I want to check if "horse A" is in the list. I tried:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
But if I input the horse name is : "horse B".
Input will also check every array in the list and print out the statement not found in array 1.
input:
Enter the horse name:horse B
horse B id 2 profile is not in the database. (You must enter the horse's profile before adding med records)
Enter treatment:
So how can I get rid of that ? Thank you.
You just need to move the else to be part of the for loop:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check, treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
You need to print the "horse not found" message only after traversing all the list, not very time you find an element. And you should exit the loop after finding the correct horse, no point in iterating beyond that point. You should use for's else construct for this:
horsename_check = input("Enter horse name: ")
for i in horselist:
if i[1] == horsename_check:
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
neededHorse = "horse B"
found = 0
for horse in horselist:
if neededHorse in horse:
found = horse[0]
if found != 0:
print("Horse found in ",found)
else:
print("Horse not found!")
This should work, you can keep a condition outside the loop and check it post the loop

unindent does not match any outer indentation level - School homework

So basically i'm stuck with my code and it's for homework and i don't know how to fix the error that i'm getting
"unindent does not match any outer indentation level"
I've tried to fix it myself but i haven't had any success, so i'm reaching out to anyone that would like to help me.
Here's my code
exit = False
while not exit:
#variables
name=str(input("Enter your students name "))
#User ratings for rolleston spirit
DSR=int(input("Enter rating for Develop Self "))
BCR=int(input("Enter rating for Building Communities "))
TFR=int(input("Enter rating for Transforming Futures "))
#If the input is above a certain number, it will print the student is doing well and if an input is below a ceratin number it will print the student needs support in .....
if DSR>=6:
print (name, "is doing well in developing self")
elif DSR<4:
print (name," needs support in developing self")
if BCR>=6:
print (name, "is doing well in Building Communities")
elif BCR<4:
print (name," needs support in Building Communities")
if TFR>=6:
print (name, "is doing well in Transforming Futures")
elif TFR<4:
print (name," needs support in Transforming Futures")
#Function to find the highest number in a list
def maxi(items):
#max finds the highest number in a list
return max(items)
print(name, "highest score was ", maxi([DSR, BCR, TFR]))
#function to get average of a list
def Average(lst):
return sum(lst) / len(lst)
# Creating List
lst = [DSR, BCR, TFR]
average = Average(lst)
# Printing average of the list
print(name, "has an overall rating of ", round(average, 2))
rep=str(input("Do you wish to continue? Y/N "))
if rep=="Y":
print (" ")
elif rep =="N":
exit = True
print(" ")
Expected output of the code.
Enter your students name Name
Enter rating for Develop Self 3
Enter rating for Building Communities 7
Enter rating for Transforming Futures 9
Name needs support in developing self
Name is doing well in Building Communities
Name is doing well in Transforming Futures
Name highest score was 9
Name has an overall rating of 6.33
Do you wish to continue? Y/N
There might be spaces mixed with tabs in your code and you need 4 spaces to indent. Try this :
exit = False
while not exit:
#variables
name=str(input("Enter your students name "))
#User ratings for rolleston spirit
DSR=int(input("Enter rating for Develop Self "))
BCR=int(input("Enter rating for Building Communities "))
TFR=int(input("Enter rating for Transforming Futures "))
#If the input is above a certain number, it will print the student is doing well and if an input is below a ceratin number it will print the student needs support in .....
if DSR>=6:
print (name, "is doing well in developing self")
elif DSR<4:
print (name," needs support in developing self")
if BCR>=6:
print (name, "is doing well in Building Communities")
elif BCR<4:
print (name," needs support in Building Communities")
if TFR>=6:
print (name, "is doing well in Transforming Futures")
elif TFR<4:
print (name," needs support in Transforming Futures")
#Function to find the highest number in a list
def maxi(items):
#max finds the highest number in a list
return max(items)
print(name, "highest score was ", maxi([DSR, BCR, TFR]))
#function to get average of a list
def Average(lst):
return sum(lst) / len(lst)
# Creating List
lst = [DSR, BCR, TFR]
average = Average(lst)
# Printing average of the list
print(name, "has an overall rating of ", round(average, 2))
rep=str(input("Do you wish to continue? Y/N "))
if rep=="Y":
print (" ")
elif rep =="N":
exit = True
print(" ")

Globalising variables from sub-routine into another sub-routine

I am having some trouble for carrying my variable from a sub-routine into another sub-routine.
Here is the code:
def loop1():
try:
age=int(input("How old are you? "))
except ValueError:
print ("Please enter a numerical integer of your age. For example: 19 ")
print("")
loop1()
if age>0:
program()
def program():
print("")
print("[1] - Knife / Spray Paint / Lottery Ticket ")
print("[2] - Alcohol / Tobacco ")
print("[3] - Anything else ")
print("")
loop2()
def loop2():
try:
item=int(input("What would you like to buy from the options above? "))
print("")
except ValueError:
print ("Please enter a numerical integer of your item. For example (if you wanted to buy alcohol): 2 ")
print("")
loop2()
if item>0:
validation()
def validation():
if item == 1 and 16>age :
print("Sale Denied - Item cannot be sold to Under 16s. ")
elif item == 1 and 16<age:
print("Sale Accepted. ")
elif item == 2 and 18>age:
print("Sale Denied - Item cannot be sold to Under 18s. ")
elif item == 2 and 25>age>18:
print("Check ID before selling alcohol - Challenge 25. ")
elif item == 2 and 18<age:
print("Sale Accepted. ")
elif item == 3:
print("Sale Accepted. ")
loop1()
Here is the outcome:
How old are you? 21
[1] - Knife / Spray Paint / Lottery Ticket
[2] - Alcohol / Tobacco
[3] - Anything else
What would you like to buy from the options above? 2
Traceback (most recent call last):
File "D:/Shop Program.py", line 48, in <module>
loop1()
File "D:/Test.py", line 9, in loop1
program()
File "D:/Shop Program.py", line 17, in program
loop2()
File "D:/Shop Program.py", line 28, in loop2
validation()
File "D:/Shop Program.py", line 33, in validation
if item == 1 and 16>age :
NameError: global name 'item' is not defined
As you can see from the error message above it is saying that global name 'item' is not defined. I have tried to place global item, above def vaildation():, but I still get the same error.
Rather than using global, which is a bad practice (in Python and everywhere else), explicitly pass item from loop2 into validation:
def loop2(age):
...
if item > 0:
validation(item, age)
# ^ pass it here
def validation(item, age):
# ^ receive it here
if item == 1 and 16 > age:
...
Note that I have done a similar thing with age, which should be passed in when loop2 is called. Using recursion for input validation isn't ideal; see Asking the user for input until they give a valid response for an alternative approach.
Forgive me if you already know this, but there is another way to get the item into the validate sub-routine that might work better for you. You can "pass in" a variable to a subroutine (also called methods or functions). Variables that you "pass in" to a subroutine are called arguments.
To use subroutine arguments, you have to do 2 things:
Define the arguments in the subroutine definition
Specify the variable to "pass in" when you call the subroutine
So for you, defining the argument item on your validate routine would look like this:
def validate(item):
if item == 1 and 16>age :
See how I stuck item between the parenthesis.
And then, all you have to do is "pass in" the item to the validate function:
def loop2():
try:
item=int(input("What would you like to buy from the options above? "))
print("")
except ValueError:
print ("Please enter a numerical integer of your item. For example (if you wanted to buy alcohol): 2 ")
print("")
loop2()
if item>0:
validation(item)
Notice how I put item between the parenthesis on the call to the validation subroutine on the last line.
Hope that helps
Apart from your original question: There is the possibility for an infinite recursion in loop1 and loop2 if the exception is risen, as the functions call themselves.
A better way is to use a loop (while True: ...) with a break after successful conversion.
Also, it is bad practice in every programming language to chain functions the way you did. That is an even worse idea than using goto and is commonly called spaghetti code.
Better is to have a single main function which calls the functions in succession and passes results of a former function as arguments to the next function:
age = get_age()
item = get_item()
if age < 16 and item == ...:
print("Not allowed")
...
A better approach would be to use a dict of { "item" : minimal_age }:
items = { "butter": 0 , "knife": 16, "booze": 18, "beer": 17 }
age = ...
item = get_item(items) # the list can be built automatically from dict
if age < items[item]:
print("Too young for", item)
else:
purchase(item)
That would avoid a loooooong list of if .. elif .. tests.
If the items are identified by strings instead of numbers, that would add to readability. In general, in Python numberincal values should only be used where they are "natural", otherwise use the appropriate type like strings, sets, etc.
Note that this is different from other languages (e.g. C), where string handling is quite uncomfortable and expensive.

using exceptions and writing data to files in python 3

here what I need to do:
Your program must raise an exception if the user chooses any item not on the menu
presented. Along with raising an exception, write the code to handle this exception.
Ask the user for a value to convert.Your program must raise and exception, and handle the exception, if an input
errors occurs
Perform the conversion and write the original value, the original unit, the
converted value, and the converted unit to an output file named
conversions.txt.
Repeat steps a and b 10 times (in a loop).
heres my code:
#imports
import os
# global variables
mile_choice = 1
gallon_choice = 2
pound_choice = 3
inch_choice = 4
fah_choice = 5
quit_choice = 6
mainfile = open('conversions.txt', 'w')
# intro and global name variable
name = input ('what is your name? ')
print()
print('hello',name,', today we will be doing\
some standard to metric conversions.')
#define main function
def main():
choice = 0
while choice != quit_choice:
display_menu()
print()
choice = int(input('Please enter a number 1 - 6 : '))\
if choice == mile_choice:
print()
miletokm()
elif choice == gallon_choice:
print()
galtolit()
elif choice == pound_choice:
print()
poundstokg()
elif choice == inch_choice:
print()
inchtocm()
elif choice == fah_choice:
print()
fahtocel()
elif choice == quit_choice:
print()
print('Exiting the program.')
#define functions
def display_menu():
print()
print(' Menu ')
print()
print('Press 1 for Miles to Kilometers')
print()
print('Press 2 for Gallons to Liters')
print()
print('Press 3 for Pounds to Kilograms')
print()
print('Press 4 for Inches to Centimeters')
print()
print('Press 5 for Fahrenhiet to Celisus')
print()
print('To exit please enter 6 ')
def miletokm():
invalid_attempts = 0
#while loop for invalid input limited to 3
while invalid_attempts < 3 and invalid_attempts >= 0:
print()
mile = float(input('how many miles would you\
like to convert to kilometers? '))
mainfile.write(str(mile) + '\n')
# if statement to determine weather to proceed with conversation
# valid input = conversion
# invalid input = return with + 1 to invalid_attempt count
if mile >= 0 :
print()
mile_conv = mile * 1.6
print('that would be:', format(mile_conv, '.2f'), 'kilometers.')
print()
mainfile.write(str(mile_conv) + '\n')
return mile
else:
print()
print ('invalid input')
print()
invalid_attempts += 1
I left out the other conversion def. to help keep it shorter.
I am having problems with the exception part first and for most.
I have tried various things but I cant figure out how to write out the code correctly
I know how to define a value error for a number entered outside of the menu range
I don't understand how to write the units along with the data entered to the file.
The way I Have it now, it is not writing any information to mainfile.
I also feel like my code is very sloppy written. I have no idea because my professor refuses to help me.
I know that's alot to run through but i really have no where else to turn. I don't understand how I should structure the code and how to effectively accomplish what I need done.
what I have read covers the basis of this but I have no examples to look at other than very simple simple examples that deal with strictly one thing.
You could try something like... (from http://docs.python.org/2/tutorial/errors.html#exceptions)
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
You're on the right track. First thing that you need to do is to handle better the value for choice that the user gives you. Check what happens if they give you 9 or 'foo'.
Next, you should do the same for every value received in your functions that convert units. For that, you use try/except as #bitfish showed you (except that you use input instead of raw_input).
close the files you open (mainfile.close())
doing this elif choice == quit_choice: inside of this while choice != quit_choice makes no sense
use '\n' to skip lines (print('\n') is the same than print() two times
there are many ways to solve such a problem, white the experience you'll acquire you'll find more elegant ones, but this one is already ok.

Categories

Resources