Trouble while using "else" - python

Can't figure out what i am doing wrong.If someone uses the Wikipedia list,the if for wikipedia will be excecuted together with the else.
wikipedia=["search","infromation"]
weatherfor=["show weather","weather today","weather forecast","weather"]
action=(input("What would you want me to do : "))
if any(word in action for word in wikipedia):
print("Here Is What I Found On Wikipedia.")
if any(word in action for word in weatherfor):
print("The Weather For Today Is")
else:
print ("Sorry I Haven't learnt this yet")

You have overkilled the if else, try this simple structure:
wikipedia=["search", "infromation"]
weatherfor=["show weather", "weather today", "weather forecast", "weather"]
action=(input("What would you want me to do : "))
if action in wikipedia:
print("Here Is What I Found On Wikipedia.")
elif aaction in weatherfor:
print("The Weather For Today Is")
else:
print ("Sorry I Haven't learnt this yet")
The in would do the job of searching a given value in any iterable (list in this case)

Related

How do I clear an "if" condition

I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.

How do I print something only when a given parameter does not equal an empty string

I am trying to print out different options which are parameters to my function, however, i want my code not to print anything if that specific parameter is an empty string.
The code I have till now:
def ask_question(question, option1, option2, option3, option4):
#print the question onto the screen as well as numbered options
print(question)
print("1 ", option1)
print("2 ", option2)
print("3 ", option3)
print("4 ", option4)
#store answer under user_response
user_response = input("Your answer: ")
return user_response
This prints
How are you
good
bad
when parameters are:
("How are you", "good", "bad","","")
but I would like it to print:
How are you
good
bad
without including any options with an empty string
Any help on what I should do?
You would be better off passing in a list of possible responses, along the lines of:
def ask_question(question, options):
print(question)
number = 0
for option in options:
number += 1
print(f" {number:2}. {option}")
while True:
try:
answer = int(input("Your answer: "))
if 1 <= answer <= number:
return answer
print(f"Input out of range, try again.")
except Exception as exc:
print(f"Input error, try again: {exc}.")
response = ask_question("How are you?", ["Good", "Bad"])
That way, you can cater for any number of possibilities, including checking input for validity as shown.
Instead of separate option params it may be better to just have one options param that takes a list. Then you can do this:
def ask_question(question, options:list):
#print the question onto the screen as well as numbered options
print(question)
for e, option in enumerate(options,1):
print(f'{e}) {option}')
#store answer under user_response
user_response = input("Your answer: ")
return user_response
I just used an if statement before everyone and it worked out fine:
ex:
if(option1 != "")
print("1", option1)
this worked and passed the test

Python 3.8 - Trying to get my random numbers saved to a variable

I'm trying to get my balance to add up but I don't know how to save my balance to a variable from a random number. In the screenshot below, it shows that they are giving and my balance does not add up.
Steps taken:
I've tried passing bank instead of money through my functions
Read the python docs doesn't say anything about saving rand ints as variables
Tried if and then statement but same issue. My balance was not adding up.
Import different libraries did not work
import random
def main():
bank=0
backstory()
pet=input("what pet do you have? ")
print("nice! your pet will be a ", pet)
decisions(pet, bank)
#outcome()
def backstory():
print('You are a homeless person and are trying to get money to feed yourself and your pet.')
print('Everything you choose to do will effect how your outcome will be.')
print('You have five decisions you can make')
print('dont forget to eat or feed your pet so neither if you two will die!')
def decisions(animal,money):
print('enter "beg" to beg for money')
print('enter "work" to work for money')
print('enter "eat" to eat food')
print('enter "feed" to feed your pet')
print('enter "steal" to steal from someone!')
print('enter "skip" to do nothing and skip a decision for the day')
cont=0
bank=0
while cont<=4:
pick=input("what will be youre decision? ")
if pick=="beg":
beg(bank)
cont+=1
elif pick=="work":
work(money)
cont+=1
elif pick=="eat":
eat(money)
cont+=1
elif pick=="feed":
feed(money)
cont+=1
elif pick=="steal":
steal(money)
cont+=1
elif pick=="skip":
skip(money)
cont+=1
else:
print("sorry! thats not an option! please pick something from above")
#outcome(animal, money)
print("all done")
def beg(bank):
names=["Alvin and the Chipmunks", "Bob", "Timmy", "Alex", "Carah", "A very Rich Man"]
amount=random.randint(1,20)
print(random.choice(names), "gave you ", amount, "!")
bank=amount+bank
print("your balance is ", bank)
main()
Because your bank is always local variable, in beg function , you don't make bank return, so bank in decisions function is always zero, so you need return it in beg function , like this:
def main():
bank=0
backstory()
pet=input("what pet do you have? ")
print("nice! your pet will be a ", pet)
decisions(pet, bank)
#outcome()
def backstory():
print('You are a homeless person and are trying to get money to feed yourself and your pet.')
print('Everything you choose to do will effect how your outcome will be.')
print('You have five decisions you can make')
print('dont forget to eat or feed your pet so neither if you two will die!')
def decisions(animal,money):
print('enter "beg" to beg for money')
print('enter "work" to work for money')
print('enter "eat" to eat food')
print('enter "feed" to feed your pet')
print('enter "steal" to steal from someone!')
print('enter "skip" to do nothing and skip a decision for the day')
cont=0
bank=0
while cont<=4:
pick=input("what will be youre decision? ")
if pick=="beg":
bank = beg(bank)
cont+=1
elif pick=="work":
work(money)
cont+=1
elif pick=="eat":
eat(money)
cont+=1
elif pick=="feed":
feed(money)
cont+=1
elif pick=="steal":
steal(money)
cont+=1
elif pick=="skip":
skip(money)
cont+=1
else:
print("sorry! thats not an option! please pick something from above")
#outcome(animal, money)
print("all done")
def beg(bank):
names=["Alvin and the Chipmunks", "Bob", "Timmy", "Alex", "Carah", "A very Rich Man"]
amount=random.randint(1,20)
print(random.choice(names), "gave you ", amount, "!")
bank=amount+bank
print("your balance is ", bank)
return bank
and then run it
main()
You will get it.
You are a homeless person and are trying to get money to feed yourself and your pet.
Everything you choose to do will effect how your outcome will be.
You have five decisions you can make
dont forget to eat or feed your pet so neither if you two will die!
what pet do you have? beg
nice! your pet will be a beg
enter "beg" to beg for money
enter "work" to work for money
enter "eat" to eat food
enter "feed" to feed your pet
enter "steal" to steal from someone!
enter "skip" to do nothing and skip a decision for the day
what will be youre decision? beg
Alvin and the Chipmunks gave you 16 !
your balance is 16
what will be youre decision? beg
Alvin and the Chipmunks gave you 9 !
your balance is 25
what will be youre decision? beg
Alvin and the Chipmunks gave you 10 !
your balance is 35
what will be youre decision? beg
Alvin and the Chipmunks gave you 1 !
your balance is 36
what will be youre decision? beg
Carah gave you 13 !
your balance is 49
all done

