Python: Loop Prompt Back Around - python

A lot of the errors of this Python file have been fixed but there is one last thing it's not working. I need the else statement to loop back to ask the question again if neither Yes or No is entered. You can probably see by the code what I was going for but I'm probably not even on the right track. Can someone help me with this one last thing?
#These are my variables which are just strings entered by the user.
friend = raw_input("Who is your friend? ")
my_name = raw_input("Enter Your Name: ")
game_system = raw_input("What's your favorite game system? ")
game_name = raw_input("What's your favorite game for that system? ")
game_status = raw_input("Do you have the game? (Yes or No) ")
game_store = raw_input("What is your favorite game store? ")
game_price = raw_input("What's the price of the game today? Enter a whole number. ")
#This is what is printed after all the prompts. There is no condition for this print.
print "I went outside today and my friend " + friend + " was outside waiting for me. He said \"" + my_name + ", did you get the new " + game_system + " game yet? You were getting " + game_name + " today, right?\""
#If the condition on the Yes or No question is yes, then this code runs.
if game_status == "YES":
print "\"You know I got it, man!\" I said. \"Awesome! Let's play it,\" he said. \"I heard " + game_name + " is supposed to be amazing!\" We went back inside and took turns playing until " + friend + " had to go home. Today was a fun day."
#If the condition is No, then this code runs.
elif game_status == "No":
print "\"Well let's go get it today and we can come back here and play it!\" We went down to " + game_store + " and baught " + game_name + " for $" + str(game_price) + " and we went back to my house to take turns playing until " + friend + " went home. Today was a good day. (Now try again with the No option!)"
#If the condition meets neither Yes or No, then this code runs, sending the user back to the same question again. This repeats until a condition is met.
else:
raw_input("That answer didn't work. Try again? Do you have the game? (Yes or No) ")

This:
if game_status: "YES"
isn't how you make an if statement. You're treating it like the syntax is
if some_variable: some_value
and if the variable has that value, the if statement triggers. In fact, the syntax is
if some_expression:
and if the expression evaluates to something considered true, the if statement triggers. When you want the if statement to trigger on game_status equalling "YES", the expression should be game_status == "YES", so the if line should go
if game_status == "YES":
Similarly, the elif line should go
elif game_status == "NO":

I would encourage to you always break to a new line after a conditional...
if game_status == "YES":
print "\"You know I got it, man!\" I said. \"Awesome! Let's play it,\" he said. \"I heard " + game_name + " is supposed to be amazing!\" We went back inside and took turns playing until " + friend + " had to go home. Today was a fun day."
anything that is indented after the "if game_status:" will get run. And it reads better.
edit:: if you use single quotes for all strings then you don't need to escape the double quotes...
print '"You know I got it, man!" I said. "Awesome! Let\'s play it," he said. "I heard ' + game_name + ' is supposed to be amazing!" We went back inside and took turns playing until ' + friend + ' had to go home. Today was a fun day.'
it's a matter of preference...but may look less cluttered.

Related

PY Chatbot Repeating user input prompt

