i want to search variable using input .
found = False
number = [1,2,3,4,5,6,7,8,9,]
for value in number :
if value == 3 :
found = True
print(found)
If you want to get a value using input() and check if the value is in a list, you can do it like this:
value = int(input())
found = False
number = [1,2,3,4,5,6,7,8,9,]
result = value in number
print(result)
You can do something like:
value = int(input("Insert a value: "))
found = False
number = [1,2,3,4,5,6,7,8,9]
for i in number:
if i == value :
found = True
break
print(found)
The method used by #SangkeunPark is more efficient, but it can be done with your program with a simple change:
found = False
a = int(input())
number = [1,2,3,4,5,6,7,8,9,]
for value in number :
if value == a :
found = True
print(found)
n=int(input('Enter a value:'))
number = [1,2,3,4,5,6,7,8,9]
if n in number:
print(True)
else:
print(False)
Alright so first we are going to make the variables (just like you had in your code)
found = False
number = [1,2,3,4,5,6,7,8,9]
now we will add an input command and store the respective value in variable called 'value'
value = int(input("Enter your number: "))
Now to check if the user's value is in our list or not, we are going to iterate through the list and in every iteration we will check if the value user entered appears to be in the list, if it does we will just set the 'found' variable to True
for values in number:
if values == value :
found = True
break
if found:
print("number found")
else:
print("number not found")
Now here you can use both "in" and "=="
but since we are just checking the numbers in this particular piece of code, == is fine!
check out this
for more info about in and ==
I want to check if the input is a number(float with 0,one or two decimals) and greater than 0
def getnumber():
print ( "write a number: \n")
isValid = False
while not isValid:
try:
number = float(raw_input().replace(",","."))
if number >= 0:
isValid=True
else:
print ("Number not valid")
isValid = False
getnumber()
except:
print ("Number not valid")
return number
I have the following problems:
1- I don't know how to check if there are only two decimals
2- The code doesn't return the number if first I introduce a negative number
Does anyone know how to fix it?
Thanks a lot
The reason why your code isn't working with negative numbers is because the function calls itself recursively when the number is negative, but the value of isValid is always false after that call, so the loop repeats.
There isn't really any need for the Boolean variable.
That leaves you with the issue of detecting two decimal places. In order to be able to do that at string level you would have to retain the string that you converted to a floating-point number. Supposing you store it as s you could use some test like len(s) > 3 and s[-3] == '.'` to verify it.
This would give you a solution like:
def getnumber():
while True:
try:
s = raw_input("Write a number:").replace(",",".")
number = float(s)
if number >= 0 and len(s) > 3 and s[-3] ==".":
return number
else:
print("Negative or not two decimal places")
except Exception:
print("Invalid number")
print(getnumber())
I want the user to input a number
Give a number : he types "10" -but...
Give a number : he types "I want to type 10"
i want the program to just "count" the integer. Because if he types a string the program will stop
import random
goal = random.randrange(1,10)
n = 1
tries = 0
name = input("Dose to onoma sou ")
print("A game in Python")
while n != 0 :
value = int(input("madepse poio einai to noumero:"))
n = abs(value - goal)
print(value,n)
tries = tries + 1
if n >= 4 :
print("den eisai koda")
elif n > 0 and n <= 3 :
print("eisai koda")
else :
print("to vrikes")
print ("to score sou einai: ",tries)
skoros = str(tries)
score = open('score.txt', 'a')
score.write(name)
score.write(' ')
score.write(skoros)
score.write("\n")
score.close
This will take any input and pull the first number out of it. \d matches any digit 0-9, and + means "one or more".
import re
while True:
user = input('Enter a number: ')
match = re.search(r'\d+',user)
if match:
value = int(match.group(0))
break
else:
print("I didn't see a number in that response.")
print(value)
Well, you could just manually loop through the string and store the position of the number using isdigit().
The following approach expects the number to be the only one in the string (multi digit allowed):
start = None
stop = None
for i in range(len(input)):
c = input[i]
if c.isdigit():
if start == None:
start = i
stop = i
try:
number = int(input[start:stop])
catch:
print("invalid input")
EDIT:
I guess there would be some nice and easy Regex solution, but I'll leave my hands off of it, as I am not too experienced with it...
I tried of making and Celcius to Faharanite converter and visa-versa.
I made extra if-else ladder to ensure that the user doesn't get stuck and when the user enters something wrong.
But i tried compiling this after the first statement gets terminated.
ch = raw_input("""What you want to convert :
1) Celcius to Faharanite.
2) Faharanite to Celcius.\n""")
if (type(ch)==int):
if (ch==1):
cel=raw_input("Enter to temperature in Celeius : ")
if (type(cel)!='float'):
cel = 1.8*(cel+32)
print "The Conversion is :" + cel
else :
print "YOu should enter values in numeric form"
elif (ch==2):
fara=raw_input("Enter to temperature in Faharanite : ")
if (type(fara)==float):
print "The Conversion is :" + 1.8*(fara-32)
else :
print "YOu should enter values in numeric form"
else :
print "Wrong choice"
Because the first if statement is never true. The result of raw_input is always a string.
devnull's comment suggesting adding ch = int(ch) will work as long as the user input is a number.
For more robust handling, I would do something like:
is_valid = False
while not is_valid:
ch = raw_input("""What you want to convert :
1) Celsius to Fahrenheit.
2) Fahrenheit to Celsius.\n""")
try:
ch = int(ch) # Throws exception if ch cannot be converted to int
if ch in [1, 2]: # ch is an int; is it one we want?
is_valid = True # Don't need to repeat the while-loop
except: # Could not convert ch to int
print "Invalid response."
# The rest of your program...
which will continue to to prompt the user until they enter a valid choice.
Note that you'll have to use a similar try/except construct to parse the temperature-to-convert into a float (with the float() method).
Hi I am having trouble with the end of my loop. I need to accept the input as a string to get the "stop" or the "" but I don't need any other string inputs. Inputs are converted to float and then added to a list but if the user types "bob" I get the conversion error, and I cant set the input(float) because then I can't accept "stop".
Full current code is below.
My current thinking is as follows:
check for "stop, ""
check if the input is a float.
if its not 1 or 2, then ask for a valid input.
Any ideas please? If its something simple just point me in the direction and i'll try churn it out. Otherwise...
Thanks
# Write a progam that accepts an unlimited number of input as integers or floating point.
# The input ends either with a blank line or the word "stop".
mylist = []
g = 0
total = 0
avg = 0
def calc():
total = sum(mylist);
avg = total / len(mylist);
print("\n");
print ("Original list input: " + str(mylist))
print ("Ascending list: " + str(sorted(mylist)))
print ("Number of items in list: " + str(len(mylist)))
print ("Total: " + str(total))
print ("Average: " + str(avg))
while g != "stop":
g = input()
g = g.strip() # Strip extra spaces from input.
g = g.lower() # Change input to lowercase to handle string exceptions.
if g == ("stop") or g == (""):
print ("You typed stop or pressed enter") # note for testing
calc() # call calculations function here
break
# isolate any other inputs below here ????? ---------------------------------------------
while g != float(input()):
print ("not a valid input")
mylist.append(float(g))
I think the pythonic way would be something like:
def calc(mylist): # note the argument
total = sum(mylist)
avg = total / len(mylist) # no need for semicolons
print('\n', "Original list input:", mylist)
print("Ascending list:", sorted(mylist))
print ("Number of items in list:", len(mylist))
print ("Total:", total)
print ("Average:", avg)
mylist = []
while True:
inp = input()
try:
mylist.append(float(inp))
except ValueError:
if inp in {'', 'stop'}:
calc(mylist)
print('Quitting.')
break
else:
print('Invalid input.')