How to test if var is not either of two strings? - python

I've stumbled upon a problem I can't explain.
chosen = input()
if chosen == "1" or chosen == "2":
print("Okay")
else:
print("Please choose between 1 or 2.")
If written like that it executes as intended, but the flow felt weird, so I want to continue with else, so I changed the statement to !=
chosen = input()
if chosen != "1" or chosen != "2":
print("Please choose between 1 or 2.")
else:
print("Okay")
That way (to me) it feels natural to continue the code, but now no input returns "Okay".

Ideally, you'd use in for this, which reads much cleaner
while True:
chosen = input()
if chosen in ["1", "2"]:
print("Okay")
break
else:
print("Please choose between 1 or 2.")

You need to use the and keyword instead of or,
by using or this makes it so that if you answer 1 then it will not print "Okay" due to the fact that it is not 2 which makes the function true, and vice versa for the input equaling 2.
This should work:
chosen = input()
if chosen != "1" and chosen != "2":
print("Please choose between 1 or 2.")
else:
print("Okay")
Note you may benefit from changing the numbers into integers by doing this:
chosen = int(input())
if chosen != 1 and chosen != 2:
print("Please choose between 1 or 2.")
else:
print("Okay")
The int function makes your input into a number, however it will give an error if the user doesn't put in a number.

Related

Trying to get my code to input only digit values and if it inputs a non digit value it prints You have input a non digit value but its not working

it seems to only recognise decimals as non digit value but if i wear to write a word it would say could not convert string to float-How do i fix this im new to programming
Try this
selection=input("Select a menu- Input a number:")
if not selection.isdigit():
print("You have input a non digit value. Select again:")
else:
selection = float(selection)
if selection==1:
print("::menu 1::")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
exit
elif selection<=0 or selection>4:
print("There is no menu",end=" ")
print(selection)
I've made a few changes to your code and added a few comments inline
# We start with None so that it enters the loop at least once
selection = None
# We create loop to keep asking the question until the user provides a number
while not selection:
selection=input("Select a menu- Input a number:")
# Check if the number is a decimal
if selection.isdecimal():
# I convert to an int since it's more natural
selection = int(selection)
# At this point, it will exit the loop
else:
# The user has intereed an incorrect value.
print("You have input a non integer value. Select again:")
# We empty selection so that it loops and asks the question again
selection = None
# Here we have an int
# If the selection is 1, 2 or 3, we display the menu. I use a list,
# but range(1, 3) would have worked too
if selection in [1, 2, 3]:
# Note I use an f-string here. You might not have learned about
# them yet. Requires at least Python 3.6
# This helps avoid repetition
print(f"::menu {selection}::")
elif selection==4:
# always call it like a function
exit()
else:
# Any other selection (remember, we know we have an int) should get this message
print(f"There is no menu {selection}")
Try this:
while True:
selection=input("Select a menu- Input a number:")
if not selection.isdigit():
print("You have input a non digit value. Select again:")
else:
selection = int(selection)
if selection==1:
print("::menu 1::")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
print('Exiting...')
quit()
else:
print("There is no menu",end=" ")
print(selection)

How to convert Celsius to Fahrenheit and vice-versa in python

