n=input("enter the no:")
check(test_list,n)
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
I had written the simple code to check if a no. exists in a list or not, but while taking user input I"m not getting any results after providing input value n.
Why is so?
In your code the first line should be corrected as n=int(input("enter the no:")).
In python it takes the inputs as strings. Think if you are giving the input as 3. Then the variable n stores the value "3"( not the value 3 ). You should need to know 3 == "3" is False.
Therefore, when you are taking the input you should convert that string input to the int. To do that we use int() method. The int() method converts the specified value into an integer number
n=int(input("enter the no:"))
check(test_list,n)
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
You were not getting any results because the input() function always returns a string. For this reason, we need to convert it to an Integer before passing it on into the function, and I did with n=int(input()).
n=int(input("enter the no:"))
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
check((1,2,3),n)
Related
Trying to understand while loops but after typing in the input a number that is not in the list, it doesn't keep asking until it is one of the numbers in the list.
number = 12
while number not in [0,1,2,3,4]:
number = input("type a number: ")
print(number)
if number in [0,1,2,3,4]:
print('one of those numbers')
else:
break
print('not one of those numbers')
the above gives this if you type 4343:
type a number: 4343
4343
not one of those numbers
If you step through your code you can see that the "number" variable gets what you typed in, 4343. Then you check to see if number is in the list of 0-4. It's not, so execution proceeds down the "else" branch, which is a break. Break will "break" the execution of your loop, so the next thing printed is "not one of those numbers" and execution stops and you are not asked for another input.
If you were to type a number like "4" what would happen? Well, the same thing I think. That's because your input comes in as a string, not a number, and you are asking if the string "4" is in the list of numbers, and it isn't. You need to parse the input as an int, you can do that by wrapping your input call in the "int" function - int(input("Type a number: ")) and now "number" will be an int, not a string.
number = 12
while number not in [0,1,2,3,4]:
number = int(input("type a number: "))
print(number)
if number in [0,1,2,3,4]:
print('one of those numbers')
break
else:
print('not one of those numbers')
continue
As #inteoryx told that when you give an input it's a default string value. You have to convert it to integer and you used break statement if the number not in the list. break gets you out of the loop you should use continue statement instead. I added break in the if statement that will get you out of the loop if the number is in the list.
This is my simple code. When a User enters a value, it has to be compared with the list I have used and should return the output as required. But when I execute the code and enter a value that is a part of the list, it returns the print statement under the else construct. Please help me with your suggestions
mylist=[1,2,3]
print('Enter the Rank:')
x=input()
if x in mylist:
print('You have passed')
else:
print('Sorry you have failed')
The items in mylist are ints. Input returns a string, so to compare them you need to convert one of them.
Either
x = int(input())
or
if int(x) in mylist
Hello I have this issue with a function that I created in python:
def intcheck(num)
if isinstance(num, int):
return num
else:
intcheck(input("Invalid datatype: Input integer only: "))
It's supposed to check if the input is an integer, and if it isn't, ask the user for another input, then check that one, ect. ect.
However the code appears to get stuck on the else: statement such that even a correct input will not return, and it will just ask for another input indefinitely.
A simpler way is:
def is_int(foo):
try:
return int(foo)
except ValueError:
print('{} is not a number'.format(foo))
return is_int(input('Please enter a number: '))
If you are on Python 2, make sure you use raw_input instead of input.
If you're using Python 3.x, input() returns a string, so you have to convert it to an int. If you're using Python 2.x, you really should be using raw_input() instead (Python 2.x input() is very unsafe), and since raw_input() is the same as Python 3.x input(), you also have to convert the string to an int.
In both case, you need to return the result of the recursive call in the else clause as shown in other answers.
Now using recursion this way, while possibly "elegant", is not the simplest solution - a good old while loop works as fine and avoids stacking frames (Python don't do tail-recursion optimisation):
def checkint():
while True:
num = input("your prompt here")
try:
return int(num)
except ValueError:
print "'{}' is not a valid integer".format(num)
You've forgotten that the input function returns a str object! So, you loop forever in the else of the intcheck function. Instead, you could do that:
def intcheck(num):
if isinstance(num, int):
return num
else:
input_string = input("Invalid datatype: Input integer only: ")
try:
input_int = int(input_string)
except ValueError:
input_int = input_string
finally:
intcheck(input_int)
Input in Python is always loaded as a string, so firstly, you need to convert the input into one. Elegant way is to check it with exceptions: if it is int, return it, and if not, ask for another input.
def intcheck(num):
try:
return int(num)
except ValueError:
return intcheck(input("That is not a integer, please enter integer: "))
name="admin"
passw="aaa"
itemone="01"
itemtwo="02"
a=input("Enter your username:")
b=input("Enter your password:")
if(a==name)and(b==passw):
print("Welcome.")
c=int(input("Enter Item Code:"))
if(c==itemone):
print("Name: ID")
elif(c==itemtwo):
print("Name: Mirror")
else:
print("Item not found. Try again.")
else:
print("Username/Password is incorrect.")
exit()
when "01" or "02" is entered, the program ignores all the other codes and directs to "item not found. try again."
I finally got it to work! Thank you!!!
You are taking the input and casting it to an integer, then checking if it is equal to a string. This will return false. Example:
01=="01"
=> False
"01"=="01"
=> True
You don't need to cast the input to an integer.
As robert_x44 said, you are comparing an integer with a string.
Try:
itemone=01
itemtwo=02
Also, in your post the if blocks are not indented. It is probably just a formatting error, but python if statements must be indented.
Either change itemone and itemtwo to ints, or don't convert your input to an int. Right now you're comparing ints to strs, which won't work.
Pick one of the following two changes - don't make both or you'll just reverse the situation you're in now (comparing strs to ints instead of ints to strs.)
How to use just ints
Change:
itemone="01"
itemtwo="02"
to:
itemone=1
itemtwo=2
How to use just strs
Change:
c=int(input("Enter Item Code:"))
to:
c = input("Enter Item Code:")
I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)