How to print numbers on a new line in python - python

A program accepts a number of inputs, for instance numbers or integers, how do you print each and every one of them on a new line.
Eg. I enter this 2,4,5,2,38.
The program should display each one on a new line as this.
Item = input ("Enter your number")
#user enters the following numbers 5,2,6,3,2
#print out each number on a new line
# output
5
2
6
3
2
All saved i one variable.

All you need is a simple for loop that iterates over the input and prints it
data = raw_input('enter ints').split(',')
for n in data:
if n.isdigit():
print n
Note if you are using Pyhon 3.x, you need to use input instead of raw_input
The first row assigns user input data to data variable and splits items by space. (You can change this tow ',' instead)
The for loop does iteration on every item in that list and checks if it is a digit. Because the list elements are strings, we can use isdigit() method of string to test it.
>>> '5'.isdigit()
True
>>> '12398'.isdigit()
True
If you want to do it in another way, maybe using '\n'.join(data) method, which will join the list elements and join them with '\n'.
>>> inpu = raw_input('enter ints\n').split(',')
>>> inpu = [c.strip() for c in inpu]
>>> print '\n'.join(inpu)
1
2
3
4
This is actually the better way to go, as it is simpler than a for loop.

By typing in print() in python it will move to the next line. If it is a list you can do
for num in list:
print(num)
print()
You want to replace "list" with the name of your list.
You can also type in \n in your print function in quotes to move to a new line.

If the numbers are separated by a comma, you can split them by that comma, then join them by a new line:
>>> Item = input ("Enter your numbers: ")
Enter your numbers: 5,2,6,3,2
>>> Result = '\n'.join(Item.split(','))
>>> print(Result)
5
2
6
3
2
>>>

looks like I'm too late to the print party :)
this can work for you too ... wrap it in a function ideally
# assuming STDIN like: "2,4,5,2,38,42 23|26, 24| 31"
split_by = [","," ","|"]
i_n_stdin = input()
for i in split_by:
i_n_stdin = i_n_stdin.split(i)
i_n_stdin = " ".join(i_n_stdin)
#print(i_n_stdin)
for i in i_n_stdin.split():
print(i)

If you want to print a comma-separated list of integers, one integer at each line, you can do:
items = input('Enter a comma-separated list of integers: ')
print(items.replace(",", "\n"))
Example:
Enter a comma-separated list of integers: 1,13,5
1
13
5
You can improve by accepting ";" instead of "," and optional spaces using RegEx:
import re
items = input('Enter a comma-separated list of integers: ')
print(re.sub(r"[,;]\s*", "\n", items))
Example:
Enter a comma-separated list of integers: 2, 4, 5; 2,38
2
4
5
2
38

You can print in the new line by using by defining end parameter as '\n' (for new line) i.e print(x,end='\n')
>>> x=[1,2,3,4]
>>> for i in x:
print(i,end='\n')
output
1
2
3
4
you can use help function in python
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

Python 3.x
items = input('Numbers:').split(',') # input returns a string
[print(x) for x in items]
Python 2.x
items = input('Numbers:') # input returns a tuple
# you can not use list comprehension here in python 2,
# cause of print is not a function
for x in items: print x

Just set variable end = '\n'
and print your numbers like:
print(" " + str(num1) + end, str(num2) + end, str(num3) + end)

Related

how to take list as input in single line python

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(",")

Eliminate numbers between 1 and 100 present in list

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

list index out of range in simple Python script