I'm trying to create a program that will convert Celsius to Fahrenheit and vice-versa.
The first thing the program will do is ask the user what the user wants to convert either Celsius or Fahrenheit. If the input is invalid, print invalid and ask to try again.
Then will ask the user to input the start, end, and interval separated by an asterisk. For example 0102. This means that the start of the conversion will be from 0 to 10 with an interval of 2, thus the value to be converted will be 0, 3, 6, 9
If the start<end, then the interval should be 0<interval otherwise, your program will display an error and ask to try again
Or
If the start>end, then the interval should be 0>interval otherwise, your program will display an error and ask to try again.
If the user inputs has only one value, like 10. This means that the start is equal to 1 which will be the default value for start, up to 10, and the interval is 2 which will be the default value of the interval if start<end.
If the user input has two values like 10*2, this means that the start is equal to 10 up to 2. The interval is set to the default value which is equal to -2 since start>end.
This is my code, it doesn't work and I'm stuck.
And how am I gonna use for loop here?
while True:
pick = input("Enter your input either in Celsius or Fahrenheit: ")
if pick == "Celsius":
pass
elif pick == "Fahrenheit":
pass
else:
print("Invalid input. Try again.")
continue
while True:
sei = input("Enter the start, range, and interval separated by an asterisk(*): ").split("*")
if len(sei) == 3:
if int(sei[0].isdigit()) < int(sei[1].isdigit()) and 0 < int(sei[2].isdigit()):
pass
elif int(sei[0].isdigit()) > int(sei[1].isdigit()) and 0 > int(sei[2].isdigit()):
pass
else:
print("Error. Try again.")
continue
else:
print("Error. Try again")
Input :0 * 100 * 3
Output:
!
Then the program will ask the user to try again. If yes, the program will run from the very start.
If no, it'll print "Thank you" and the number of invalid inputs in the whole program and the number of times the user successfully converts temperature.
Here is my solution (inefficient maybe, I'm a beginner too) to your problem.
temperatureValues = []
while True:
pick = input("Enter your input either in Celsius or Fahrenheit: ")
if pick == "Celsius":
pass
elif pick == "Fahrenheit":
pass
else:
print("Invalid input. Try again.")
continue
while True:
sei = input("Enter the start, range, and interval separated by an asterisk(*): ").split("*")
if len(sei) == 3:
if int(sei[0]) < int(sei[1]) and 0 < int(sei[2]): # normal case
for i in range(int(sei[0]), int(sei[1]), int(sei[2])):
temperatureValues.append(i)
break
elif int(sei[0]) > int(sei[1]) and 0 > int(sei[2]): # reverse case
for i in range(int(sei[1]), int(sei[0]), int(sei[2])):
temperatureValues.append(i)
break
else:
print("Error. Try again.")
continue
elif len(sei) == 2:
for i in range(int(sei[0]), int(sei[1]), 2):
temperatureValues.append(i)
break
elif len(sei) == 1:
for i in range(1, int(sei[0]), 2):
temperatureValues.append(i)
break
else:
print("Error. Try Again.")
continue
print(temperatureValues)
# Implement your conversion here, by performing the conversion operation on each value of the temperatureValues list.
I would also advise you to do comparison in values by writing the variable first. Like int(sei[0]) > 0, instead of writing this in reverse. Makes the code more readable.
Best of luck!

Not being able to make an integer greater than another one

I'm making a program that gives you different basic operations to solve.
If you choose subtraction, it also gives you a choice if negative numbers are allowed or not. If the user says "No", it's supposed to change the variable that determines the minuend to a different number and check if it's greater than the subtrahend, and if it isn't, it tries again.
I've tried using a while loop that keeps regenerating the minuend until it's greater than the subtrahend, I've tried placing after FAT1 (minuend) = random.randint(1,50) > FAT2 (subtrahend) or FAT1 = random.randint(1,50 > FAT2).
I've also tried placing it in a function, or making a boolean used in the while loop instead of FAT1 < FAT2, but it keeps not working.
Variables I made throughout (all global):
FAT1 = first number (int)
FAT2 = second number (int)
OPER = the operation the user chooses (string)
NEG = if the user chooses yes or no to negative numbers (string)
Problematic part of the code:
#No negative numbers
elif NEG == "NO" or "No" or "no" or "nO" :
while True :
FAT1 = random.randint(1,50)
FAT2 = random.randint(1,50)
#Here it takes what the user typed and converts it in an int
TYP = input()
NUM = int(TYP)
while FAT1 < FAT2 :
FAT1 = random.randint(1,50)
RES = FAT1 - FAT2
print("What's",FAT1," - ",FAT2)
if NUM == RES :
print("Correct!")
elif NUM != RES :
print("Wrong! Try again!")
EDIT: As I said in my comment:
I get the input before the problem gets made because the user may choose a different operation. This question could be clearer with the whole code, but i didn't feel like putting it all there because it felt redundant Here's the code: pastebin.com/ZfqhY2md
EDIT2: I tried making this dictionary at the beginning (all in one line):
dict = {'Addition': 'Addition', 'Subtraction': 'Subtraction', 'No': 'No',
'Yes': 'Yes'}
And at the beginning of every if statement i tried this:
if NEG == dict.get('Yes') :
And it works for every suite except the one with No to negative numbers...
New full code here:
https://pastebin.com/600TpkZe
I think the problem may be in your elif condition.
Checking: NEG == "NO" or "No" or "no" or "nO" is going to return True if, and only if, NEG = 'NO'
rather try:
elif NEG.upper() == 'NO':
I found out this is a duplicate...
I made a tuple for any No you might type and check with:
(Notup is the list of NOs)
if OPER in Notup :
Then I made tuples for everything else.

How to cleanly ask user for input and allow several types?

So this is a prompt for user input, and it works just fine. I was printing some names and associated (1 based) numbers to the console for the user to choose one. I am also giving the option to quit by entering q.
The condition for the number to be valid is a) it is a number and b) it is smaller or equal than the number of names and greater than 0.
while True:
number = str(input("Enter number, or q to quit. \n"))
if number == "q":
sys.exit()
try:
number = int(number)
except:
continue
if number <= len(list_of_names) and number > 0:
name = list_of_names[number-1]
break
There is no problem with this code, except I find it hard to read, and not very beautiful. Since I am new to python I would like to ask you guys, how would you code this prompt more cleanly? To be more specific: How do I ask the user for input that can be either a string, or an integer?
A bit simpler:
while True:
choice = str(input("Enter number, or q to quit. \n"))
if choice.lower() == "q":
sys.exit()
elif choice.isdigit() and (0 < int(choice) <= len(list_of_names)):
name = list_of_names[int(choice)-1]
break
Just downcase it.
number = str(input("Enter number, or q to quit. \n"))
number = number.lower()
That will make the q lower case so it doesn't matter if they press it with shift if they press something else just make a if statement that sets a while loop true.

