How do I get a specific input in python such as
variable = input()
if variable == "Specific input":
do stuff
I need the input to be one of two options say X
or O
How do I get a specific input in python such as
variable = input()
if variable == "Specific input":
do stuff
I need the input to be one of two options say X
or O
Its Simple Example to use specific Variable: This is Simple Code For Converting Between Inch-to-Cm OR Cm-to-Inch:
conv = input("Please Type cm or inch?")
if conv == "cm" :
number = int(input("Please Type Your number: "))
inch = number*0.39370
print(inch)
elif conv == "inch":
number = int(input("Please Type Your Number?"))
cm = number/0.39370
print(cm)
else:
print("Wrong Turn!!")
Define a list
specific_input = [0, 'x']
and so
if variable in specific_input:
do awesome_stuff
I understand the question more on looping for relevant input (as @SvbZ3r0 has pointed out in comment). For a very beginner in Python it may be hard to even copy code from tutorials, so:
#! /usr/bin/env python
from __future__ import print_function
# HACK A DID ACK to run unchanged under Python v2 and v3+:
from platform import python_version_tuple as p_v_t
__py_version_3_plus = False if int(p_v_t()[0]) < 3 else True
v23_input = input if __py_version_3_plus else raw_input
valid_ins = ('yes', 'no')
prompt = "One of ({0})> ".format(', '.join(valid_ins))
got = None
try:
while True:
got = v23_input(prompt).strip()
if got in valid_ins:
break
else:
got = None
except KeyboardInterrupt:
print()
if got is not None:
print("Received {0}".format(got))
Should work on either python v2 and v3 unchanged (there was no indication in question and input() in Python v2 might not be a good idea ...
Running the above code in Python 3.5.1:
$ python3 so_x_input_loop.py
One of (yes, no)> why
One of (yes, no)> yes
Received yes
Breaking out via Control-C:
$ python3 so_x_input_loop.py
One of (yes, no)> ^C
When it is clear, on which version to run, say python v3, than the code could be as simple as:
#! /usr/bin/env python
valid_ins = ('yes', 'no')
prompt = "One of ({0})> ".format(', '.join(valid_ins))
got = None
try:
while True:
got = input(prompt).strip()
if got in valid_ins:
break
else:
got = None
except KeyboardInterrupt:
print()
if got is not None:
print("Received {0}".format(got))
The simplest solution would be:
variable = input("Enter x or y")
acceptedVals = ['x','y']
if variable in acceptedVals:
do stuff
Or if you want to keep prompting the user for the right use a while loop
variable = None
acceptedVals = ['x','y']
while variable not in acceptedVals
variable = input("Enter x or y")
do stuff