I just started learning Python and want to create a simple script that will read integer numbers from user input and print their sum.
The code that I wrote is
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += inflow[i]
print(result)
It gives me an error
IndexError: list index out of range
pointing to result += inflow[i] line. Can't see what am I doing wrong?
BTW, is there more elegant way to split input flow to the list of integers?
You can also avoid the loop altogether:
inflow = '1 2 34 5'
Then
sum(map(int, inflow.split()))
will give the expected value
42
EDIT:
As you initialize your result with 1 and not 0, you can then also simply do:
sum(map(int, input.split()), 1)
My answer assumes that the input is always valid. If you want to catch invalid inputs, check Anton vBR's answer.
Considering: I just started learning Python
I'd suggest something like this, which handle input errors:
inflow = raw_input("Type numbers (e.g. '1 3 5') ") #in py3 input()
#inflow = '1 2 34 5'
try:
nums = map(int, inflow.split())
result = sum(nums)
print(result)
except ValueError:
print("Not a valid input")
for i in list gives the values of the list, not the index.
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += i
print(result)
If you wanted the index and not the value:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And finally, if you wanted both:
for index, value in enumerate(inflow):
script that will read integer numbers from user input and print their
sum.
try this :
inflow = list(map(int, input().split(" ")))
result = 0
for i in inflow:
result += i
print(result)
If you were going to index the list object you would do:
for i in range(len(inflow)):
result += inflow[i]
However, you are already mapping int and turning the map object into a list so thus you can just iterate over it and add up its elements:
for i in inflow:
result += i
As to your second question, since you arent doing any type testing upon cast (i.e. what happens if a user supplies 3.14159; in that case int() on a str that represents a float throws a ValueError), you can wrap it all up like so:
inflow = [int(x) for x in input().split(' ')] # input() returns `str` so just cast `int`
result = 1
for i in inflow:
result += i
print(result)
To be safe and ensure inputs are valid, I'd add a function to test type casting before building the list with the aforementioned list comprehension:
def typ(x):
try:
int(x)
return True # cast worked
except ValueError:
return False # invalid cast
inflow = [x for x in input().split(' ') in typ(x)]
result = 1
for i in inflow:
result += i
print(result)
So if a user supplies '1 2 3 4.5 5 6.3 7', inflow = [1, 2, 3, 5, 7].
What your code is doing, in chronological order, is this:
Gather user input, split per space and convert to integer, and lastly store in inflow
Initialize result to 1
Iterate over every item in inflow and set item to i
Add the current item, i to result and continue
After loop is done, print the result total.
The broken logic would be at step 4.
To answer your question, the problem is that you're not gathering the index from the list as expected-- you're iterating over each value in the list opposed to the index, so it's really undefined behavior based on what the user inputs. Though of course, it isn't what you want.
What you'd want to do is:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And on your last regard; there are two real ways to do it, one being the way you're doing right now using list, map and:
inflow = [int(v) for v in input().split()]
IMO the latter looks better. Also a suggestion; you could call stdlib function sum(<iterable>) over a list of integers or floats and it'll add each number and return the summation, which would appear more clean over a for loop.
Note: if you're splitting per whitespace you can just call the str.split() function without any parameters, as it'll split at every whitespace regardless.
>>> "hello world!".split()
['hello', 'world!']
Note: also if you want extra verification you could add a bit more logic to the list comprehension:
inflow = [int(v) for v in input().split() if v.isdigit()]
Which checks whether the user inputted valid data, and if not, skip past the data and check the following.

Printing long interger in python up to 10 digits

I am trying to take two long input integers (up to 10 digits) separated by space and display there sum.
I took the input into a string which are separated by space and then split them. After that I type caste them to int.
print "Enter two numbers"
a = raw_input()
a.split(" ")
sum = int(a[0]) + int(a[2])
print "\r", sum
Here I am not able to print the sum if the numbers are of even two digits.
You ignored the return value of str.split():
a.split(" ")
Assign that back to a:
a = a.split(" ")
Python strings are immutable, you cannot split the value of a in-place (let alone replace the type, splitting returns a list object rather than a new string).

Printing a list without line breaks (but with spaces) in Python

I'm trying to print the values of a list without line breaks using sys.stdout.write(). It works great, but the only problem is that I want to space each value from another. In other words, instead of 123, I want 1 2 3. I looked on the website for a solution, but I haven't found something that involves lists.
When I add " " to sys.stdout.write(list[i]), like this: sys.stdout.write(list[i], " "), it doesn't print at all. Any suggestions how to fix that?
Here's my code:
import random
import sys
list = []
length = input("Please enter the number of elements to be sorted: ")
randomNums = input("Please enter the number of random integers to be created: ")
showList = raw_input("Would you like to see the unsorted and sorted list? y/n: ")
for i in range(length):
list.append(random.randint(1,randomNums))
if(showList == "y"):
for i in range(length):
sys.stdout.write(list[i], " ")
Try
sys.stdout.write(" ".join(list))
The above will only work if list contains strings. To make it work for any list:
sys.stdout.write(" ".join(str(x) for x in list))
Here we use a generator expression to convert each item in the list to a string.
If your list is large and you'd like to avoid allocating the whole string for it, the following approach will also work:
for item in list[:-1]:
sys.stdout.write(str(item))
sys.stdout.write(" ")
if len(list) > 0:
sys.stdout.write(list[-1])
And as mentioned in the other answer, don't call your variable list. You're actually shadowing the built-in type with the same name.
You can do:
sys.stdout.write(" ".join(my_list))
Also, it's better not to name your variable list as Python already has a built-in type called list. Hence, that's why I've renamed your variable to my_list.
In Python3, I tried the above solution, but I got a weird output:
for example:
my_list = [1,2,3]
sys.stdout.write(" ".join(str(x) for x in ss))
the output is:
1 2 35
It will add a number at the end (5).
The best solution, in this case, is to use the print function as follows:
print(" ".join(str(x) for x in ss), file=sys.stdout)
the output: 1 2 3

Categories

Resources