Comparing raw input to an specific element in an array using Python - python

I have a little piece of code in Python where I'm trying to compare a user input to a specific element in an array. Here is the code:
movies = ["movie 1", "movie2", "movie3"];
answer = raw_input("What is your guess: ")
if answer == movies[1]
then print ("yes that is correct")
else:
print ("no that is incorrect")
I know the indentation above looks wrong becasue I typed it out in the text box and I'm new to this site as well as python.
I also know that I probably need to use some sort of conditional loop, maybe a while loop, but I'm having trouble finding where I can compare user input string value to a string value in my array. Any ideas how I might accomplish this?

Have fun with Python! I guess you are trying to make a loop which keeps receiving inputs from user to compare with the desired input until user types the correct input. If so, one way, it can be implemented as following (but think of adding a break condition, like input == "Bored" , to avoid infinite loop and hard stopping your code):
movies = ["movie 1", "movie2", "movie3"]
correctAnswer = movies[1]
is_notCorrect = True
while(is_notCorrect):
answer = raw_input("What is your guess: ")
if answer == correctAnswer:
print("Yes, that is correct")
is_notCorrect = False
else:
print("No, that is incorrect")
In the code above, when is_notCorrect turns into False. At next condition checking, it will break condition, and done with the loop.
Your code has some issues
movies = ["movie 1", "movie2", "movie3"]; # No need the semi-colon in Python
answer = raw_input("What is your guess: ")
# Need a colon here after if condition, new line, and indent.
#If you don't like the colon, you need to write a different way with one line of code Eg: <Do A> if <Condition happens> else <Do B>
if answer == movies[1]
then print ("yes that is correct") # No then in if-else statement in Python
else:
print ("no that is incorrect")

Related

Got a problem with Python conditional structure

I have an if conditional structure in my python code and i got a problem with how its executing...
I expect the first nested if to print The input choice you entered is out of range") when false is returned but its executing the code in the else which is you entered 4 in the second nested if, i expect it to execute the false counterpart of the first nested if which is print("nThe input choice you entered is out of range"), Am i indenting the wrong way or?Please help me
message=input("Enter the message you want encrypted")
if(message.isalpha()& message.__len__()!=0):
options=("1. Substitution Cypher","2.Playfair Cypher","3. Transposition Cypher", "4. Product Cypher","RSA Cypher")
print("Choose an encryption Cypher you would like to use?")
print(options[0])
print(options[1])
print(options[2])
print(options[3])
choice=int(input("Please reply with a number for choice of Cypher"))
##USER NEEDS CHOICE OF encryption algorithm to use
if(choice>=1&choice<=4):
if(choice==1):
print("You chose 1")
elif(choice==2):
print("You chose 2")
elif(choice==3):
print("You chose 3")
else:
print("You chose 4")
else:
print("nThe input choice you entered is out of rage")
else:
print("User input is required in form of alphabet format")
if(choice>=1&choice<=4):
This does not do what you think. Due to operator precedence & is more sticky than comparison therefore above is equivalent to
if(choice>=(1&choice)<=4):
If you want to keep & you need to add brackets as follows
if((choice>=1)&(choice<=4)):
However note that thanks to one of python's feature you might write
if(1<=choice<=4):
to get same result

Using a While Loop to check whether user's input (string) belongs to a List?

I'm new to Python, with a bit of background in C. I'd like to set up a while loop with try - except - else construction. I have successfully done this when trying to verify a data type (using except: ValueError), for instance prompting the user for an integer. However for this program, the the user inputs a string and the program needs to check that string against a list of strings, and if it's not in there, ask the user again. My code so far runs but regardless of the user's input, the loop breaks. Here it is now:
senses = ["touch", "smell", "sight", "hearing", "taste"]
while True:
try:
choice = input("What is your favorite sense? ")
except:
if choice not in senses:
print("Sorry, I don't think that's a sense")
#try again, return to start of loop
continue
else:
break
Originally my code looked like this and it worked but there is the issue of redundancy with the input method:
senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = input("What is your favorite of the 5 human senses:")
while choice not in senses:
choice =input("What is your favorite of the 5 human senses")
A matter of personal preference / problem suitability, but I would tend to use something like this
senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = ""
while choice not in senses:
choice =input("What is your favorite of the 5 human senses")
This initializes choice as something not in senses, thus forcing the first loop
I'd write that like:
senses = {"touch", "smell", "sight", "hearing", "taste"}
while True:
choice = input("What is your favorite of the 5 human senses? ")
if choice in senses:
break
This way you're only asking the question in one place. while True means "do this forever", and break stops the loop once the condition is met.

