Prompt error message for python - python

def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter")
if answer == 'a' or 'A':
print "You chose 'a'!"
elif answer == 'b' or 'B':
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()
This is my code. It's very simple, but for some reason it keeps returning and error message of reference error: 'prompt' is undefined

This is probably not going to solve the problem you are having (although the code worked for me in an iPython shell), there is an issue with your if/else statements. The following statement:
if answer == 'a' or 'A':
print "You chose 'a'!"
will always print "You chose 'a'!" regardless of the letter you enter upon prompting. In python, the or expression you are using asks the following question: Is the answer given equal to 'a' OR is the boolean value of "A" True? What you mean to ask is: Is the answer given equal to 'a' OR is the answer given equal to "A"? This is most concisely represented through:
if answer.lower() == 'a':
print "You chose 'a'!"
That should solve at least one problem that this code is having.

As #Bhargav Rao commented, your code does not match your error, when you run it you will get an output of a regardless of what you enter.
This is because if answer == 'a' or 'A': is the same as saying:
if answer == 'a': OR if 'A': <-- this is always true
To fix this you can use the condition in:
def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter: ")
if answer in ['a','A']:
print "You chose 'a'!"
elif answer in ['b','B']:
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()

Related

Please can somebody explain why I can't put my int inside my input?

I would just like for somebody to explain why the int inside the input for the string 'cont' wont work. Here is the complete program:
import random
ans1=("Go for it!")
ans2=("No way, Jose!")
ans3=("I’m not sure. Ask me again.")
ans4=("Fear of the unknown is what imprisons us.")
ans5=("It would be madness to do that!")
ans6=("Only you can save mankind!")
ans7=("Makes no difference to me, do or don’t - whatever.")
ans8=("Yes, I think on balance that is the right choice.")
print("Welcome to MyMagic8Ball.")
question = input("Ask me for advice then press ENTER to shake me.\n")
print("shaking ...\n" * 4)
cont=input(int("Continue? Yes = 1, No = 0.\n"))
choice=random.randint(1, 8)
while cont != 0:
if choice==1:
answer=ans1
elif choice==2:
answer=ans2
elif choice==3:
answer=ans3
elif choice==4:
answer=ans4
elif choice==5:
answer=ans5
elif choice==6:
answer=ans6
elif choice==7:
answer=ans7
else:
answer=ans8
print(answer)
Because you can't cast a string containing non-numeric characters to an int, as simple as that. What you're currently doing is converting a non-integer string into an integer.
input(int("Continue? Yes = 1, No = 0.\n"))
It should instead be
int(input("Continue? Yes = 1, No = 0.\n"))
Note this would work as long a string containing only integer characters is passed as an input, so be prepared for some exception handling.
#A.Chandu already gave you the answer, and I know this isn't codereview.se, but I can't help myself to add this:
This code:
ans1=("Go for it!")
ans2=("No way, Jose!")
ans3=("I’m not sure. Ask me again.")
ans4=("Fear of the unknown is what imprisons us.")
ans5=("It would be madness to do that!")
ans6=("Only you can save mankind!")
ans7=("Makes no difference to me, do or don’t - whatever.")
ans8=("Yes, I think on balance that is the right choice.")
could be written as:
answers = [
"Go for it!",
"No way, Jose!",
"I’m not sure. Ask me again.",
"Fear of the unknown is what imprisons us.",
"It would be madness to do that!",
"Only you can save mankind!",
"Makes no difference to me, do or don’t - whatever.",
"Yes, I think on balance that is the right choice.",
]
so that this:
if choice==1:
answer=ans1
elif choice==2:
answer=ans2
elif choice==3:
answer=ans3
elif choice==4:
answer=ans4
elif choice==5:
answer=ans5
elif choice==6:
answer=ans6
elif choice==7:
answer=ans7
else:
answer=ans8
can become this:
answer = answers[choice-1]
you still have to somehow support the case when choice is less than 1 or greater than 8.
Also please look at random.choice.
Simple you are trying to change the string into Integer. You're calling a invalid function inside input. because you cannot change the string that contains non-numeric characters so its invalid.
Change
cont=input(int("Continue? Yes = 1, No = 0.\n"))
to
cont=int(input("Continue? Yes = 1, No = 0.\n"))

