Python operator != isn't working as expected - python

Does anyone know why this sample is not working? I have not used Python in years and wanted to test NOT operators. As far as I can remember this should work, I have checked online and it appears to be the correct format. Am I missing something?
Essentially it is just asking for an input of 1, 2 or 3. If the user enters those it will break out the loop. If they do not enter either 1, 2 or 3 it will print to screen and loop again. Currently it is only printing "Invalid input!" then looping not breaking.
while True:
x = input("1, 2, or 3?\n")
if x != 1 or x != 2 or x != 3:
print("Invalid input!")
else:
break
I am using Python 3.6.4.

Well, this will be always true. if I type 1, it'll fail the first condition, but it'll pass the other two: x != 2 or x != 3. Any other number different than 1, 2 or 3 will also be true for all the conditions. There's no problem with the comparison operator.
I think you want to do something like:
x = int(input("1, 2, or 3?\n"))
if x not in [1, 2, 3]:
print("Invalid input!")
The conversion of x to int is also important. Otherwise, the comparison of x with the numbers will be always false.

Related

If function error. Not equals to function not working

I am writing this program and it works fine,
I leave it for sometime and the code stops working.
Please help me in this function;
Here is the code:
acceptables = [1, 2, 3, 4, 5, 6, 10]
try :
toss = input("Toss a number from 1 to 6 (10 included): ")
except ValueError:
print("Invalid")
if toss != acceptables:
print("Illegal Numbers!")
time.sleep(2)
exit()
else:
pass
So what should happen is, the user will enter a number in toss and it will check
if the number is from acceptables, if not it will quit the program.
But now, I entered number that is in acceptables and it still ends up showing
"Illegal Number" and quits the program.
Is this a new python3 update or something that I missed out on? Please help
You've got two problems:
toss = input(...) returns a string, but you want to compare that value to ints. Try a type conversion: toss = int(toss) to transform your str from "1" to 1.
You're checking if the number is in the list using if toss != acceptables: which will always be False because an int (or str at the moment) will never be equal to a list. You want to check if toss is in the list of acceptables. Try this instead: if toss in acceptables:
There are a few issues. First, this line:
toss = input("Toss a number from 1 to 6 (10 included): ")
will store the string value of whatever you submit into toss. You likely want this line to read:
toss = int(input("Toss a number from 1 to 6 (10 included): "))
to ensure you get an integer or a ValueError in the case the user types a non-integer string.
Secondly, this line:
if toss != acceptables:
is checking if toss, what would be an int, is not equal to a list, essentially doing this: if 5 != [1, 2, 3, 4, 5, 6, 10]. You instead likely want this to read:
if toss not in acceptables:
To check if this number is in your list of acceptable numbers.

How do I add different levels & a quit option to my guess a number game?