Error Tapping a section of code

I have a while statement which works well and I have a whole section of code that asks the user to input how many names they have which will then ask them for a name that amount of times and then each time a name will be entered.
I need the section of the names entered to be error tapped but I don't know how to do it, as I have a while statement and I may need to put another while statement in, although I have error tapped the section for amount of names in numbers.
Also there is code further on with a dictionary and sorts but I need help with the one section of error tapping started at while currentnum part
print("Please enter each name when asked without any spaces.") #The program will post this
print("Please enter each of your names individually also.") #Program will again post this
names = [] #This is the value of names which will be changed depending on the input
currentnum = 0 #Currentnum value is 0
while True: #While loop as it will revert to the start if question answered incorrectly
try:
numofnames = int(input("How many names do you have? "))
except ValueError: #if the input is not an integer or a whole number it will
print("Sorry that was not a valid input please retry")
continue #it will loop back and ask the question again as it says that the unput was not valid
else:
break #If the input is correct then the loop will break and continue to the next section of the program
while currentnum < numofnames: #This means that while currentnum is smaller than input for numofnames it will continue to ask question. This is another loop
currentnum = currentnum + 1 # every time the question is asked it means that currentnum gets 1 added to it and will continue to ask untill it is the same as the input for numofnames
name = str(input("Enter your name: ")) #Name asked to be entered in string
name = name.upper() #This changes all letters to upper case no matter what so there is no error for upper and lower case or a bigger dictionary showing lower and upper case values.
names.append(name)
Yep. The easiest way to describe what you're doing is to use the .isalpha attribute in an if statement. First you will have to def your while loop
Like the following:
def Loop():
name_input_complete = False
while name_input_complete != True:
string = input("Please input :")
string = str(string)
if string.isalpha():
name_input_complete = True
else:
print("Please do not use numbers and spaces")
Loop()
Loop()
Baisically you have to define the loop and then run it. The if statement(which is the part you should add to your loop) then checks if there is nothing other than letters. If true, your done with error trapping and the loop is exited. The program continues outside the loop. If not then the while is repeated because the Loop() function is called again.
Your code looks very good to me. I dont see what input can the user put that could cause an error, since most data in python can be stringed AND names can be pretty much anything!. If you could comment exactly what error could be caused i might be able to help you

In this very basic code i can't figure out what's the sytax error here in line 6 is (python)

myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
ready = input("Are you readyyyy!?")
if ready = "yes" or "yeah" or "totally" or "hell yeah" or "yupp" or "yepp" or "uhumm" or "sure": <-- here's the problem it says, at "sure"'s 1st "-sign
print("Let's go!")
loop = "y"
else:
print("I'm sorry to hear that.")
loop "n"
Could please anyone help, beginner here. I tried to delete and add new word, I restared the program and the computer because there's something clearly wrong. If I delete a word like "sure" the pointer will still point to the same exact place but there's nothing there...
You're using a single = sign in your if statement. That's not allowed. If you want to check for equality, you'll need to use ==. The = operator is only for assignment statements.
While changing = to == will fix the syntax error, your code still won't work exactly right. That's because == will not be distributed over all the or options you show. The expression a == b or c gets interpreted as (a == b) or c, and if c is "truthy" (as any non-empty string will be), the expression will be considered true.
Instead, you probably want to use something like if ready in {"yes", "yeah", "totally"}. This creates a constant set object and tests if the value of the ready variable is in the set (which is a fast check).
You are using a = instead of a == in your if statement. However, I would recommend doing if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp"} to account for them using all uppercase.
Also, you seem to be missing your actual loop statements. I noticed you had variables named loop that are 'y' and 'n' but don't actually use them. You should also do something like this:
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
loop = True
while loop:
ready = input("Are you readyyyy!?")
if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp", "uhumm", "sure"}:
print("Let's go!")
loop = False
#To break out of the while loop that will keep asking them when they are ready
else:
print("I'm sorry to hear that.")

(Python) For loop syntax - execute for only one item?

Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.

Categories

Resources