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
Related
I'm an absolute beginner - like I'm Today-years-old with this.
So I'm mucking about with a silly little piece of code to try and help me understand If statements:
print ('How many sausages have you eaten today?')
userInput = ('>5' or '<5')
if userInput input == int ('> 5'):
print ('Whoa! Slow down Fatty!')
elif userInput input == ('< 5'):
print ('Ok, but better call it a day now')
I'm trying to alter the printed message based on how many sausages the user inputs - e.g. above 5 or below 5.
I know that I'm doing something (probably many things) wrong.
Can anyone help to tidy this up?
Here is a fixed version:
There is some notes to help you understand
# To get an input you need to use input()
userInput = input('How many sausages have you eaten today?')
# Turn the input from text to a number with int()
userInput = int(userInput)
if userInput > 5:
print ('Whoa! Slow down Fatty!')
elif userInput < 5:
print ('Ok, but better call it a day now')
Your code has a few problems. First, you cannot use int() to get user input. Instead, you must use input(). Second, you cannot convert inequalities into integers. Like this:
print('How many sausages have you eaten today?')
userInput = int(input())
if userInput > 5:
print('Whoa! Slow down Fatty!')
else:
print('Ok, but better call it a day now')
Notice how I get user input with input(), which will return a string. Then, I convert it to an integer with int(). If the user inputs something that is not an integer, then the program will crash because the input to int() must be able to be converted into an integer.
In the if-else statement, I check if userInput, which is an integer, is greater than 5. I also used an else statement, not an elif, because if userInput is exactly 5 then neither statement would have been true.
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")
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.
I am trying to make code that will retrieve courses, instructors and times from the input of a course number (CS101)
It should tell you the room number, instructor and time of the class after you type in the correct course number.
This is what I have so far.
def main():
courses, instructors, times = create_info()
print('Please enter a course number...')
choice = input(': ').upper()
if choice == 'CS101':
courses.get(CS101)
instructors.get(CS101)
times.get(CS101)
elif choice == 'CS102':
print()
elif choice == 'CS103':
print()
elif choice == 'NT110':
print()
elif choice == 'CM241':
print()
else:
print('Sorry, invalid course number')
print()
main()
print()
main()
def create_info():
courses = {'CS101':'3004', 'CS102':'4501', 'CS103':'6755', 'NT110':'1244',
'CM241':'1411'}
instructors = {'CS101':'Haynes', 'CS102':'Alvarado', 'CS103':'Rich',
'NT110':'Burke', 'CM241':'Lee'}
times = {'CS101':'8:00 a.m.', 'CS102':'9:00 a.m.', 'CS103':'10:00 a.m.',
'NT110':'11:00 a.m.', 'CM241':'1:00 p.m.'}
return courses, instructors, times
main()
It gives the following:
NameError: global name 'CS101' is not defined
The problem is with these lines:
courses.get(CS101)
instructors.get(CS101)
times.get(CS101)
CS101 is assumed to be a variable, and not a string or a dictionary key.
it should be something like this:
print(courses.get('CS101'))
or
print(courses['CS101'])
The key needs to be enclosed in single or double quotes to indicate it's a string, and not a variable.
One nice thing about using dictionaries is that you can quickly check if a key is in them using the in operator. So you could replace your big if/elif/else block with the following:
if choice in courses:
# do the output with choice as a key to the dictionaries
print("Course Number:", courses[choice])
print("Instructor:", instructors[choice])
print("Times:", times[choice])
else:
# choice is not a valid key to the dictionaries
print("Sorry, invalid course number")
This style of coding is known in the Python world as "Look Before You Leap" (LBYL) because you check that the operations you're about to do (looking up the chosen class in the dictionaries) is valid before doing them. An alternative style (which is a bit more advanced), is known as "Easier to Ask Forgiveness than Permission" (EAFP), where you use try and except clauses to handle Exceptions that get generated in some unusual situations. Here's how you could do the code above in a EAFP style:
try:
# try do the output unconditionally
print("Course Number:", courses[choice])
print("Instructor:", instructors[choice])
print("Times:", times[choice])
except KeyError:
# a KeyError is raised if choice isn't in the dictionaries
print("Sorry, invalid course number")
In this case there's not much difference between the two approaches, but in some situations (if checking the situation is valid takes lots of time), EAFP may be faster since the operation that may fail is already doing a check for the invalid situation (so it can raise an appropriate exception).
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'.