New to Python here. I've been coding a small chatbot for a while now, and when I prompt the user to enter something instead of answering with the correct response the bot just repeats the prompt. Everything before that works just fine, but it gets stuck in a loop of asking the user for an input.
print("Hello " + User_Name + """.
Tonic is a simple Python chatbot made in order to test things such as boolean logic
and variable definition.
(Also remember to speak to the bot in lowercase, without punctuation.)""")
while 1 == 1:
str1 = input("Say something: ")
#"hello" //////////////////////////////////////////
if "hello" in str1:
print("Hi " + User_Name + "! (I read this as the 'hello' greeting.");
#"hi" //////////////////////////////////////////
if "hi" in str1:
print("Hi " + User_Name + "! (I read this as the 'hi' greeting.");
#"how are you?" //////////////////////////////////////////
if "how are you" in str1:
print("good, how about you? (I read this as you asking 'how are you'.)")
mood = input("Enter Mood: ")
if "good" in mood:
print("Nice to hear " + User_Name + "! (I read this as you being in a good mood.)");
if "bad" in mood:
print("I hope you feel better soon, " + User_Name + "! (I read this as you being in a bad mood.)");
#"name length" //////////////////////////////////////////
if "name length" in str1:
print( "Your name is " + len(User_Name) + "letters long. (I read this as you asking how long your name is.");```
Your while loop does not have an exit condition. It will repeat forever since 1
is always equal to 1.
Instead, you could do while (str1 != "quit") which would stop the while loop once the user enters "quit" in the prompt.
Also, side note, you should not be using semicolons at the end of lines in Python.
print("Hello " + User_Name + """.
Tonic is a simple Python chatbot made in order to test things such as boolean logic
and variable definition.
(Also remember to speak to the bot in lowercase, without punctuation.)""")
while (str1 != "quit"): # You need an exit condition here
str1 = input("Say something: ")
#"hello" //////////////////////////////////////////
if "hello" in str1:
print("Hi " + User_Name + "! (I read this as the 'hello' greeting.")
#"hi" //////////////////////////////////////////
if "hi" in str1:
print("Hi " + User_Name + "! (I read this as the 'hi' greeting.")
#"how are you?" //////////////////////////////////////////
if "how are you" in str1:
print("good, how about you? (I read this as you asking 'how are you'.)")
mood = input("Enter Mood: ")
if "good" in mood:
print("Nice to hear " + User_Name + "! (I read this as you being in a good mood.)")
if "bad" in mood:
print("I hope you feel better soon, " + User_Name + "! (I read this as you being in a bad mood.)")
#"name length" //////////////////////////////////////////
if "name length" in str1:
print( "Your name is " + len(User_Name) + "letters long. (I read this as you asking how long your name is.")
Fix indentation
Convert output from len into string
print("Hello " + User_Name + """.
Tonic is a simple Python chatbot made in order to test things such as boolean logic
and variable definition.
(Also remember to speak to the bot in lowercase, without punctuation.)""")
while 1 == 1:
str1 = input("Say something: ")
#"hello" //////////////////////////////////////////
if "hello" in str1:
print("Hi " + User_Name + "! (I read this as the 'hello' greeting.");
#"hi" //////////////////////////////////////////
if "hi" in str1:
print("Hi " + User_Name + "! (I read this as the 'hi' greeting.");
#"how are you?" //////////////////////////////////////////
if "how are you" in str1:
print("good, how about you? (I read this as you asking 'how are you'.)")
mood = input("Enter Mood: ")
if "good" in mood:
print("Nice to hear " + User_Name + "! (I read this as you being in a good mood.)");
if "bad" in mood:
print("I hope you feel better soon, " + User_Name + "! (I read this as you being in a bad mood.)");
#"name length" //////////////////////////////////////////
if "name length" in str1:
print( "Your name is " + str(len(User_Name)) + "letters long. (I read this as you asking how long your name is.");
i just found a module which you can create a chatbot with just a handful lines of code
refer to this https://pypi.org/project/prsaw/
or
from prsaw import RandomStuff
random = RandomStuffV2()
str1 = input("message: ")
response = random.get_ai_response(str1)
print(response)

How do I make my code return outside loop? Could someone please fix my code?

I hope you are doing well!
I am making a code for my free time.
I just have a small issue with it.
After you buy a sword in my game, I put "break" so that it brings you to the else statement.
(Just put my code into a console such as replit or pycharm and you will understand)
But when I put my break, it ends my code!
I would want it to instead write everything after this part:
else:
print("\033[1;37;40mYou exit the shop.")
print("After leaving the shop, you head home.")
Here is my code:
import time
def coins_left(player_name, coins):
print(player_name + "\033[1;37;40m, you currently have " + str(coins) + " Coins!")
CharacterHealth = 100
Coins = 1000
Sword = "Diamond" or "Metal" or "Wooden"
Shop = ["Shop"]
print("Hello! Welcome to my game! This is an extremely fun action game! I hope you enjoy!\n")
time.sleep(2)
name = input("Please enter your username.\nUsername: \033[1;32;40m")
response = input("\033[1;37;40mHello, " + name + ". Would you like to enter the shop?(yes/no)\nSelection: \033[1;32;40m")
if (response == "Yes") or (response == "yes"):
while True:
answer = input("\n\033[1;37;40mYou have %s coins. Would you like to buy:\n(a) Diamond sword [Costs 900]\n(b) Metal Sword[500]\n(c) Wooden sword[200]\n(d) Back\nSelection: \033[1; 32; 40 m" % Coins)
if (answer == "A") or (answer == "a"):
Sword = "Diamond"
print(name + ", you have bought a " + str(Sword) + " Sword!")
Coins -= 900
coins_left(name, Coins)
break
elif (answer == "B") or (answer == "b"):
Sword = "Metal"
print(name + ", you have bought a " + str(Sword) + " Sword!")
Coins -= 500
coins_left(name, Coins)
break
elif (answer == "C") or (answer == "c"):
print(name + ", you have bought a " + str(Sword) + " Sword!")
Coins -= 200
coins_left(name, Coins)
break
elif (answer == "D") or (answer == "d"):
print("You exit the shop.\n")
break
else:
print("\033[1;37;40mYou exit the shop.")
print("After leaving the shop, you head home.")
Thank you so much for helping me through this process! I hope you can fix this!
Have a great day!
It looks like you are misunderstanding how if-else statements works. Since your print statements are inside the else statement they will only execute if the user had entered "yes" or "Yes". If you want the print statements to execute only if the user had entered anything else, this would work as expected.
However, if you simply want them to be run whenever they "leave" or don't enter the shop you can simply leave them outside any conditional, or even add a boolean value to make sure that they actually entered the shop beforehand:
shop_entered = False
if (response == "Yes") or (response == "yes"):
shop_entered = True
# do shop things...
if shop_entered:
print("\033[1;37;40mYou exit the shop.")
print("After leaving the shop, you head home.")
When you break your loop you are telling the program to stop the loop and execute the code following the loop; however, since there is no code following the loop, the if branch of the conditional is finished, and python will execute anything following the conditional (in this case anything that follows the else). Since there is no other code, your program exits without any more code being run.
If you add a print statement at then end or your script, something like print("thanks for playing!"), you will see "thanks for playing!" printed to the console after everything else is run.

How can I choose a random conversation output in Python?

I'm trying to get my script to choose between three options of conversation, labeled petconvo1, petconvo2, or petconvo3. The program asks what pet the user has and then picks a random thing to say about them. Based on what tidbit the script picks, I want to continue the conversation there. My problem is that it just stops and doesn't keep going with the conversation. What's the best way to do this?
My code is below.
#imports the random module
import random
#Asks what pet the user has
pet = input("What kind of pet do you have? ")
#Sets the input to lowercase
petlower = pet.lower()
#Sets tidbits of conversation about the pet
petconvo1 = ("Oh, I've heard that " + petlower + " is a good companion to have.")
petconvo2 = ("Oh, really? I had " + petlower + " when I was growing up.")
petconvo3 = ("Does it cost a lot to keep " + petlower + " fed?")
#Turns the tidbits into a list
petconvolist = [petconvo1, petconvo2, petconvo3]
#Compliments pet
print(random.choice(petconvolist))
#Continues the conversation
if petconvolist == petconvo1:
time.sleep(1)
print("Wouldn't you agree?")
else:
if petconvolist == petconvo2:
time.sleep(1)
print("I think it's important for children to grow up with pets.")
else:
if petconvolist == petconvo3:
time.sleep(1)
foodbudget=input("Does it cost a lot to feed " + petlower + "?")
time.sleep(.5)
else: pass
The script stops after this bit:
print(random.choice(petconvolist))
Thanks in advance!
hmm first in the if statements you should use the elif statement. Afterwards you should use set the random selection to a var in order to check it. This code works for me.
#imports the random module
import random
#Asks what pet the user has
pet = input("What kind of pet do you have? ")
#Sets the input to lowercase
petlower = pet.lower()
#Sets tidbits of conversation about the pet
petconvo1 = ("Oh, I've heard that " + petlower + " is a good companion to have.")
petconvo2 = ("Oh, really? I had " + petlower + " when I was growing up.")
petconvo3 = ("Does it cost a lot to keep " + petlower + " fed?")
#Turns the tidbits into a list
petconvolist = [petconvo1, petconvo2, petconvo3]
#Compliments pet
convo = random.choice(petconvolist)
print(convo)
#Continues the conversation
if convo == petconvo1:
time.sleep(1)
print("Wouldn't you agree?")
elif convo == petconvo2:
time.sleep(1)
print("I think it's important for children to grow up with pets.")
elif convo == petconvo3:
time.sleep(1)
foodbudget=input("Does it cost a lot to feed " + petlower + "?")
time.sleep(.5)

'while' loop in Python

I'm starting to learn Python by throwing myself in the deep end and trying a bunch of exercises.
In this particular exercise, I'm trying to make a program to ask the name and age of the user and tell the user the year they're going to turn 100.
I tried putting in a yes/no input to ask if the user's birthday has passed this year, and give the correct year they will turn 100, based on that.
I wanted to incorporate a while loop so that if the user enters an answer that isn't "yes" or "no", I ask them to answer either "yes" or "no". I also wanted to make the answer case insensitive.
print("What is your name?")
userName = input("Enter name: ")
print("Hello, " + userName + ", how old are you?")
userAge = input("Enter age: ")
print("Did you celebrate your birthday this year?")
while answer.lower() not in ('yes', 'no'):
answer = input ("Yes/No: ")
if answer.lower() == 'yes':
print ("You are " + userAge + " years old! That means you'll be turning 100 years old in the year " + str(2019 - int(userAge) + 100))
elif answer.lower() == 'no':
print ("You'll be turning " + str(int(userAge) + 1) + " this year! That means you'll be turning 100 years old in the year " + str(2019 - int(userAge) + 99))
else:
print ('Please type "Yes" or "No"')
print ("Have a good life")
You should addd the input before trying to access the answer.lower method, so it will be something like:
answer = input('Yes/No: ')
while answer.lower() not in ('yes','no'):
answer = input('Yes/No: ')
Check geckos response in the comments: just initialize answer with an empty string

How to get user input? Python

I'm very new to this, so please be gentle!
As a little bit of work for my Python course, I am learning to run user input code. I put together the below code but when I run it using command-B, it asks me the 'What's your name?' question, but when I type in my name and click enter, nothing happens? For info, I am using Python 3.7, and using SublimeText.
I am 100% sure this is an easy answer, but surprisingly I cannot find the answer, and I have searched a little bit on here, and generally via Google, etc.
name=input("What's your name?:")
print("Hi",name,"how do you do.")
age=input("How old are you",name,"?:")
print("Great",name,"I'm",age,"years old too.")
city=input("Which city do you come from",name,"?:")
print("What a coincidence, I am from",city,"too.")
print(name,", here is your record //")
print(name, age, city)
Thanks for any help, and if you guys have an tips for a super newbie, it would be much appreciated!
You are having some issues because you have few syntax errors. The following is your code with the corrections. There you go:
name = input("What's your name?:")
print("Hi "+ name + " how do you do.")
age = input("How old are you " + name + " ?:")
print("Great " + name + "I'm " + age + " years old too.")
city = input("Which city do you come from " + name + " ?:")
print("What a coincidence, I am from " + city + " too.")
print(name + " , here is your record //: ")
print(name + " " + age + " " + city)
Good luck with learning Python :)
a = input() //for string
b = int(input()) //for int
c = float(input()) //for float
name=input("What's your name?:")
print("Hi"+name+"how do you do.")
age=input("How old are you "+name+" ?:")
print("Great "+name," I'm ",age+" years old too.")
city=input("Which city do you come from "+name+" ?:")
print("What a coincidence, I am from "+city+" too.")
print(name+", here is your record //")
print(name+age+city)
Use + for concatenation inside print

Categories