Function with more choices

I created a simple key stroke counter code that prints number of entered letters. However I am trying to figure out how to make a function so it recognizes 1 letter from 2 letters (singular and plural). I would like to add also 'stroke' in my code, and when the keyboard key is entered only once Id like it to print "You entered 1 stroke" instead of "You entered 1 strokes.".
I tried something but cant really move forward:
print('Start typing: ')
count = raw_input()
print('You entered:'), len(count), ('strokes')
Just use normal conditionals, e.g. using a conditional expression:
print "You entered:", len(count), 'stroke' if len(count) == 1 else 'strokes'
Also, just for fun, the overly clever for the sake of brevity solution that you should not actually use:
print "You entered:", len(count), 'strokes'[:6+(len(count) != 1)]
or:
print "You entered:", len(count), 'stroke' + 's' * (len(count) != 1)
You can use if and else:
if len(count) == 1:
print 'you entered: 1 stroke'
else:
print 'you entered: {} strokes'.format(len(strokes))
Instead of using multiple arguments to print, you can also use string formatting:
print "You entered {} stroke{}".format(len(count), "s"*(len(count)!=1))
Admittedly, the last part is a bit exotic, but you can of course also do
print "You entered {} stroke{}".format(len(count), "s" if len(count) != 1 else "")

3-day old programming noob. List indices must be integers, not tuple

new to the place, and 3 days into learning programming. I am currently running through Code Academy (Python), and during one of my free-rein assignments I decided to write some code that wasn't relevant to the assignment just to test out some things I had learned.
Here is the code I have so far:
guns = ["AWP", "SSG 08", "SG 553", "SCAR-20 ", "G3SG1", "AK-47"]
print guns
print "Of the above mentioned Rifles, which one is the most accurate in CS:GO?",
answer = raw_input()
answer_capitalize = answer.upper()
correct_answer = guns[0]
if answer_capitalize == correct_answer:
print "You are correct. The AWP is the most accurate weapon in CS:GO"
elif answer_capitalize == guns[1, 2, 3, 4, 5]:
print "I'm sorry. " + answer_capitalize + " is not correct. Please try again."
else:
print "You spelled your weapon choice incorrectly. Please try again."
Here is the ERROR I am getting: Traceback (most recent call last):
File "python", line 11, in
TypeError: list indices must be integers, not tuple
Line 11 being the elif statement (spacing is different on here)
There is no error code when inputting 'awp', but for any other input the error code is generated.
The objective of this little bit of kindergarden-grade code is to ask the question, which weapon is the most accurate. If they reply with awp, they get it right, if they choose the wrong weapon and spell it correctly, then the elif statement comes into play. If they butcher the weapon's spelling, or type anything other than a word on the list, then the else statement comes into play. Another nuisance was that it was printing both the IF and ELIF statements after input was received.
My next step, which I haven't even gotten to is looping back in the event they guess wrong. I am just trying to get the first half correct for the time being.
Thanks in advance for any assistance!
Your error is on this line:
elif answer_capitalize == guns[1, 2, 3, 4, 5]:
You can't reference list items like this.
Instead, you could use
elif answer_capitalize in guns: #First if catches the correct answer
Lists don't work that way.
elif answer_capitalize == guns[1, 2, 3, 4, 5]:
This is syntax error. To get a sublist of a list, you use guns[1:5]. However, in your case just get straight to the point and make it use answer_capitalize != correct_answer. To be even more specific and account for the "spelling errors", use answer_capitalize in guns.
In a case where the guns contained also lowercase items and you wanted to check if it's in the list case insensitively, you could transform guns to uppercase using list comprehensions: guns_uppercase = [gun.upper() for gun in guns].
You can use similar to what you have used in if statement.
elif answer_capitalize != correct_answer:
print "I'm sorry. " + answer_capitalize + " is not correct. Please try again."
!= means not equal.
As already spelt out, there's no concise syntax to get a non-contiguous sublist. You can however use a list comprehension:
elif answer_capitalize in [guns[i] for i in [1,2,3,4,5]]:
However probably it would be more efficient to do something like:
elif any(answer_capitalize==guns[i] for i in [1,2,3,4,5]):
elif answer_capitalize == [0 for guns in range(5)]:

