Python given number exists in list or not - python

a = [1,2,3,4,5,6]
print(a)
s=input("Enter a number from the list given \n")
if s in a:
print("the number given is", s)
else:
print("please select the number given in the list")
When I give 2 as input, the if statement is not being checked directly; the else part is printed. But if provide the value hardcoded in the program, the code is working as expected.
If my input is any number from the list, it should print that number. If not, the other part should be printed.

s=int(input("Enter a number from the list given \n"))
I believe

You are taking string as an input and not int. Try using
s = int(input("Some value")

You can change your if condition like this:
a = [1,2,3,4,5,6]
print(a)
s = input("Enter a number from the list given: ")
if s in set(str(e) for e in a):
print("the number given is", s)
else:
print("please select the number given in the list")
In this way you do not have to convert the user input to int which is fraught with problems if the value(s) entered cannot be converted to int.
An alternative is to use exception handling as follows:
a = [1, 2, 3, 4, 5, 6]
while True:
try:
print(a)
s = int(input("Enter a number from the list given: "))
if s in a:
print("the number given is", s)
break
else:
raise ValueError("please select the number given in the list")
except ValueError as ve:
print(ve)

Related

How to use the same code but with different variables

I want to make a code that allows me to check if the number I have entered is really a number and not a different character. Also, if it is a number, add its string to the list.
Something like this:
numbers = []
num1 = input("Enter the first number: ")
try:
check = int(num1)
numbers.append(num1)
print("The number {} has been added.".format(num1))
except ValueError:
print("Please, enter a number")
I have to do the same for several numbers, but the variables are different, like here:
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Is there any way to create a code that does always the same process, but only changing the variable?
If you are trying to continue adding numbers without copying your code block over and over, try this:
#!/usr/bin/env python3
while len(numbers) < 5: #The five can be changed to any value for however many numbers you want in your list.
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Hopefully this is helpful!
Create the list in a function (returning the list). Call the function with the number of integers required.
def get_ints(n):
result = []
while len(result) < n:
try:
v = int(input('Enter a number: '))
result.append(v)
print(f'Number {v} added')
except ValueError:
print('Integers only please')
return result
Thus, if you want a list of 5 numbers then:
list_of_numbers = get_ints(5)

Data validation for multiple user inputs with Python

I am creating a function for my python course that receives a list and returns the same list without the smallest number. However, I wanted to extend the function to ask the user for inputs to create the list after performing some data validations on the inputs.
I was able to validate the first input. However, I got stuck at the second data validation as I need to guarantee that the program should accept only integers in the list and throw and prompt the user again for every wrong input something like while not (type(number) == int) which breaks as soon as the user input matches an int.
How should I do this?
def smallest():
# This function asks the user for a list
# and returns the same list without the smallest number or numbers
list_range = 'Not a number'
list_created = []
while not (type(list_range) == int):
try:
list_range = int(input('Please enter the total number of elements for your list: '))
except:
print('Please provide a number!')
for number in range(1,list_range + 1):
try:
list_element = int(input('Please enter the value of the %d element: ' %number))
list_created.append(list_element)
except:
print('Please provide a number!')
smallest = min(list_created)
result = []
for num in list_created:
if num != smallest:
result.append(num)
return result
Thanks for the help in advance!
You could use a while loop until an int value is entered:
for number in range(1, list_range + 1):
while True:
list_element = input('Please enter the value of the %d element: ' % number)
try:
list_element = int(list_element)
list_created.append(list_element)
break
except ValueError:
print('Please provide a number!')

Greatest of 3 numbers code not working for specific numbers

I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
if (a > b) and (a > c):
lnum = a
elif (b > a) and (b > c):
lnum = b
else:
lnum = c
print("The largest number is", lnum)
Can anyone help me to understand why the output is showing 20 as greatest instead of 100?
Your variables are strings, you must convert them to ints like this:
a = int(input('Enter 1st value'))
a = input("Enter 1st value") stores string into a you should convert it into integer by using int() method.
a = int(input("Enter 1st value")) or try a= input("Enter 1st value") then a=int(a).
you have to convert your inputs to int:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
print("The largest number is", max(map(int, (a, b, c))))
You could do this easier with max(list) when you store your values in a list. Example:
values = []
values.append(int(input('Enter 1st value ')))
values.append(int(input('Enter 2st value ')))
values.append(int(input('Enter 3st value ')))
lnum = max(values)
print("The largest number is", lnum)
Your inputs are strings and are sorted by comparing the characters left to right.
Comparing "100" against "20" first compares "1" and "2". "1" is smaller so your code picks "20" as the larger value.
As others have mentioned if you convert the input to integer using int(input('Enter 1st value ') then it will work as you intended and there is a max() function you can use.
Note: There still is another mistake in your code:
Enter 1st value20
Enter 2nd value20
Enter 3rd value10
('The largest number is', 10)
The check for (b > a) is wrong and causes you to output c if a == b.

Why doesn't the max() function run as it is expected?

numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(first_input)
while first_input:
input_numb = input("Write next number")
if input_numb == int():
numbers.append(input_numb)
elif input_numb == "done":
print("The largest number is "+max(numbers))
print("The smallest number is "+min(numbers))
break
Can someone look at this code and tell me what I did wrong please? After I put the input numbers I want to print the biggest and smallest number from the list numbers but I don't know why the max function does not return the biggest number, instead it returns the smallest one (just like the min function. Why?
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(int(first_input))
while first_input:
input_numb = input("Write next number")
try:
numbers.append(int(input_numb))
except:
if input_numb == "done":
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
break
else:
print('invalid input!')
out:
Write any number.When you are done just write "done":1
Write next numbera
invalid input!
Write next number2
Write next number3
Write next number6
Write next numberdone
The largest number is 6
The smallest number is 1
int() will return 0:
class int(x, base=10)
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given.If x is a number, return x.__int__(). For floating point numbers, this truncates towards
zero.
In [7]: int() == 0 == False
Out[7]: True
you should use max in a list of number not a list of string, convert string to int before you append it to list
"The largest number is " + max(numbers)
return :
TypeError: Can't convert 'int' object to str implicitly, just use , to concate the string and int.
you should convert your inputs to integers using int(my_input) then add them to the list my_list.append(int(my_input)) and use the max or min functions max(my_list) after getting all the inputs from the user
numbers = []
user_input = input('Write any number.When you are done just write "done": ')
while user_input != "done":
try:
numbers.append(int(user_input))
user_input = input("Write next number : ")
except ValueError:
user_input = input("please enter a valid number : ")
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))