how do I reset a input in python

so i have this code that basically consists of you asking questions, but i have it so the input answers the question, so you can only ask one question, then you have to reset the whole thing again and again, and i have it to ask you your name first so i want a loop that ignores that.
print("hello,what is your name?")
name = input()
print("hello",name)
while True:
question = input("ask me anything:")
if question == ("what is love"):
print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
break
if question == ("i want a dog"):
print("ask your mother, she knows what to do",name)
break
if question == ("what is my name"):
print("your name is",name)
break
Get rid of the breaks, so the loop keeps prompting for new questions. For performance, change the subsequent if tests to elif tests (not strictly necessary, but it avoids rechecking the string if you get a hit early on):
while True:
question = input("ask me anything:")
if question == "what is love":
print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
elif question == "i want a dog":
print("ask your mother, she knows what to do",name)
elif question == "what is my name":
print("your name is",name)
Of course, in this specific case, you could avoid the repeated tests by using a dict to perform a lookup, making an arbitrary number of prompts possible without repeated tests:
# Defined once up front
question_map = {
'what is love': "love is a emotion that makes me uneasy, i'm a inteligence not a human",
'i want a dog': 'ask your mother, she knows what to do',
'what is my name': 'your name is',
# Put as many more mappings as you want, code below doesn't change
# and performance remains similar even for a million+ mappings
}
print("hello,what is your name?")
name = input()
print("hello",name)
while True:
question = input("ask me anything:")
try:
print(question_map[question], name)
except KeyError:
# Or check for "quit"/break the loop/alert to unrecognized question/etc.
pass
print("hello,what is your name?")
name = input()
print("hello",name)
while True:
question = input("ask me anything:")
if question == ("what is love"):
print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
elif question == ("i want a dog"):
print("ask your mother, she knows what to do",name)
elif question == ("what is my name"):
print("your name is",name)
Take out the breaks. Then have one of the options be "quit" with a break

What function should I use to fix my code?

I'm an amateur trying to code a simple troubleshooter in Python but I'm sure what function I need to use to stop this from happening...
enter image description here
What should I do so the code doesnt continue running if the user inputs yes?
TxtFile =open('Answers.txt')
lines=TxtFile.readlines()
import random
def askUser(question):
answer = input(question + "? ").lower()
Split = answer.split()
if any(word in Split for word in KW1):
return False
elif any(word in Split for word in KW2):
return True
else:
print("Please answer yes or no.")
askUser(question)
KW1=["didn't", "no",'nope','na'] #NO
KW2=["did","yes","yeah","ya","oui","si"] #YES
print (lines[0])
print("Nice to meet you, " + input("What is your name? "))
print("Welcome to my troubleshooter")
#This is the menu to make the user experience better
shooter=True
while shooter:
print('\n\n1.Enter troubleshooter\n2.Exit\n\n')
shooter=input('Press enter to continue: ')
if shooter==('2'):
print('Ok bye')
break
words = ('tablet', 'phone', 's7 edge')
while True:
question = input('What type of device do you have?: ').lower()
if any(word in question for word in words):
print("Ok, we can help you")
break
else:
print("Either we dont support your device or your answer is too vague")
if askUser("Have you tried charging your phone"):
print("It needs to personally examined by Apple")
else:
if askUser("Is it unresponsive"):
print (lines[0])
else:
print ("Ok")
if askUser("Are you using IOS 5.1 or lower"):
print (lines[1])
else:
if askUser("Have you tried a hard reboot"):
print (lines[2])
else:
if askUser("Is your device jailbroken"):
print (lines[3])
else:
if askUser("Do you have a iPhone 5 or later"):
print (lines[4])
else:
print(lines[5])
print ('Here is your case number, we have stored this on our system')
print (random.random())
Here is my code for reference.
Edit: Here is the problem
enter image description here
It should just end the code there but it doesnt. I'm not sure how I can fix it
I would recommend moving the following:
if askUser("Are you using IOS 5.1 or lower"):
print (lines[1])
else:
if askUser("Have you tried a hard reboot"):
print (lines[2])
else:
if askUser("Is your device jailbroken"):
print (lines[3])
else:
if askUser("Do you have a iPhone 5 or later"):
print (lines[4])
else:
print(lines[5])
print ('Here is your case number, we have stored this on our system')
print (random.random())
into the else part of:
if askUser("Is it unresponsive"):
Hope this helps.

Categories