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)')
Related
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.
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(',')))))
This is the code.
n = int(input("Enter number of strings: "))
for i in range(n):
ai= input("Enter string ")
i=0
print(ai)
Why does it give last string and not the first string?
If I try to print a0 ,it gives error.
I know that I can use lists , but I didn't know about list when I wrote the program and now I have to change everything to use list.
Because you are overwriting the variable in each iteration of the loop, if you want to print all the strings added in the format you can use something like this
n = int(input('enter number of strings'));
ai = ''
for i in range(n):
ai += input('enter a string: ')+'\n'
i = 0
print(ai)
This will print your string.
You should use a list and append every input to the list instead:
n = int(input("Enter number of strings: "))
a = []
for _ in range(n):
a.append(input("Enter string: "))
print(a[0])
I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.