i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output.
my first code:
f=int(input("String of numbers: "))
l=[]
for x in range(f):
string_numbers = int(input(f'Enter {x+1} string of numbers: '))
l.append(string_numbers)
mylist = list(dict.fromkeys(l))
print(len(mylist))
I wanted to take into account if the user entered a string too short or too long than declared. I wanted the user to type everything on one line. When I enter an incorrect string number, I get duplicated "incorrect string lengthincorrect string length"
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
if i < l:
print("incorrect string length", end='')
elif i > l:
print("incorrect string length", end='')
else:
It seems like you're mixing up your different variables -- f is what you want the length to be, l is just the number 2, and the way you're comparing those two has nothing to do with the actual input entered by the user, which is my_list.
Using variable names that indicate their meaning might make it easier to keep it all straight:
num_count = int(input("Length of string of numbers: "))
num_list = input('Enter numbers in the string, separated by spaces: ').split()
if len(num_list) == num_count:
print(f"there are {len(set(num_list))} different numbers")
else:
print("incorrect string length")
In the above code, num_count is the count of how many (non-unique) numbers you expect them to input, and num_list is the actual list. To figure out if the list is the expected length, compare num_count to len(num_list).
Note that since all you're doing is looking for unique values, converting the strings in num_list to int is not necessary (whether or not you use a set as I've done here).
You will most likely be better off using another function that ultimately has a while loop. This will make sure that when the user is giving the input that if anything is malformed you can then parse it checking and finally making sure to prompt the user again.
For example:
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
# XXX Here call your "input-function"
get_user_input(i, l)
def get_user_input(user_len, len):
while True user_len != len:
print('Incorrect Input')
user_len = int(input("String of numbers: "))
return
This is not exactly a working example but with what you have you get the idea that you want to do a while loop until your inputs match.
Related
i am asking the user to input a number as well as if they think their number plus a random integer will be odd or even in the same line but cant get it to work.
I wrote
user, num = input('Enter a number 1-10: ' and '\n odd or even?').split()
Only the 2nd string is asked (odd or even?) when i run the program.
i want it to be formatted as
Enter a number 1-10: \n
odd or even?
How do I take two different types of inputs using one line of code. i want the input from
'Enter a number: '
to be an int and i want the input from
'odd or even' to be a str
Well, you can simply use two lines of input. something like this:
num = int(input('Enter your number: '))
state = input('Odd or Even?')
Remove and it will work
>>> user, num = input('Enter a number 1-10: odd or even? ').split()
Enter a number 1-10: odd or even?10 3
>>> user
'10'
>>> num
'3'
>>>
input() outputs strings. You may have to convert it to int using int(num).
try this line:
user, num = input('Enter a number 1-10:' + '\nodd or even?\n').split()
numbers = list (input("Please enter your numbers: "))
print (numbers)
This is all I have when I start the code it only shows single digit numbers but when I put 12, I get '1' '2' how do I make it stay 12 and sort the numbers smallest to biggest?
input("Please enter your numbers: ") - this returns string
list(string) - will separate string on every character and make list of them
I think this will do what you want:
numbers = [int(x) for x in input("Please enter your numbers: ").split(' ')]
print (numbers)
I used split() function, and when i say string.split(' ') it will separate string on every ' ' and return the list.
For sorting the list you can use the built-in function sort(), or you can make your own. This page will help you to make your sorting function with selection sort.
I am trying to have the user input a series of numbers (separated by commas) to receive the total of them.
I have tried (with no luck):
values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)
values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)
If the user inputs 5.5,6,5.5 the expected output will be 17.
You're almost there.
After splitting, the values will still be strings, so you have to map them to float.
values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))
Output:
The total sum is: 17.0
Side note: Please don't name your variables list or sum, otherwise you will shadow the python built-ins!
After you split the values by comma into a list, you need to convert them from strings to numbers. You can do that with
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [float(x) for x in lst]
total = sum(lst)
print("The total sum is: ", total)
For reference, see List Comprehensions in Python.
(Also, you shouldn't use list as a variable name, since that's a function in Python.)
You have to convert the inputs to float:
numbers = input("Input some comma seprated numbers: ")
result = sum([float(n) for n in numbers.split(',')])
print(result)
You have to convert to numbers before adding them together.
For example, you could convert them all into floats:
input_str = input("Input some comma seprated numbers: ")
# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]
# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
try:
n = float(s)
number_list.append(n)
except ValueError:
pass
print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))
# empty list to store the user inputs
lst = []
# a loop that will keep taking input until the user wants
while True:
# ask for the input
value = input("Input a number: ")
# append the value to the list
lst.append(value)
# if the user wants to exit
IsExit = input("enter exit to exit")
if 'exit' in IsExit:
break
# take the sum of each element (casted to float) in the lst
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))
OUTPUT:
Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0
It's hard to know what went wrong w\o a sample of the error\output code.
I think the issue is in getting the sum of list (very bad name btw) when it's a list of strings.
please try the following
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)
This code will work when expecting integers, if you want floats then change the list comprehension.
Try not to name objects with the same name of standard objects such as list,int,str,float etc...
use below
print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))
I need to write a program that will check the numbers that a user enters. If the user enters a number more than once then it will skip over it and print out only numbers that the user entered once.
I was playing around with this:
def single_element():
numbers = []
numbers = input("Enter some numbers: ").split()
for i in numbers:
if i in numbers:
i + 1 #I was trying to find a way to skip over the number here.
print(numbers)
You can build a set to just print unique numbers:
numbers = input("Enter some numbers: ").split()
print set(numbers)
Use a set. They are iterables, like lists, and can easily be converted back and forth. However, sets do not contain duplicate values.
def single_element():
numbers = list(set(input("Enter some numbers: ").split()))
print(numbers)
In this function, you get the input numbers as a list and convert them to a set, which will remove duplicates, and then convert back to a list.
Note: sets are not guaranteed to keep the same order like lists.
this is my code on python 3.2.3 IDLE:
numbers = []
numbers = input("(Enter a empty string to quit) Enter a number: ")
while numbers != "":
numbers = input("(Enter a empty string to quit) Enter a number; ")
numbers.append(n)
print ("The list is", numbers)
problem now is, i can't append the list.
if i make numbers = int(input( then it works for appending the list but won't let me quit out of entering the numbers.
if i make numbers = input
like i have right now, it won't let me append the list
how can i get these numbers to append to a list?
There are two problems:
you're assigning the input to numbers instead of n;
the append() is in the wrong place.
Try the following:
numbers = []
n = input("(Enter a empty string to quit) Enter a number: ")
while n != "":
numbers.append(n)
n = input("(Enter a empty string to quit) Enter a number; ")
print ("The list is", numbers)
If you want to store integers instead of string, change the append() line to:
numbers.append(int(n))
Stylistically, if the first prompt is the same as the prompt for all subsequent inputs, I'd restructure the code as follows:
numbers = []
while True:
n = input("(Enter a empty string to quit) Enter a number: ")
if n == "": break
numbers.append(n) # or int(n)
print ("The list is", numbers)
Despite the problems you've got an answer to, this can be heavily simplified for simple data input:
numbers = list(map(int, iter(input, '')))
Working inside-out (a bit of explanation):
iter(input, '') repeatedly calls until '' (an empty input) is met and yields that value
the map(int,...) takes those values and tries to convert to an integer - an exception will be thrown if it can't
the list(...) then takes that and creates an actual list object
numbers = ... is err, as it says :)
Then, possibly wrap in a function (using functools.partial here, but lambda is fine):
def ask(prompt):
from functools import partial
prompt_func = partial(input, prompt)
return list(map(int, iter(prompt_func, '')))
numbers = ask('Keep entering valid numbers (or a blank line to quit)')