Why condition "else" doesn't work in my python code

here is my code.
highnum=100
lownum=0
guessnum=highnum/2
print "Please think of a number between 0 and 100!"
while True:
print "Is your secret number is "+str(guessnum)+"?"
print "Enter 'h' to indicate the guess is too high.",
print "Enter 'l' to indicate the guess is too low. ",
print "Enter 'c' to indicate I guessed correctly."
result=raw_input()
if result=="h":
highnum=guessnum
guessnum=int(highnum+lownum)/2
if result=="l":
lownum=guessnum
guessnum=int(highnum+lownum)/2
if result=="c":
break
else:
print "Sorry, I did not understand your input."
print "Game over. Your secret number was: "+str(guessnum)+" ."
Everytime I type the input, it prints out "Sorry, I did not understand your input." The condition "else" doesn't work.
I don't know why. Could anyone help me? Thank you very much!
Because as written, each of your if statements are independent, the else only corresponds to your last if result == 'c', so if they don't type 'c', they hit your else case.
Instead, you can use if/elif/else to try each of your cases.
if result=="h":
highnum=guessnum
guessnum=int(highnum+lownum)/2
elif result=="l":
lownum=guessnum
guessnum=int(highnum+lownum)/2
elif result=="c":
break
else:
print "Sorry, I did not understand your input."

Why Aren't These Arguments Working On Python 3? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I am a novice coder who's just started coding about 4-5 weeks ago. The best I have achieved is a basic Python username and password login page for a 'top secret' website (the website is fake). However, just to refresh my memory of basic coding (I've been doing some un-related things lately), I tried making a basic childrens game to do with the alphabet. Here's my current code:
name = input("What's Your Name?: ")
print("Welcome" , name , "to the 3 lucky guess alphabet skills builder!")
print("Let's get started:")
C = input("What Is The 3rd Letter of The Alphabet: ")
if C == 'C' or 'c':
print("Congraulations!")
else:
print("Think We Should Retry That!")
C
if C == 'C' or 'c':
print("That's Better!")
Z = input("What Is The Last Letter of The Alphabet: ")
if Z == 'Z' or 'z':
print("You're Really Good At This! One More!")
else:
print("Have Another Go!")
Z
if Z == 'Z' or 'z':
print("That's More Like It! Last One!")
J = input("What Is The 10th Letter Of The Alphabet: ")
if J == 'J' or 'j':
print("Great! How Many Did You Get In Total?")
else:
print("Unlucky, Better Luck Next Time!")
total = input("How Many Did You Get In Total?: " , print("Out Of 3!")
print("Wow! You Got" , total , "! Well Done" , name , "!!!")
exit
Why aren't any of the 'else' arguments working?
Also, why won't the second to last bit of code work - it just states a syntax error!
I have tried indenting all the else statements but that results in a syntax error too!
Please help! :)
The if statement you wrote, like the following
if C == 'C' or 'c':
doesn't do what you mean. The expression after or just checks whether 'c' evaluates to true, which it always will. That's why the code after else: won't execute.
You have to write it like this:
if C == 'C' or C == 'c':
It's difficult to know what you mean by "not working" - you should be more specific about the error you're seeing. Are you referring to this?
else:
print("Have Another Go!")
Z
if Z == 'Z' or 'z':
print("That's More Like It! Last One!")
The second line of the body simply evaluates the variable Z - it doesn't change anything. Therefore, the conditional following it still returns the same result as the last time you evaluated it.
Also, as the other answer points out,
if a = "foo" or "bar"
will always be True, because "bar" is a non-false value, and an or with any non-false value is True.

Categories

Resources