Linking user input to a variable in a list - python

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.

Related

Pickle module that breaks the code from the book "Conceptual Programming with Python"

I'm taking the example from the book "Conceptual Programming with Python".
Some introduction to the problem that the code is aimed at solving:
Example: Creating a Knowledge Base
As a second example for OOP, we are going to implement a simple guessing game! But this game will be able to learn from experience, that is, you will be able to teach the program as you play. For this example, we will create a knowledge base of animals. The user will think of an animal, and the computer will have to figure out which animal it is by asking you (sensible) questions about that animal; the answer will be either yes or no. If it fails to guess correctly the animal, the program will ask you what would be a sensible question to be able to find the right solution next time!
Example 1: The computer only knows how to distinguish between a bird or a cat depending on whether it has 4 legs or not. That is, the initial knowledge base only contains these two animals and one single question.
You: Think of a cat.
Computer: Does it have 4 legs?
You: Yes
Computer: Were you thinking of a cat?
You: Yes
Computer: I knew it !! Let's keep playing! I am good at this!
Once again, this follows a tree structure! Depending on whether the user answers yes or no, the computer will ask a different question, or will provide an answer!
Example 2: You teach the computer a new question.
You: Think of a dog.
Computer: Does it have 4 legs?
You: Yes
Computer: Were you thinking of a cat?
You: No
Computer: What animal were you thinking of?
You: Dog
Computer: What is a question to distinguish between dog and cat?
You: Does it bark?
Computer: For a dog, what should be the answer?
You: Yes
Now for the pickle fragment:
Files need to be always opened first; then manipulate them (for example loading their content into a data structure), and finally close them when they are no longer in use. So, we are going to try to open a file called animal.kb in which we will save the tree. The first time we open the file, it will be empty, so we will create our previous knowledge base. To do so, we will use a try-except structure. Why? Whenever we try to open a file that doesn’t exist, this will create an exception FileNotFoundError. We can simply catch it and create the knowledge base ‘manually’. Then we let the user play, and we keep updating the knowledge base kb. At the end of the program, when the user doesn’t want to play anymore, we ‘dump’ the information contained in kb on the file “animal.kb”.
After the 2nd try with opening the "animal.kb" knowledge base the error appears:
```
Do you want to play? y
Traceback (most recent call last):
File "...\ConceptualPython02\knowledgeBase.py", line 71, in <module>
kb = kb.play()
AttributeError: 'NoneType' object has no attribute 'play'
Process finished with exit code 1
```
That's the problematic code:
import pickle
class Knowledge:
pass
class Question(Knowledge):
def __init__(self, text, if_yes, if_no):
self.text, self.if_yes, self.if_no = text, if_yes, if_no
def play(self):
if ask(self.text):
self.if_yes = self.if_yes.play()
else:
self.if_no = self.if_no.play()
return self
class Answer(Knowledge):
def __init__(self, text):
self.text = text
def play(self):
if ask("Were you thinking of a {} ? ".format(self.text)):
print("I knew it!")
return self
# here we got it right, # so we simply return the
# Answer node as it is.
else:
newanimal = input("What animal were\ "
"you thinking of? ")
newquestion = input("What is a question "
"to distinguish between {} and {} ?"
.format(self.text, newanimal))
# but in case we didn't know the animal
# we need to modify the node adding # the appropriate question and# what to do
# ifyes and if no
if ask("For {} , what should be the answer? ".format(newanimal)):
return Question(newquestion,
Answer(newanimal), self)
else:
return Question(newquestion,
self, Answer(newanimal))
def ask(q):
while True:
ans = input(q + " ")
if ans == "y":
return True
elif ans == "n":
return False
else:
print("Please answer y or n!")
try:
file = open("animal.kb", "rb")
kb = pickle.load(file)
file.close()
except FileNotFoundError:
kb = Question("Does it have 4 legs?", Question("Does it bark?",
Answer("dog"), Answer("cat")), Answer("bird"))
while True:
if not ask("Do you want to play?"):
break
kb = kb.play()
file = open("animal.kb", "wb")
pickle.dump(kb, file)
file.close()
Of course, also, it doesn't cache the new questions about the animals as it should have.
play should always return a Knowledge instance (or inherited from it). But when in Question.play the call to ask returns True, you don't return anything:
def play(self):
if ask(self.text):
self.if_yes = self.if_yes.play()
else:
self.if_no = self.if_no.play()
return self
So change the indentation of return self so it is always executed.