Returning to menu after command? Python

I know all my questions are really easy but I'm a beginner so here it is...
I have been developing the guessing number thing after everyones help, but I want to then return to a menu which has just been left. Here's the code:
import time
import random
animalmenu()
def animalmenu():
print()
print()
print()
print()
print('Welcome to the menu. I am thinking of a menu. Select the option\'s below to try and guess my animal.')
print()
print('a) No. of Legs')
print('b) Type of animal')
print('c) Preffered Climate')
print('d) Size')
print('e) Colour')
print('f) Diet')
print('g) Habitat')
print('h) Can be kept as pet')
print('i) Guess animal')
print()
print('When in a menu, type in \'555\' to return here')
AniChoice = input('Choose your option: ')
if AniChoice == 'a':
loop = 10
while loop == 10:
print()
print('')
print()
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
print('r = Return to menu, g = guess again.')
rg = input()
if rg == 'g':
print('Loading...')
elif rg == 'r':
loop = 0
time.sleep(1)
print('Returning to menu...')
time.sleep(1)
animalmenu()
everytime I run it, I type in a number as the code asks but then, instead of asking if I want to return to the menu it just asks the question again and again, 'Guess the number of legs: '. I know this is something to do with my looping method but I do not understand and because of the integer setting I cannot just make another if, like so:
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
elif guessleg == 'back':
loop = 0
animalmenu()
And I do not see any other way of doing it as neither way seems to work? How would you suggest returning to animalmenu()?
As the message is telling you, 'back' is not an integer, but you are comparing it to a variable into which you have put an integer value. Specifically, your line:
guessleg = int(input('Guess the number of legs: '))
puts an integer value into guessleg (or more properly tries to) from the user's input.
One approach to resolve this is to capture the user's input in a string variable, compare that string to 'back' first, and then convert to an integer if needed.
Another approach is to wrap a try/except around the integer conversion and proceed with the integer check if the conversion is successful and with the check against 'back' if the exception is encountered. This is probably preferred these days and I've put it into code:
inp_val = raw_input('Guess the number of legs: ')
try:
guess_num = int(inp_val)
if guess_num == leg:
print('True')
else:
print('False')
except ValueError:
if inp_val == 'back':
loop = 0
else:
print 'Invalid entry'
animalmenu()
because the you convert your input into integer and store it into guessleg which means guessleg is also an integer. However, 'back' is a string. You can't compare the string with integer. the 3 == 'back'means nothing.
and syntax error may because of your indent.
UPDATE:
if you want to return to the top menu, you can do something like:
def animalmenu():
while True:
print your menu here
and do something....
while ...:
get input and do something...
if get the input of 'back to menu':
break
UPDATE again:
I don't think you shall use input() here, try readline() or raw_input() instead.

Categories