So I'm a freshman in high school trying to figure out Python coding, and I need to make a guess a number game.
My first level works fine, but I need to make it so it has 3 different levels, and a quit option. I don't understand these while loops.
I'm really sorry if I posted something wrong or this is an already asked question, but any help would be much appreciated!
Here's my code so far:
import random
print("let's play guess a number!")
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
while number1!=guess1:
print
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
if guess1==number1:
print("you guessed it!")
if myLevel == 2:
nextumber2= random.randint (1,100)
guess2=int(input("guess an integer from 1 to 100"))
while number2!=guess2:
print
if guess2<number2:
print("guess is too low!")
guess2=int(input("guess again!"))
elif guess2>number2:
print("guess is too high!")
guess2=int(input("guess again!"))
print("you guessed it!")
Welcome to Python! Since you're new I'll go over the fundamentals of everything you need to learn to complete this game.
Your code looks good so far. Since your question is mainly about a while loop, you'll need to learn what exactly that does. A while loop is a block of code that first checks the provided condition, then executes the indented code block if the condition evaluates to true. Then, it checks the condition again, and executes the code again if it's still true. This continues until the condition evaluates to false.
x = 0
while x < 5:
print(x)
x += 1
Try this code out. It should print 0 to 4 then stop when x = 5.
What's actually happening:
x = 0
# loop starts here
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #false
# At this point, x is not longer < 5, so the repeating stops and the code continues to run as normal.
Imagine if you wanted to print numbers from 1 to 50. Would you rather have a loop, or do each number by hand like the above? In fact, if you want to print from 1 to x, where you don't know what x will be beforehand, you'll need a loop!
While loops are extremely powerful and are used all over the place. The idea is that you want to do something until some sort of flag or condition occurs, then stop doing the thing. I hope that makes sense.
Secondly, you need to learn about the input function.
x = input()
The input function is just a regular function that returns a string with the user input. If you want to make it into a number, then you have to typecast it to the type of number you want.
x = int(input())
You're already doing this. But what if you want a string?
Let's get back to your code:
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
# User inputs "quit"
>> ValueError: invalid literal for int() with base 10: 'quit'
This happens because we already converted our input to an int. However, at no point are we doing any math with MyLevel. Here's a better way:
myLevel = input("would you like to play level 1, 2, 3, or quit?")
if myLevel == "quit":
exit() # this exits a python program entirely.
if myLevel == "1":
#do level 1 stuff
if myLevel == "2":
#do level 2 stuff
if myLevel == "3":
#do level 3 stuff
Our lives are made easier by not converting this variable. However, it's correct to convert the guess-a-number input() results because those need to be compared to other numbers.
Finally, this project is meant to teach you a very valuable lesson! Don't repeat yourself in the code. If you find yourself doing ANYTHING twice (or any number of times more than one), then use a function, loop, or other construct to condense it. We'll use your project as an example. I updated the code to get it working.
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
# This whole while loop needs to be within the "if" statement's indented block.
# Why? Because we only want to execute the code *if* we're on level 1.
while number1!=guess1:
print(str(number1) + " isn't correct.") #fixed this
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
# The last if statement isn't needed so I took it out.
# Why? Because if the loop ends, it's because guess1==number1. So our condition
# always returns true. Therefore, we can just move the print statement outside of the
# while loop.
print("you guessed it!")
This is a fine start and it should be working. Now, what do we do for level 2? The first thing that comes to mind is to copy paste this whole code block... but that would be repeating ourself! We're going to reject that idea straight out because we don't repeat ourselves.
Instead, let's use a function to wrap up the core of the game into a nice little repeatable action. Functions are just repeatable actions.
# define a function with a variable to hold the highest possible guess
def guess(max):
# get a random number based on our max
number = random.randint(1,max)
guess = int(input("guess an integer from 1 to " + str(max)))
while number != guess: # Guess is wrong
if guess < number:
print("guess is too low")
elif guess > number:
print("guess is too high!")
# Since guess is wrong, we can just assume we'll always do this.
# I removed the int() wrapper for the next step
guess = input("guess again! or would you like to quit?")
# Adding "quit" as an option:
if guess == "quit":
exit()
else:
guess = int(guess) # Now we can convert to int for our comparisons.
print("you guessed it!")
With this defined, now we just need to call the function itself at the correct difficulty.
if myLevel == "1":
guess(10)
if myLevel == "2":
guess(100)
if myLevel == "3":
guess(500)
If you're still alive after reading all this, hopefully you noticed a problem here -- we're repeating ourselves with 3 different if statements. We can do better, but that's a lesson for another day!
tl;dr:
1) Input returns a string, so you converted it to an int immediately. However, a string of "quit" is a valid choice and this will give you an error if you convert it to an int. Instead, test for "quit" first, then convert to an int if needed.
2) A while loop is for repeating something until some sort of condition is cleared. Loops and if statements can be nested within other statements. Think about when you want your code to run and honestly just practice a bit to make this more natural.
3) If you're repeating something in your code (copy/pasting similar things over and over again), strongly consider making a function or loop or something similar to do the work for you!
For the quit it's simple. Either use quit(), or, if you don't want to reload the program, put everything in a while loop and have the quit function set it to false, and then true after a while. For the 3 levels, you could either write 3 entirely separate programs or use if statements to change numbers or something. I'm not sure that would work, though.
As for your while problem, just use while some_variable='whatever_you_want': and you're done.

10 Integers and 1 input that is asked too soon in Python 3

