Python autocomplete user input [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a list of teamnames. Let's say they are
teamnames=["Blackpool","Blackburn","Arsenal"]
In the program I ask the user which team he would like to do stuff with. I want python to autocomplete the user's input if it matches a team and print it.
So if the user writes "Bla" and presses enter, the team Blackburn should automatically be printed in that space and used in the rest of the code. So for example;
Your choice: Bla (User writes "Bla" and presses enter)
What it should look like
Your Choice: Blackburn (The program finishes the rest of the word)

teamnames=["Blackpool","Blackburn","Arsenal"]
user_input = raw_input("Your choice: ")
# You have to handle the case where 2 or more teams starts with the same string.
# For example the user input is 'B'. So you have to select between "Blackpool" and
# "Blackburn"
filtered_teams = filter(lambda x: x.startswith(user_input), teamnames)
if len(filtered_teams) > 1:
# Deal with more that one team.
print('There are more than one team starting with "{0}"'.format(user_input))
print('Select the team from choices: ')
for index, name in enumerate(filtered_teams):
print("{0}: {1}".format(index, name))
index = input("Enter choice number: ")
# You might want to handle IndexError exception here.
print('Selected team: {0}'.format(filtered_teams[index]))
else:
# Only one team found, so print that team.
print filtered_teams[0]

That depends on your usecase. If your program is commandline based, you can do that at least by using the readline module and pressing TAB. This link also provides some well explained examples on that since its Doug Hellmanns PyMOTW. If you are trying that via a GUI it depends on the API you are using. In that case you need to deliver some more details please.

Related

How do I get this If statement condition to work properly? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
I'm having a problem with the following piece of code:
decision = str(input("Would you like to change it?:"))
if decision.lower == 'yes':
new_holiday = input("What is your new favorite holiday?:")
The problem with this is that when I input 'yes' in the first prompt, instead of showing me the second one as I want, it just skips the if statement completely. Am I missing something here?
decision.lower generates a method <built-in method lower of str object at ...>. you should call decision.lower().
Change your code to the following:
decision = str(input("Would you like to change it?:"))
if decision.lower() == 'yes':
new_holiday = input("What is your new favorite holiday?:")
decision.lower() user this method which will return a lower cased string.
decision = input("Would you like to change it?:")
if decision.lower() == 'yes':
new_holiday = input("What is your new favorite holiday?:")

Python returns None to input [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Hey so I’m writing a text-adventure game in python and made a typingprint function to make the text look like it was typed out. But when I try to use this function with inputs it will reply with None.
import random
import time
import console
import sound
import sys
def typingPrint(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
console.set_color()
typingPrint('Hello! My name is Sawyer and I will be your guide
throughout this game. Heres a helpful hint, every time you enter
room you will have to battle a enemy.')
time.sleep(3)
player_name = input(typingPrint('\nBefore we begin why don\'t
you tell me your name: '))
How can I fix this?
This is because your function doesn't return anything so there is no text in the input prompt. To solve it, you will need to first call your function, then the input -
typingPrint('Hello! My name is Sawyer and I will be your guide throughout this game. Heres a helpful hint every time you enter a room you will have to battle a enemy.')
time.sleep(3)
typingPrint('\nBefore we begin why dont you tell me your name: ')
player_name = input()

write a basic inventory management system python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
Hello everyone I'm writing a basic inventory management system and in one of my functions I'm trying to print specific values within the text document for the function trying to print user names, numbers and users designations I keep returning
UnboundLocalError: local variable 'user_numbers' referenced before assignment
Here's my code:
def display_users():
all_users = open('all_users.txt', 'r')
user_description = all_users.readline()
print('All Current User')
print('<----------------->')
while user_description != '':
user_names = all_users.readline()
user_numbers = user_numbers.rstrip('\n')
user_desig = user_desig.rstrip('\n')
print('User Names: ', user_names)
print('User PH Numbers: ', user_numbers)
print('User Designations: ', user_desig)
print('<---------->')
user_description = all_users.readline()
all_users.close()
Edit: I've made it a global variable and now it's just saying
"NameError: name 'user_numbers' is not defined"
https://pastebin.pl/view/ae461557
Here's full code
The issue is with user_numbers = user_numbers.rstrip('\n'), specifically the second part. The error gives you a clear description: user_numbers is not defined yet, so you cannot call rstrip on it. Did you mean to type user_names.rstrip('\n')?
The problem is with this line
user_numbers = user_numbers.rstrip('\n')
In the first iteration of your loop, user_numbers has no value so you cannot call user_numbers.rstrip('\n') on it. I don't follow exactly how you are structuring your text file, but you probably want to make a user_numbers = all_users.readline() call first.

Linking user input to a variable in a list

I got the task of creating code from a flow chart as follows.
You can see what it's asking me to do and as such, I think the method to doing this would be to assign the three languages to a separate variable each and then to assign "Welcome to ..." to its own variable as well.
However, I'm having problems with having the user input a link to one of the variables to print whatever is in that variable. Hopefully that makes sense, I'm new to this community and coding in general so I apologise for my issues. Thanks in advance!
On Stack Overflow, we don't normally write code, but here you go:
# Get user's selected language
userLanguage = input("What is your language? (English/French/Mandarin) ") # Ask the user the question
# Compare languages
if userLanguage.lower() == "english": # If the user entered "english", forced to lower-case by .lower()
print("Hello")
elif userLanguage.lower() == "french": # If the user entered "french"
print("Bonjour")
elif userLanguage.lower() == "mandarin": # If the user entered "madarin"
print("Ni Hao")
else: # The entered language was something else
print("Sorry, but I don't speak that")
# Welcome the user
print("Welcome to ...")
Adjust it to how you specifically need it, but there is a Python version of the flowchart.

Programming A Troubleshooting Program On Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
INCOMPLETE CODE
So one of my assignments is to create a troublshooting program that will indetify keywords within a query and link the user to a solution based on their input. Although this code works, any of the keywords will always call for the first solution... any ideas on how to correct this? Many thanks!
#CODE BEGINS
#damaged screen#
sol1 = ("If the battery of your mobile phone battery has swollen or changed appearance, we recommend removing the battery from the phone immediately and bringing them in store. This is something our technicians will have to look at.")
sol2 = ("We recommend bringing the phone in to a nearby store in able to gain help from a specialist.")
sol3 = ("We recommend factory resetting the phone or updating the mobile to the latest interface as the majority or errors are caused due to out-of-date interfaces.")
#subjected to damage#
sol4 = ("If the screen has been cracked, we recommend replacing the screen. If not, bring the phone into a store in order to seek help from a technician.")
sol5 = ("If the phone is water logged, we recommend removing the battery and allowing each piece of the phone to dry separately. Alternatively take the phone into a store.")
sol6 = ("We recommend taking the phone into a store, in order to seek help from a specialist.")
#editing#
sol7 = ("If you have recently changed the security settings on your phone there may be a corruption within your files. Please ensure you are entering your password correctly, and if this does not work, we recommend taking the phone into a store, in order to seek help from a specialist.")
sol8 = ("If you have recently deleted or edited files there may be a corruption within the files. In which case, please drop in to a nearby specialist in order to seek professional help.")
sol9 = ("If there has been a new update release for your device and many people are suffering a similar issue, there may be a manufacturing problem. We recommend taking the phone into a store, in order to seek help from a specialist.")
#file corruption#
sol10 = ("If you have recently attempted a factory reset and there has been an error you may need to retry this process. If the results come back the same, we recommend bringing the phone in to a nearby store in able to gain help from a specialist.")
sol11 = ("If there is a corruption within your files you may need to take your phone into a nearby store to gain professional help. This will ensure none of your files get lost in the process of storing them.")
sol12 =("We recommend factory resetting the phone or updating the mobile to the latest interface as the majority or errors are caused due to out-of-date interfaces.")
#corruptions due to download#
sol13 =("If you have recently download files from an external site there may be corruptions within the files or viruses. Please take your phone into a nearby store to gain professional help. This will ensure that no more damage is done to your device.")
sol14 =("If you have recently downloaded something from the app store your storage may be too full for your phone to run. In which case, please clear some space on your device.")
#If not solution can be provided, this outcome is the last message#
sol15 = ("Unfortunately we were not able to identify your problem. If you feel as though you may have made a mistake, you can restart this test. If there is no available solution we would recommend taking the phone into a store, in order to seek help from a specialist.")
import time
boolean = 0 #I have decided to use boolean operators in a way that they will act as subfunctions. This will help in directing the user to a specific solution instead of a general one.#
problemsolved = False
while problemsolved == False:
print("Hello, this system consists of multiple queries that will aim to help solve any problems that have arisen with your mobile device. If no solution is available the case number will be stored and revisited as soon as possible by a member of our customer support team.")
print("Let's get started, shall we?")
while boolean == 0:
problem1 = input("Is there something visably wrong with the phone?")
if problem1 == "yes":
print("Please describe in more detail.")
boolean += 1
elif problem1 == "no":
print("The problem is not to do with visable damage")
boolean+= 2
while boolean == 1:
problemexplainedone = str(input("Please decribe what is wrong with your phone."))
if ("battery" or "swollen" in problemexplainedone):
print(sol1)
elif ("screen" or "display" in problemexplainedone):
print(sol2)
elif ("error" or "message" in problemexplainedone):
print(sol3)
programfinished = input("Has the source of the problem been found and a solution suggested?")
if programfinished == "yes":
system = False
time.sleep(3)
exit()
elif programfinished == "no":
boolean += 1
while boolean == 2:
problem2 = input("Has the phone been subjected to damage?")
if problem2 == "yes":
print("Please describe in more detail.")
boolean += 1
elif problem1 == "no":
print("The problem is not to do with trauma to the hardware")
boolean+= 2
while boolean == 3:
problemexplainedtwo = str(input("Please decribe what is wrong with your phone."))
if ("battery" or "swollen" in problemexplainedtwo):
print(sol4)
elif ("screen" or "display" in problemexplainedtwo):
print(sol5)
elif ("error" or "message" in problemexplainedtwo):
print(sol6)
programfinished = input("Has the source of the problem been found and a solution suggested?")
if programfinished == "yes":
system = False
time.sleep(3)
exit()
elif programfinished == "no":
boolean += 1
You have to change occurences like
if ("battery" or "swollen" in problemexplainedone):
print(sol1)
to
if ("battery" in problemexplainedone or
"swollen" in problemexplainedone"):
Otherwise it always returns True, selecting the first solution.
The same for other if (... in ...) constructions.
Also some non-related tips:
Use an array for the solutions, that makes it easier to selecting a solution by index directly.
Do not use a variable named Boolean and assign it a number; give the variable a better name
use while not problemsolved instead of while problemsolved == False:
Use better casing, e.g. problemSolved

Categories

Resources