How can i search variables using input in this code? in python - python

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 ==

Related

Verifying if user input is in multiple zero values

How can we check if a user enters the value 0 multiple times in a row?
I have tried below code- here I have tried to define multiple value in list, but if the user enters 000000000 or more, I have to define till 000000000 in list is there any other way to achieve this
list = [0,00,000,0000]
num = int(input("Enter a number: "))
if num in list:
print("Zero")
elif :
print(" None ")
You need to take the input as a string. And you can check if the user has entered a string that will have all zeros in it as follows
def all_zeros(string):
return all(ch == '0' for ch in string)
This worked for me
num = input("Enter: ")
if num.count('0') > 0 and num.startswith('0'):
print("0")
else:
print("none")
Since you asked in this way
How can we check if a user enters the value 0 multiple times in a row?
But, other answers were checking whether more than one 0's are present in the string or not. I assume you want to check continuous zero's only,
num = input("Enter Number: ") # returns string
if "00" in num: #checking substring
print("Found continuous zeros")
else:
print("Entered no continous zeros!")
value = int(num) # convert it to int if needed
It doesn't matter how many zeros in the string, all these [00,000,0000,00000...] belong to the same category.
Output:
>>> num = input("Enter Number: ")
Enter Number: 0008
>>> num
'0008'
>>> "00" in num
True
>>>
num = input("Enter: ")
if num.count("0") > 1 and int(num) == 0:
print("0")
else:
print("none")
don't change num to int it will remove all the trailing zeroes

checking next and previous indexes

I'm trying to go through each index and check if it's greater than the next index or not, but I could not come up with any idea about how to do it. I tried using range and enumerate functions, but did not work so help would be much appreciated. This is my current code:
user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
test = []
for the_index, the_item in enumerate(arrayList):
Here is what I tried earlier than this
user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
first_numbers = []
second_numbers = []
finalList = []
for i in arrayList:
the_index = arrayList.index(i)
if the_index % 2 != 0:
first_numbers.append(i)
if the_index % 2 == 0:
second_numbers.append(i)
first_numbers.append(second_numbers)
Not sure i got this clear but if you want to know if user's input was bigger / smaller than the previous choice, you can do this:
This may not be the shortest way to do it, but this is a dynamic snippet where you can decide ask as much as inputs you want the user to answer:
user_choice = input('Choose some numbers: ')
user_choice_listed = user_choice.split(',')
marked_choice = None # Uninitialized integer that would be assigned in the future
for t in user_choice_listed:
converted_t = int(t)
if marked_choice != None and marked_choice < converted_t:
print('{0} is Bigger than your previous choice, it was {1}'.format(t,marked_choice))
elif marked_choice != None and marked_choice > converted_t:
print('{0} is Smaller than your previous choice, it was {1}'.format(t,marked_choice))
elif marked_choice == None:
print('This is your first Choice, nothing to compare with!')
marked_choice = converted_t # this is marking the previous answer of the user
NOTE: You can add a line to handle where the previous is equal to the current choice.
OUTPUT:
Choose some numbers: 1,3,5 # My Input
This is your first Choice, nothing to compare with!
3 is Bigger than your previous choice, it was 1
5 is Bigger than your previous choice, it was 3
Loop it through the indexes?
for i in range(len(arrayList)):
if arrayList[i] > arrayList[i + 1]:
//enter code here

Eventhough i have defined a function inside my code, still it's showing "Nameerror: not defined" in PYTHON

t=int(input("enter no of test cases"))
global mylist1,mylist2
for a in range(t):
n = int(input("number of cubes"))
while True:
list_inp = input("enter list").split()
if len(list_inp)== n:
break
print("no of list items is not equal to specified length.")
mylist=[int(x) for x in list_inp]
x = min(mylist)
y = mylist.index(x)
mylist1 = mylist[0:x]
mylist2 = mylist[x:]
if isascend(mylist2) and isdescend(mylist1):
print('yes')
else:
print('no')
def isdescend(mylist1):
previous = mylist1[0]
for number in mylist1:
if number > previous:
return False
previous = number
return True
def isascend(mylist2):
previous = mylist2[0]
for number in mylist2:
if number < previous:
return False
previous = number
return True
In the if block isascend and is descend are not defined showing "unresolved reference" but why??
Why the function cannot be called?Is there some kind of order followed for defining a function in python.
how can i resolve this?? I'm new to programming &symbol table concept.
You need to define the functions before the code that uses them.

