Hi im trying to write a program which uses a repetition statement to allow users to enter 5 numbers and stores them in a list.Then allow the user to search the list for a number entered by the user and indicate whether the number has been found or not. Im quite stuck on this one, I've made as much of an effort as i can
data =raw_input('Please input 5 numbers: ')
print data
search =raw_input('Search for the numer: ')
for sublist in data:
if sublist[1] == search:
print "Found it!", sublist
break
data is a string, the for loop will loop over every character in this string. That's probably not what you want.
If you want to find an integer in a list of integers, split the input on whitespace and convert each to an integer using int.
ints = [int(x) for x in data.split()]
if int(search) in ints:
print "Found it"
You might try something like this
numbers = []
while len(numbers) < 5:
number = raw_input('Please input 5 numbers: ')
if number.isdigit():
numbers.append(int(number)) #may want to use float here instead of int
else:
print "You entered something that isn't a number"
search = raw_input('Search for the numer: ')
if int(search) in numbers:
print "Found it!"
your code indicates that you may be using sublists but it is unclear how you are creating them.
Issue 1: This line stores the input as a string in the variable data.
data =raw_input('Please input 5 numbers: ')
At this point it is necessary to split the string into a list, and converting the elements to integers.
If the user inputs numbers separated by a space, you can do:
data_list = data.split() # if the numbers are comma-separated do .split(',') instead
int_list = [int(element) for element in data_list]
Issue 2: The users search input should be converted to an integer
search =raw_input('Search for the numer: ')
search_int = int(search)
Issue 3: There is no need for indexing the sublist as you've attempted sublist[1].
The for-loop should then be:
for sublist in int_list:
if sublist == search_int:
print "Found it!", sublist
break
Related
how to take list as a input in python in a single line.
enter image description hereI tried following thing but it didn't worked
You need to take input separated by space:
input_string = input("Enter a list element separated by space ")
lst = input_string.split()
You can also take input separated by any other character as well.
You can do so by accepting the numbers on a single line separated by spaces and then split it to get all the numbers as a list, then map it to an integer value to produce the required integer list.
numList = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))
print(numList)
You can make use of eval function.
_list = eval(input("enter the list:"))
When prompted you pass the list as follow: [1, 2, 3]
Your _list variable will be a list structure containing 1, 2 and 3 as elements.
Edit: this, of course, does not guarantee that only lists will be accepted on the input, so have this in mind.
list1 = input("data with spaces: ").split(" ")
list2 = input("data with commas: ")split(",")
I have written a code that should input numbers from the user and report back the numbers from 1 to 100 that are missing from their input.
My code is below which doesn't work:
num_list = []
number = input('Enter numbers (remember a space): ')
number.split()
num_list.append(number)
for i in range(1, 101):
if i in num_list:
continue
else:
print(i, end =', ')
The code outputs all the numbers from 1 to 100 but doesn't exclude the numbers.
Note: The code has to exclude all the numbers entered not only one number.
E.g. if the user inputted 1 2 3 4 the output should start from 5 and list the numbers through to 100.
There are three of problems
1) your are not saving the returned list from split method
result = number.split()
2) Use extend instead of append
num_list.extend(result)
3) By default input will read everything as string, you need to convert them into int from string after splitting, below is example using List Comprehensions
result = [int(x) for x in number.split()]
append : Will just add an item to the end of the list
So in you case after appending user input your list will be
num_list.append(number) #[[1,2,3,4,5]] so use extend
extend : Extend the list by appending all the items from the iterable.
num_list.append(number) #[1,2,3,4,5]
Note : If the num_list empty you can directly use result from split method, no need of extend
So my programming assignment wants me to take a user inputted list of numbers, ints and floating, and then order them in descending order and replace any of the floating with "0". I have got the reorder part done but the replace is getting me lost.
Reading Numbers
Write a program that shall ask the user to enter several integer numbers on
the same line, separated by vertical bars surrounded by zero or more spaces
(e.g., “|” or “ |” or “| ” or “ | ”). The program then shall display the entered
numbers in the descending sorted order (from the largest to the smallest),
all on the same line, separated by vertical bars and spaces (“ | ”). If
any entry on the command line is not an integer number, the program shall
replace it with a 0. Use only “for” loop(s) or list comprehensions. Use exception
handling.
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|' :
").split("|")
# replace the floating numbers with "0"
for number in numbers:
print(type(number))
if number.isdigit() == False:
numbers.replace(number,'0')
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(key = float , reverse = True)
[print(number,end = ' | ') for number in numbers]
One change I made was switching all of the for number in numbers to for i in range(len(numbers)). This allows you to access the actual variable by index, while for number in numbers just gets the value.
Here is my solution. I tried to add comments to explain why I did what I did, but if you have any questions, leave a comment:
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|'\n").split(
"|")
# strip any extra spaces off the numbers
for i in range(len(numbers)):
numbers[i] = numbers[i].strip(" ")
# replace the floating numbers and strings with "0"
for i in range(len(numbers)):
try:
# check if the number is an int and changes it if it is
numbers[i] = int(numbers[i])
except:
# set the item to 0 if it can't be converted to a number
numbers[i] = 0
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(reverse = True)
# changes the numbers back into strings
numbers = [str(numbers[i]) for i in range(len(numbers))]
# makes sure that there are more than one numbers before trying
# to join the list back together
if len(numbers) > 1:
print(" | ".join(numbers))
else:
print(numbers[0])
the instructions permit you to use exceptions. the following should get you most of the way there.
>>> numbers = ['1', '1.5', 'dog', '2', '2.0']
>>> for number in numbers:
>>> try:
>>> x = int(number)
>>> except:
>>> x = 0
>>> print(x)
1
0
0
2
0
I'm a noob so please excuse me.
There are three lists
A list of letters L = ['A','B','C','D','E']
A list of numbers N = ['1','2','3','4','5']
A list of number strings List = ['124','351']
These are the steps I wish to achieve
Request a letter from the user e.g. A
Find the letter in the letter list L and record its numerical position e.g. [0]
Use the same numeric position in the list of numbers N and record the
number that's there e.g. 1
Replace the instances of the number found in the non-letter strings List e.g. ['124','351'] becomes ['A24','35A']
Ask the user for the next letter until all the number strings become letters.
What I have achieved so far is the first 4 steps. After step 4 I thought to check if the number strings still contained numbers and if so go to step 5. I can't seem to work out how to get the code to check if the number strings contain any more number. NOTE: The number list is not limited to numbers. It could contain math symbols e.g. + or -
L = ['A','B','C','D','E']
N = ['1','2','3','4','5']
list = ['124','351']
print ("Enter a letter")
# Is there a number in List
# If yes then do the following else print List
# Ask for a letter from the user
letter = input ("Enter letter: ")
# Confirm whether the letter is correct or not
if letter in L:
# Find the position of the letter in the list
position = (L.index(letter));
# Make a variable called number with value at the same position in the N list
number = N[position];
# Replace the numbers in the List with the letter entered
list = [item.replace(number, letter) for item in list];
# Print the list with the numbers replaced
print (list, "\n");
print ("Please guess again. \n");
letter = input ("Enter a letter now: ")
# repeat until the List only contains letters
else:
print ("That is not correct");
print ("Please guess again. \n");
letter = input ("Enter a letter now: ")
I hope that is OK. If you need anything further please let me know
L = ['A','B','C','D','E']
N = ['1','2','3','4','5']
n_strings = ['124','351'] # Don't use list as a variable name
while not all( x.isalpha() for x in n_strings): # keep going until all are alpha chars
print ("Enter a letter")
# Is there a number in List
# If yes then do the following else print List
# Ask for a letter from the user
letter = input("Enter letter: ")
# Confirm whether the letter is correct or not
if letter in L:
# Find the position of the letter in the list
position = (L.index(letter));
# Make a variable called number with value at the same position in the N list
number = N[position];
# Replace the numbers in the List with the letter entered
n_strings = [item.replace(number, letter) for item in n_strings];
# Print the list with the numbers replaced
print (n_strings, "\n");
print ("Please guess again. \n");
letter = input("Enter a letter now: ")
# repeat until the List only contains letters
else:
print ("That is not correct");
print ("Please guess again. \n");
letter = input("Enter a letter now: ")
You could change the logic and shorten the code.
while True:
if all(x.isalpha() for x in n_strings ):
print("All guessed correct {}".format(n_strings)) # if all are alpha print final n_string and break out of loop
break
print n_strings
letter = input("Please enter a letter: ")
if letter in L:
# Find the position of the letter in the list
position = (L.index(letter));
number = N[position];
n_strings = [item.replace(number, letter) for item in n_strings];
print (n_strings, "\n");
# repeat until the List only contains letters
else:
print ("That is not correct");
print ("Please guess again. \n");
I can't seem to work out how to get the code to check if the number
strings contain any more number
You could define a function that loops over the list to see if any of the entries have digits using using isdigit() like so
def has_number(lst):
for s in lst:
if any(x.isdigit() for x in s):
return True
return False
This will return True if any of the entries in your number string list contains a number
Saw your edit
My goal is for it to contain letters only
To do that you could just check like this
if all(x.isalpha() for x in lst):
# lst contains only entries that consists of letters
This uses isalpha()
str.isalpha()
Return true if all characters in the string are
alphabetic and there is at least one character, false otherwise.
Demonstration:
>>> all(x.isalpha() for x in ['abc', 'def'])
True
>>> all(x.isalpha() for x in ['ab1', 'def'])
False
I have a function here and I want it to count the length of list like 1,2,3,4,5 =5
but the function only counts numbers 1234=4
how can i fix this
def mylen(alist):
if alist:
return 1 + mylen(alist[1:])
return 0
def main():
alist=input("Enter a list of number :")
print(mylen(alist))
main()
fyi i cannot use len
I'm assuming you want mylen('1234') to be = 1. Take your input and split up the numbers by the comma separator.
def mylen(alist):
if alist:
return 1 + mylen(alist[1:])
return 0
def main():
alist=input("Enter a number :")
print(mylen(alist.split(','))
main()
There is no need for the computer to do so much processing for something that is built into the language. This will work just fine:
alist=input("Enter a number :")
print(len(alist.split(','))
In Python 3:
alist=input("Enter a list of number :")
alist will now be a string. If you enter "1,2,3,4,5", a list will be the string "1,2,3,4,5", not a list of numbers [1,2,3,4,5].
A string is a sequence type, just like a list, so your code works with the string as well, and counts the number of elements (characters) in it.
You can use split to convert the input in a list:
userinput = input("Enter a list of number :")
alist = userinput.split(",")
(Note that this is still a list of strings, not numbers, but this doesn't matter for this exercise.)