I'm trying to create a program right now where the user insert 10 integers, and then gets the possibility to do the following:
program: "What would you like to do?: 1. Show me the biggest integer. 2. Show me the smallest integer. 3. Show me the average of all numbers combined with one decimal. 4. Show me all the entered integers. 5. Terminate this program."
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
s = [max(nr), min(nr), nr, sum(nr)/len(nr)]
z = int((input("What would you like to do? Please enter a number between 1 to 4. ")))
if z == 1:
print(s[0])
elif z== 2:
print(s[0])
elif z == 3:
print(s[0])
elif z == 4:
print(s[0])
else:
print("Please select a number between 1 to 4.")
This is how far I've come, and now I'm just stuck. When I get the "Please enter an Integer" I enter, let's say for example "1". Then I get the "Please enter a number between 1 to 4" directly after that. I would also like the "Please enter a number between 1 to 4" list several options but got: "TypeError: input expected at most 1 arguments, got 5". I also would like a fifth option to terminate the program. I tried "brake" but I guess it doesn't work like that?
I've re-formatted and added some bits to get this example working. Hopefully you can follow everything I've changed from the comments, but feel free to ask.
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
#only calculate params after all numbers are entered (outside for loop)
s = [max(nr), min(nr), nr, sum(nr)/len(nr)]
while 1: #loop forever until user chooses "terminate this program"
#print options in a nicely formatted way
#triple quoted string allows newlines within literal definition (multiline strings)
print("""What would you like to do?:
1. Show me the biggest integer.
2. Show me the smallest integer.
3. Show me the average of all numbers combined with one decimal.
4. Show me all the entered integers.
5. Terminate this program.""")
#we don't specifically need an integer if we're just picking a choice from a list of options
z = input("input: ")
if z == "1": #choices are now strings so be sure to quote them
print(s[0]) #be sure to select proper element from our list 's'
elif z == "2":
print(s[1])
elif z == "3":
print(s[3])
elif z == "4":
print(s[2])
elif z == "5": #now that we are in a separate loop, break will bring us out of it
break
else:
print("Please select a number between 1 to 5.")
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
while True:
s = [max(nr), min(nr), sum(nr)/len(nr), nr]
z = int((input("What would you like to do? Please enter a number between 1 to 4.\n1> Max Value\n2> Min Value\n3> Average\n4> Show All\n5> Terminate\n")))
if (z-1) in range(0,4):
print(s[z-1])
elif z == 5:
break
else:
print("Please select a number between 1 to 4.")
Here is the working version. I will explain each change to get you started on programming Python.
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
s = [max(nr), min(nr), sum(nr)/len(nr), nr]
z = 0
while not 1 <= z <= 5:
z = int((input("What would you like to do? (1) Max ; (2) Min; (3) Avg; (4) All; (5) None. ")))
if z != 5:
print(s[z-1])
Here are the changes I made:
As I originally said in the comments, we shift everything from the s = line to the left, to get it out of the input loop. Remember indentation is syntactically significant.
We swap the 3rd and 4th elements in your s array to conform to the description you had (option 3 is the average, option 4 prints the array)
We set up a while loop to keep asking for a legal option input (1 thru 5). Notice how in Python, you can do things like 1 <= z <= 5. This more natural notation is not something you find in many languages. Notice also how we had to set z = 0. We could have set z = 6 or z = 99 or whatever - basically, any value not between 1 and 5. Without that, z is initialized to the special Python value None - the null value that is nowhere in the set of integers, and will thus fail the 1 <= z <= 5 test.
We modify the message printed to the user just make the options clear
Last but not least, rather than having all the if statements, we take advantage of the fact that the option number is the same as the index in the array of calculations we did. Well, almost the same, except that arrays in Python start at index 0. So, we subtract one from the option number, and that indexes right to the place in the array holding the desired calculation. The only exception is option 5, which is meant to do nothing. So, we still have just one if statement, which tests for that option 5.

Basic Python If Statements Using "or"

I am following a beginner program for learning python. I am struggling to find a better way to use an "if" statement with multiple possibilities. I am writing a basic text based game in which the user is able to choose three different difficulty levels: Easy, Medium, Hard. I am just trying to write code that takes in a 1, 2, or 3 to tell the program which level to run. I want to make sure the user input is one of those options, not "4" or "one".
Here is the relevant code I have written:
selected_level = 0
selected_level = raw_input("\n Please select a level by entering 1, 2, or 3 : ")
print selected_level
if selected_level == 1 or selected_level == 2 or selected_level == 3:
print "Pass"
else:
print "Fail"
break
All I am trying to do right now is test that the "if" statement works. However, no matter what input I enter it will print the input and then print "Fail" which tells me it is never entering the first part of the "if" statement.
I have tried testing this with inputs 1, 2, 3, 4, one, etc and it always skips to the "else" statement. Is there a better way to write an "if" statement with multiple or values?
Your issue is that raw_input returns a string, but the if-statement is comparing to ints.
"1" does not equal 1.
Try checking if selected_level == "1" ... "2"... etc. and it should work.
I would compare to strings instead of casting the input to an int, as that will crash the program if the user types something unexpected.
Also for a more succinct check:
if selected_level in ("1", "2", "3"):
print "Pass"
raw_input returns a string. Try int(raw_input(...))
The reason it keeps skipping down to the if statement is because it is comparing the string that you entered to the numbers 1, 2, etc and not to the string value of 1 and 2. If you want to take the numeric value of the input you could do something like:
selected_level = int(raw_input("\n Please select a level by entering 1, 2, or 3 : "))
This will take the integer value of whatever the user inputs.
raw_input (in Python 2.x) returns a str. so selected_level is a str, not int. You must parse it to int before compare it woth int values
selected_level = 0
selected_level = int(input("\n Please select a level by entering 1, 2, or 3 : "))
print selected_level
if selected_level == 1 or selected_level == 2 or selected_level == 3:
print "Pass"
else:
print "Fail"
break

How do i do a Does not equal multiple numbers?

i'm using python 3.2.3 idle
here's my code:
number = input("please enter 1 or 2")
if number != 1 or 2: #this part is wrong
print("You didn't enter 1 or 2")
my code is incorrect. i want to make it so that if the user doesn't enter 1 or 2, error pops up. say they enter 1.5, 3, etc or something that isn't 1.0 or 2.0.
how do i do that using the != command?
The problem is that the code is parsed as
if ((number != 1) or 2):
and 2, being nonzero, is always True.
Instead I would suggest
if number not in (1, 2):
You can always use in/not in:
if number not in (1,2):
Don't forget to create an integer out of your number as well...
number = int(input("please enter 1 or 2"))
Your code as is will never give a True result since you're comparing strings to integers (which will always be inequal).
You can try this:
if number!=1 and number!=2

Categories

Resources