What is wrong in the code?

I am very newbie to programming and stack overflow. I choose python as my first language. Today as I was writing some code to refresh and to improve my skills I wrote a little program. But with complete errors.
Here is the Program
a = [1 , 2, 3]
def list_append():
numbers = int(raw_input("Enter the number please"))
a.append(numbers)
print a
def average(list):
for marks in list:
print marks
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
def loop():
add_numbers = raw_input("Do you want to add another number")
if add_numbers == ("y"):
return list_append()
else:
return average()
while True:
loop()
print average(a)
Basically the function of this program is to ask user for the input of the number. Then append to the list and then show the average which is an easy one.
But I want the program to stop after the first input and ask user if they want to give another input ?
Can't understand where is the problem. ** I am not asking for the direct solution. I would rather want an explanation than the solution itself.**
Following is missing in your code:
Need to break any loop, your while loop in going into infinite loop.
while True:
loop()
2. Handle exception during type casting.
numbers = int(raw_input("Enter the number please"))
Create user enter number list in loop function and pass to list_append function to add numbers.
Also return from the loop function to pass argument into average function.
code:
def list_append(numbers):
while 1:
try:
no = int(raw_input("Enter the number please:"))
numbers.append(no)
break
except ValueError:
print "Enter only number."
return list(numbers)
def average(number_list):
avg = float(sum(number_list))/ len(number_list)
return avg
def loop():
numbers = []
while 1:
add_numbers = raw_input("you want to add number in list(Y):")
if add_numbers.lower()== ("y"):
numbers = list_append(numbers)
else:
return list(numbers)
numbers = loop()
avg = average(numbers)
print "User enter numbers:", numbers
print "average value of all enter numbers:", avg
output:
vivek#vivek:~/Desktop/stackoverflow$ python 17.py
you want to add number in list(Y):y
Enter the number please:10
you want to add number in list(Y):y
Enter the number please:e
Enter only number.
Enter the number please:20
you want to add number in list(Y):Y
Enter the number please:30
you want to add number in list(Y):n
User enter numbers: [10, 20, 30]
average value of all enters numbers: 20.0
vivek#vivek:~/Desktop/stackoverflow$
do not use variable names which are already define by python
e.g. list
>>> list
<type 'list'>
>>> list([1,2,3])
[1, 2, 3]
>>> list = [2]
>>> list([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
a = []
def average(list):
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
while True:
numbers = raw_input("Enter the number please or 'q' to quit : ")
if numbers == "q":
average(a)
break
else:
a.append(int(numbers))
Hope this helps

Categories

Resources