I created some code where I try to find elements in a list given by the user using the in operator.
productNums = []
nums = int(input("How many numbers should be in your list?"))
while nums > 0:
productNums.append(input("Add a number: "))
nums -= 1
numFind = int(input("What number are you trying to find? "))
if numFind in productNums:
print("This product number is in the list")
elif numFind not in productNums:
print("Ahh, sorry. This product number is NOT in this list!")
else:
print("Huh, you're confusing me now, check your numbers pal!")
When I run this, I get the outcome that the number is not in this list, even though it is in it. Can someone tell me what I am doing wrong?
As people said above, just small issue with you integers and strings.
This is your code working:
Be careful with the indentention, initially was a mess.
productNums = []
nums = int(input("How many numbers should be in your list?"))
while nums > 0:
productNums.append(int(input("Add a number: ")))
nums -= 1
numFind = int(input("What number are you trying to find? "))
if numFind in productNums:
print("This product number is in the list")
elif numFind not in productNums:
print("Ahh, sorry. This product number is NOT in this list!")
else:
print("Huh, you're confusing me now, check your numbers pal!")
I believe its a missing conversion when u append, its appended as a string and u search for an int
Because the productNums list contains string values, not integer, so you always compare int with str variable and obtain the same result. Set productNums elements to int and it will work properly.
productNums = []
nums = int(input("How many numbers should be in your list?"))
while nums > 0:
productNums.append(int(input("Add a number: ")))
nums -= 1
numFind = int(input("What number are you trying to find? "))
if numFind in productNums:
print("This product number is in the list")
elif numFind not in productNums:
print("Ahh, sorry. This product number is NOT in this list!")
else:
print("Huh, you're confusing me now, check your numbers pal!")
You correctly cast nums and numFind to int, but you didn't do so for the input values in the while loop — so productNums is a list of single-character strings.
This change will fix it:
productNums.append(int(input("Add a number: ")))
The problem is that you are trying to find an int in a list of strings.
When you wrote the code productNums.append(input("Add a number: ")), after the user enters the code, the number would be appended into the productNums list as a string.
Further on, the numFind = int(input("What number are you trying to find? ")) makes the user enter a number. this time, the input is converted into an int. So when the line of code if numFind in productNums: runs, it sees the if as the user trying to find an int in a list of strings.
In short, you should either change the productNums.append(input("Add a number: ")) code into productNums.append(int(input("Add a number: "))), or change the line of code numFind = int(input("What number are you trying to find? ")) into numFind = input("What number are you trying to find? ").
Related
Hope everyone is doing good. I just joined this platform. So, I have just started learning python about a week or so from YouTube. This is my first program please tell me what am I doing wrong here. I want the program to display message if the user input is not in the list and continue asking for another input!
Thank you.
numbers = [7,3,13,6,8,5,1,2,4,15,9,10,12,14,11]
new_list = []
while True:
num = int(input("Enter any number from the list 'numbers': "))
for i in numbers:
if i < num:
new_list.append(i)
new_list.sort()
elif num != i:
print("Number doesn't exist in the list 'numbers'")
break
print(new_list)
This code would do the work:
numbers = [7,3,13,6,8,5,1,2,4,15,9,10,12,14,11]
not_in_list = True
while not_in_list:
number = int(input("Enter any number from the list 'numbers': "))
if number in numbers:
not_in_list = False
the quesion you asked is not exactly what you are trying in your code. I can't undestand the idea behind creating new list. but in general you can use nested functions to write your code and continuously asking user to input data if the previous input is not what you want.
remember in such cases that you are looking for number in a list that contains only numbers, you should control user input type. for instance show warning if the input is string.
numbers = [7,3,13,6,8,5,1,2,4,15,9,10,12,14,11]
def ask_number():
num = int(input("Enter any number from the list 'numbers': "))
check_number(num)
def check_number(num):
if num not in numbers:
print("Number does not exist in the list")
ask_number()
else:
print(f"found {num} in list")
ask_number()
I just started learning Python and am stuck with an exercise.
The program should ask the user for a number and then print out a list including all of the number's divisors.
myList = []
usernumber = int(input("Please enter a number: "))
a = int(1)
for a in range(1, usernumber):
while usernumber % a == 0:
divisor = usernumber / a
myList.append(divisor)
a += 1
print(*myList)
This seems to work for everything except 1, but I can't figure out what I have to change to make it work for an input of 1. Any ideas?
Try this:
myList = []
usernumber = int(input("Please enter a number: "))
#No need to declare a as an integer, for loop does that for you.
for a in range(1, usernumber+1):
#usernumber+1 as range() does not include upper bound.
#For each number leading up to the inputted number, if the
#remainder of division is 0, then add to myList.
if usernumber % a == 0:
myList.append(a)
print(myList)
I'm supposed to write a code that asks users for 10 numbers, create a list with that and then sum them all up. I'm currently able to do that. However, I don't know how to check that the numbers do not overlap each other. If they do, the number is not supposed to be added onto the list.
So I am able to get the program to run such that it asks for a number for 10 times. However, after that, it appears to have a syntax error when producing the sum.
numberList = []
for i in range (0,10):
number= int(input("Please enter a number: "))
numberList.append(number)
total = sum(numberList)
total = sum(numberList)
TypeError: 'int' object is not callable
You can use if condition with "not in", it will only add the new numbers in the list. I am not getting any error doing sum operation. May be there is sum indentation issue please check that.
numberList = []
for i in range (0,10):
number= int(input("Please enter a number: "))
if number not in numberList:
numberList.append(number)
print "List formed: %s" %numberList
total = sum(numberList)
print "Sum of all elements in list: %d" %total
Console:
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
List formed: [1, 2, 3, 4, 5]
Sum of all elements in list: 15
Removing duplicates from a python list can be done in a few different ways. The most common for lists that need to keep their order is to convert into an OrderedDict because dictionary keys must be unique it will not create additional keys for duplicate elements.
Because we are finding the sum of numbers, order does not matter so we can use a built-in method set() which converts any iterable in to a set (By nature, must have unique elements).
If you need it to be a list you can convert back to list afterwards:
numberList = list(set(numberList))
reduce, map and filter are some of the most important functions to learn in any programming language. For this use case the reduce() is perfect, it performs a rolling computation.
from functools import reduce
final_sum = reduce((lambda x, y: x + y), numberList)
I am just starting my first computer science class and have a question! Here are the exact questions from my class:
"Write a complete python program that allows the user to input 3 integers and outputs yes if all three of the integers are positive and otherwise outputs no. For example inputs of 1,-1,5. Would output no."
"Write a complete python program that allows the user to input 3 integers and outputs yes if any of three of the integers is positive and otherwise outputs no. For example inputs of 1,-1,5. Would output yes."
I started using the if-else statement(hopefully I am on the right track with that), but I am having issues with my output.
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
I have this, but I am not sure where to go with this to get the desired answers. I do not know if I need to add an elif or if I need to tweak something else.
You probably want to create three separate variables like this:
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
In your code you only keep the value of the last number, as you are always writing to the same variable name :)
From here using an if else statement is the correct idea! You should give it a try :) If you get stuck try looking up and and or keywords in python.
On the first 3 lines, you collect a number, but always into the same variable (num). Since you don't look at the value of num in between, the first two collected values are discarded.
You should look into using a loop, e.g. for n in range(3):
for n in range(3):
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
Use the properties of the numbers...
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
Try Something like this
if num1< 0 or num2 <0 or num3 < 0:
print ('no')
elif num1 > 0 or num2 > 0 or num3 > 0:
print ('yes')
i've been making a program on python...
selected_pizzas=[] #creates an empty list
for n in range(pizza_number):
selected_pizzas = selected_pizzas + [int(input("Choose a pizza: "))]
that will let the user input up to 5 numbers and store them in an empty list (selected_pizzas) the the user is only aloud to enter numbers from 0-11, i had a method of using while loops to check errors with the users inputs but i tried and it didn't seem to work with the numbers being inputted in the list:
pizza_number=0
goodpizza_number=False
while not goodpizza_number:
try:
pizza_number= int(input("How many Pizzas do you want? (MAX 5): "))
if pizza_number ==0 or pizza_number > 5: #if the number of pizzas asked for is 0 or over 5 it will give an error message and repeat question
print("Not a correct choice, Try again")
else:
goodpizza_number=True
except ValueError:
print("Not a number, Try again")
how would i use this method (above) to make sure the user is inputting the expected inputs(numbers from 0-11) in the first piece of code shown in the question
Thanks
You could do:
selected_pizzas=[] #creates an empty list
while len(selected_pizzas) < pizza_number:
try:
pizza_selection = int(input("Choose a pizza: "))
except ValueError:
print("Not a number, Try again")
else:
if 1 <= pizza_selection <= 11:
selected_pizzas.append(pizza_selection)
This will make sure you still get the correct number of pizzas even after user errors.