Getting TypeError: argument of type 'int' is not iterable in Python

I'm trying to write a text game with what I've learned so far, but I ran into a problem.
When I input 1, it's fine, but when I input 2, it gives me the following error:
Traceback (most recent call last):
File "ex36.py", line 39, in <module>
start()
File "ex36.py", line 27, in start
if choice == 1 or "closer" in choice:
TypeError: argument of type 'int' is not iterable
I realize that the function idf(): is totally unnecessary as I can just treat the input 2 as a string without converting it into an integer. This fixes the program. However, I would like to know why this error occurs when I try to change the input into a string, and why it only works for 1 and not 2.
I'm sorry for this stupid question; I'm very new to programming and trying to teach myself python. Thanks for the support, everyone.
Update 1:
I think I see the problem now, as pointed out by two answerers below. The problem happens when the program tries to check "closer", which is a string, in choice, which is an integer.
I would like the if statements to accept both integers and strings. How would I do this? Any advice to modify my program?
from sys import exit
print("""Welcome to my text game! You may input numbers (e.g. 1, 2, 3) to
navigate or type in your choice.""", "\n")
def bad_news(reason):
print(reason)
exit(0)
#IDs if str or int
def idf(check):
if check.isdigit() == True:
converted = int(check)
return converted
else:
return check
def start():
print("You're walking home down a dark road, in a dark and gloomy night.")
print("There's someone going the same way as you.")
print("'It's quite dark and dangerous,' you think. 'Better do something.'")
print("Will you: 1. Follow him/her closer? or 2. Keep distance?")
choice1 = input("> ")
choice = idf(choice1)
if choice == 1 or "closer" in choice:
bad_news("""The person gets spooked and you got cops called on you.
Now you have a restraining order. Great!""")
elif choice == 2 or "distance" in choice:
alley()
else:
print("The input is invalid; please try again.")
start()
def alley():
print("Now in alley.")
start()
Your idf converts any digit strings into numbers and then you try to check if a string is in the integer.
Your best option is to just always return strings from idf (or remove this function altogether) and check if choice == "1"
Your main problem is this line:
if choice == 1 or "closer" in choice:
If choice is not 1 you cannot check "closer" in choice without potential errors, because choice can still be an integer (e.g. the number 2) and an integer is not iterable.
It is best to keep the program simple and also to keep the return type from the input() function, i.e. the string. The string method is_digit() already exists and you can also apply it directly to the return value. In my opinion, there is no need to write another function that checks this. Then the function can also return two different data types. This complicates the code unnecessarily.
The string method is_digit() already does all the magic that is essential to your problem. It allows you to check if a user has entered a number or a text. You only need to explicitly convert the potential number to an integer (int(choice)) if you want to save the number as an integer.
Since you have several cases that you need to handle differently, you will also need to write some if-statements. So you could simply do something like this, for example:
if not choice.isdigit():
if "closer" in choice:
# do something
elif "whatever" in choice:
# do something
elif choice == "1":
# do something
elif choice == "2":
# do something
...
You can save one indentation by using the logical and-operator, but this is more a matter of taste, e.g.:
if not choice.isdigit() and "closer" in choice:
...
If you just want to react to certain return values, you can even do it without the is_digit() function, at all. But you mentioned in the question that you still want to distinguish between numbers and text (at least that's how I understood it). Because then you always get a string back and this string is always iterable. The error from above would simply not occur.
Most of it you have already figured out yourself, but the answer should also have added value for other readers. Therefore I have revised the answer again and hopefully clarified the problem better.

how to validate values in array and do actions python whatsapp framework

I am newbie learning python, I need a little help in whatsapp framework in github but that's python programming where my knowledge is limited. here you can see two things:
message.text ( here is stored the whatsapp message, so i can create commands)
message.conversation (here you can get the groupid or phone number of the sender)
the example code:
# modules/hi_module.py
from app.mac import mac, signals
#signals.message_received.connect
def handle(message):
if message.text == "hi":
mac.send_message("Hello", message.conversation)
# Can also send media
#mac.send_image("path/to/image.png", message.conversation)
#mac.send_video("path/to/video.mp4", message.conversation)
i want to limit my commands like that "hi" to work only in three groups allowed by me, i am thinking in an array where this is stored. So i am thinking in an idea like that
groupIds = { "group": "123456789#whatsapp.net", "group": "123458754#whatsapp.net",}
if "hi" in message.text:
validategroup()
#do something
else:
#print("you are not allowed to do this command")
def validategroup:
if groupIds in message.conversation:
validation = true
else:
validation = false
I am stuck at this part, I don't know how to code correctly the method and how to return and allow command or deny. please help me to learn
I think you can not do like this
if groupIds in message.conversation:
As groupIds is dic and you can not find complete dic. you should use the value of the key to find in message.conversation.
One more I want to check is message.conversation get string or list..?
Thanks
Your BOOLEAN values must begin with a Capital Letter ( i.e. True or False ).

python randomly shuffled multiple choice questionaire

I'm making a subclass for multiple choice questions under a superclass of trivia questions for my Python university course. The multiple choice aspect works, but I want to shuffle the order of the answers for extra credit.
Some of my code:
class ChoiceQuestion(Question) :
def __init__(self) :
super().__init__()
self._choices = []
def addChoice(self, choice, correct) :
self._choices.append(choice)
if correct :
# Convert len(choices) to string.
choiceString = str(len(self._choices))
self.setAnswer(choiceString)
# Override Question.display().
def display(self) :
# Display the question text.
super().display()
# Display the answer choices.
for i in range(len(self._choices)) :
choiceNumber = i + 1
print("%d: %s" % (choiceNumber, self._choices[i]))
The question choices are added in a seperate file I have no control over as a test-file. This is run by the professor after turning in whatever variation of the first code. Here is what he runs it on. Side note: there are of course import statements in the second file, but I have the other stuff solved and it's very long. Didn't want to include stuff that has been worked out.
print('\n')
mcq = ChoiceQuestion()
mcq.setText("In which country was the inventor of Python born?")
mcq.addChoice("Australia", False)
mcq.addChoice("Canada", False)
mcq.addChoice("Netherlands", True)
mcq.addChoice("United States", False)
for i in range(3) :
presentQuestion(mcq)
## Presents a question to the user and checks the response.
# #param q the question
#
def presentQuestion(q) :
q.display() # Uses dynamic method lookup.
response = input("Your answer: ")
if q.checkAnswer(response):
print("Correct")
else:
print("Incorrect") # checkAnswer uses dynamic method lookup.
# Start the program.
With that said, I need to display the options in a random order, while updating the number value tied to that choice slot. I.e. if Netherlands is randomized into slot 1, typing "1" will print "Correct". I also have to make sure I don't allow the same option to appear more than once.
How should I go about it? What are some suggestions? Note: I can only modify the first program
Here are a couple of things to think about:
As kiran.koduru mentioned, look at using the random module for easily shuffling lists.
Currently your code stores the correct answer as it is received. This makes it difficult because when the answers are shuffled the stored answer is no longer correct. An alternative is to store choice and correct together and calculate the correct answer after your choices are shuffled.
Your code does not know in addChoice whether or not there will be more choices added, so shuffling there will result in wasted computation.

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