how do I reset a input in python - 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

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.

If any question has the answer no, how to print a certain text

I'm stuck with a problem that asks 5 questions. If any of them has the answer no It should print ALIEN! or else Cool.
This is what I have got so far:
human = input("Are you human? ")
human = input("Are you living on planet Earth? ")
human = input("Do you live on land? ")
human = input("Have you eaten in the last year? ")
human = input("Is 2 + 2 = 4? ")
if human == "yes":
print("Cool")
elif human == "no":
print("ALIEN!")`
You could use any() to check if any of the answers to questions is 'no' and print message accordingly:
human = [input("Are you human? "), input("Are you living on planet Earth? "),
input("Do you live on land? "), input("Have you eaten in the last year? "), input("Is 2 + 2 = 4? ")]
if any(x.lower() == 'no' for x in human):
print('ALIEN!')
else:
print('Cool')
You have the variable human that is changed every time and given a new value using input() Try and make multiple variables instead of just using human.
human = input("Are you human? ")
var1 = input("Are you living on planet Earth? ")
var2 = input("Do you live on land? ")
var3 = input("Have you eaten in the last year? ")
var4 = input("Is 2 + 2 = 4? ")
if(human == "yes"):
print("Cool")
elif(human == "no"):
print("ALIEN!")
If you're not worried about storing the variables and only care if one of the questions comes up as "no" or "n":
x=["human?","on earth?", "on land?","someone who eats food?","sure that 2+2=4?"]
for i in x:
if input("Are you {}".format(i)).lower() in ['no','n']:
print("Alien!")
break
else:
print("Cool")
Just a side note: Here you can see a great case for using a for loop since there is code that is repeated many times. Personally, I would do the following to solve this problem.
Create a list of questions
Iterate through the list of questions
If any answer is no, break and print Alien.
Now for the code:
# Initialize our list
lst = ["Are you human? ", "Are you living on planet Earth? ","Do you live on
land? ","Have you eaten in the last year? ","Is 2 + 2 = 4? "]
#Create a flag for Alien
flag = False
#Iterate through the list
for question in lst:
answer = input(question)
if answer == 'no':
#Print alien
print('Alien')
#Change Flag
flag = True
#Break out of the loop
break
#Check to see if our flag was thrown during the loop
if flag == False:
print('cool')
If you want more help on solving coding challenges like this one, check out this intro to python course: https://exlskills.com/learn-en/courses/learn-python-essentials-for-data-science-intro_to_python/content

Use of continue in python - how to break out of an individual loop?

I have written some code that contains several while loops.
answer = "yes"
while answer == "yes":
name = input("what is your name?")
while len(name) > 0 and name.isalpha():
print("okay")
break
else:
print("error")
continue
job = input("what is your job?")
while job.isalpha():
print("great")
else:
print("not so great")
continue
age = input("how old are you?")
while age.isnumeric():
print('nice')
else:
print("not so nice")
continue
What I want the code to do is check for a valid name entry, and if it is invalid re-ask the user for their name. I want it to do the same thing with their job. Unfortunately, when I use continue after the job statement, instead of just re-asking for their job, it re-asks for their name as well. Does anyone know how to make it only re-ask for the job, and not re-do the whole program? Does anyone know how I could replicate this for multiple while loops I.e. Asking for job, name, age, star sign etc.?
Thank you.
You can use while True because answer never change.
It's useless while for 1 expression and 1 break.
You should put everything on a while True and check:
while True:
name = input("what is your name?")
job = input("what is your job?")
if len(name) > 0 and name.isalpha() and job.isalpha():
print("great")
break
print("error")
I moved the question into a seperate fuction to de-duplicate the code. It will ask again and again as long as the answer is not satisfactory.
def ask(s):
r = ""
while not r or not r.isalpha():
r = input(s)
return r
name = ask("What is your name?")
print("Okay. Your name is {}.".format(name))
job = ask("What is your job?")
print("Great. Your job is {}.".format(job))

New Programmer, How do you use If and Elif and Else statements? Its giving me NameError: name 'No' is not defined

answer = input('Hi! Would you like to say something? (No or Yes)')
if answer == No or no:
print('Okay then, have a good day!')
elif answer == Yes or yes:
answertwo = input('What would you like to say?')
print(answertwo, 'Hmmmmmm, Intresting.')
**if answer == No or no:
NameError: name 'No' is not defined**
I would suggest you using .lower() for every input. This ensures that if some types "nO" or "YeS" it takes the lowercase equivalent. Example:
ui = input("Type \"Hi\"").lower()
Next, you should really add an else option to your code. This is for answers you don't want them to type. This should be held in a while loop Example:
while(True):
ui = input("Type \"Hi\"").title()
if(ui == "Hi"):
print("Hello")
break
else:
print("That isn't a choice!")

welcome. denied!!! press enter to quit [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
I tried to create a username and password program for my family, but when I open it it says:
Welcome.
Denied!!!
Press enter to quit.
Can anyone solve my problem? The code is below:
print ("Welcome.")
username = ("Please enter your username.")
if username == ("mom, savanna, joseph"):
print ("Granted.")
password = input ("Please enter your password.")
if password == ("1975, 2000, jesus"):
print ("Granted.")
question = ("Do you like it?")
if question == ("yes"):
print ("I thought you would.")
if question == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
else:
print ("Denied!!!")
input ("press enter to quit")
Your primary issue is on this line:
username = ("Please enter your username.")
I presume you mean to have an input function call there.
username = input("Please enter your username.")
That will solve your immediate rejection issue.
You also have the same issue on this line:
question = ("Do you like it?")
Which should also be:
question = input("Do you like it?")
Here's the thing:
You are new to code. We can see that here. However, there is always room for improvement and you can learn from mistakes. Some people make odd code sometimes ;)
I have created a working model for you to see where you went wrong.
print ("Welcome.")
username = input("Please enter your username.")
if username in ("mom", "savanna", "joseph"):
password = input("Please enter your password.")
if password in ("1975","2000","jesus"):
print ("Granted.")
question = input("Do you like it?")
if question == ("yes"):
print ("I thought you would.")
elif question == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
break
You typed question = ("Do you like it?") without the input. This is important since it actually lets the user type something.
You wrote if username == ("mom,savanna,joseph")
this means that if the username is mom,savanna,joseph then you get in. obviously you wanted only one of these to get in. the Boolean operator or can help a lot in this situation.
Notice how I used elif instead of if. Python can only have one if and one else. but as many elifs as you want. It means else-if.
EDIT:
After reading Joel's comment, I noticed that you probably want Mom's password to be 1975, Savannah's to be 2000, and Joseph's to be jesus. How do you think you can do that by using my code given here?
I'm assuming you want to have 3 different usernames, and mom's password to be 1975 etc.
password = {"mom":"1975", "savanna":"2000", "joseph":"jesus"}
print ("Welcome.")
username = input("Please enter your username.")
if username in password: #if x in dict returns True if dict has the key x
print ("Granted.")
mypassword = input ("Please enter your password.")
if mypassword == password[username]:
print ("Granted.")
answer = input("Do you like it?")
if answer == ("yes"):
print ("I thought you would.")
elif answer == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
else:
print ("Denied!!!")
input("press enter to quit")
You may want to put a loop around it so that it doesn't have to get restarted if there's a bad entry.
you are asking if username == ("mom, savanna, joseph") instead of if username in ("mom, savanna, joseph")
if you entered in "mom" for username when it asked you, it would be like comparing this
if "mom" == ("mom, savanna, joseph"):
("mom, savanna, joseph") and "mom" are not equal
to check if an item is in a list use the in keyword
>>> x = [0, 1, 2, 3, 4]
>>> 3 in x
True
you also did the same thing when checking if password ==
also #Alexander O'Mara is correct, you never did the input() for username

Categories