Python function using appends with lists not very efficient

Trying to write a function which takes input of 4 digit numbers and compares them, output of Ys and Ns to try and check if they are the same. EG 1234 and 1235 would output YYYN. At the minute it's very inefficient to keep using all these append commands. How could I simplify that?
def func():
results=[]
firstn= str(input("Please enter a 4 digit number: "))
secondn= str(input("Please enter a 4 digit number: "))
listone= list(firstn)
listtwo= list(secondn)
if listone[0]==listtwo[0]:
results.append("Y")
else:
results.append("N")
if listone[1]==listtwo[1]:
results.append("Y")
else:
results.append("N")
if listone[2]==listtwo[2]:
results.append("Y")
else:
results.append("N")
if listone[3]==listtwo[3]:
results.append("Y")
else:
results.append("N")
print(results)
Furthermore, how can I validate this to just 4 digits for length and type IE. Nothing more or less than a length of four / only numerical input? I have been researching into the len function but don't know how I can apply this to validate the input itself?
For the validation, you can write a function that will ask repeatedly for a number until it gets one that has len 4 and is all digits (using the isdigit() string method).
The actual comparison can be done in one line using a list comprehension.
def get_number(digits):
while True:
a = input('Please enter a {} digit number: '.format(digits))
if len(a) == digits and a.isdigit():
return a
print('That was not a {} digit number. Please try again.'.format(digits))
def compare_numbers(a, b):
return ['Y' if digit_a == digit_b else 'N' for digit_a, digit_b in zip(a, b)]
first = get_number(4)
second = get_number(4)
print(compare_numbers(first, second))
I think this should work.
def compare(a,b):
a,b = str(a),str(b)
truthvalue = {True:"Y",False:"N"}
return "".join([truthvalue[a[idx]==b[idx]] for idx,digit in enumerate(a)])
print(compare(311,321)) #Returns YNY
print(compare(321312,725322)) #Returns NYNYNY
def two_fourDigits():
results = []
firstn = input("Please enter the first 4 digit number: ")
while firstn.isnumeric() == False and len(firstn) != 4:
firstn= input("Please enter the second 4 digit number: ")
secondn = input("Please enter a 4 digit number: ")
while secondn.isnumeric() == False and len(secondn) != 4:
secondn= input("Please enter a 4 digit number: ")
for i in range(0, len(firstn)):
if firstn[i] == secondn[i]:
results.append("Y")
else:
results.append("N")
print(results)
You don't need to convert the input to a string, the input() function automatically takes in the values as a string.
Second, I added in input validation for firstn and secondn to check that they were numeric, and to check if they are the correct length (4). Also, there is no need to change the input to a list, because you can search through the strings.
I tried to do your function like this. Basically, the function uses the length of the first string to iterate through all the values of each list, and return Y if they are the same and N if they are not.
Because you don't make it a global variable which can be used from out of the function. Here is an example:
my_list = []
def my_func():
global my_list
my_list.append(0)
return "Something..."
my_list.append(1)
print my_list

Struggling with 'for' statement in Python

I have to write a program using Python, which should ask the user to enter integer numbers to compose a list of numbers. Then I have to check whether at least one number in this list is 3 digits long. How can I do that? I should use 'for' statement. I started this way:
numbers_list = []
while True:
try:
n = int(input("Enter an integer (press ENTER to end the program): "))
except ValueError:
break
else: numbers_list.append(n)
And then I tried to do this way, but it didn`t work:
num = False
for num in numbers:
if len(num) == 3:
num = True
break
print(num)
The answer should be: E.g. input = [1, 101, 2000], then output would be True; if input = [1,2,3], then output would be False
Use any function to return a bool value if any one element in the given list satisfies a particular condition.
numbers_list = []
while True:
try:
n = int(input("Enter an integer (press ENTER to end the program): "))
except ValueError:
break
else: numbers_list.append(n)
print(any(len(str(i))>2 for i in numbers_list))
It returns true if any one element in the list has the length greater than 2.
To return true if an element has exact three digits, then change the above any statement to,
print(any(len(str(i))==3 for i in numbers_list))

Categories

Resources