Imagine I have the following code in file test.py:
for x in range(1,11):
print x
This will print:
$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
However, I want it to print:
$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
Notice the last '\n' char, that is missing in the normal case. How do I get this last newline char?
Nothing is missing; if there wasn't a newline at the end the last line would look like 10$myuser:
Perhaps you want:
for x in range(1,11):
print x
print
Just put a bare print after the loop.
That's why I love python3:
print(*range(5), sep='\n',end='\n\n')
actually this is ugly:
for i in range(5)+['']:
print i
Related
I have to print below patter.
1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 5 4 3 2 1
when I use following code printing same pattern but the answer is not acceptable because new line
for i in range(1, N + 1):
val = ''
for j in range(1, i + 1):
val += ' ' + str(j)
val = val.strip()
val += ' ' * (N - i)
print(val,val[::-1])
output is same but showing output difference as-
when i uses follow code everything is okay and all test cases passed-
for i in range(1,N+1):
for j in range(1,1+i):
print(j,end=' ')
print(' '*(N-i),end='')
print(' '*(N-i),end='')
for j in range(i,0,-1):
print(j,end=' ')
print()
where am i doing mistake?
Not really a python question. More a question about the validator you are submitting your code to.
But, indeed, your 2 codes are not producing exactly the same result.
The first one is better in my view.
The secoond (and, apparently the one of the teacher who created the validator) add an extra space to each line. Which shows either by using a tool like | hexdump -C to inspect exact output.
Or by looking at the code: you were careful enough to avoid those spaces with correct usage of strip in the 1st code. When the second just write a space after each number, including the last one.
So if you ask me, the rejection of your first code was unfair (it is not only visually the same. But better. If you have a small terminal, with just enough width, that extra space may lead to pattern not rendering well when it should). So unfair. But, well, now your know the reason.
This question already has answers here:
Does Python support short-circuiting?
(3 answers)
Closed last year.
For the following exercise I am expecting an IndexError for certain test inputs, but it is not occurring.
Goal: Write a function that takes in a list of integers and returns True if it contains 007 in order
My Function:
def spy_game(nums):
for x in range(len(nums)):
print(x)
try:
if nums[x]==0 and nums[x+1]==0 and nums[x+2]==7:
return(True)
except IndexError:
return(False)
Test Cases:
#Case 1
spy_game([1,2,4,0,0,7,5])
#Case 2
spy_game([1,0,2,4,0,5,7])
#Case 3
spy_game([1,7,2,0,4,5,0])
Question:
I included the print statement in the function to try to understand the issue. Case 1 prints 0 1 2 3 and returns True which is expected. Case 2 prints 0 1 2 3 4 5 6 and does not return anything. Case 3 prints 0 1 2 3 4 5 6 and returns False. For both Case 2 and 3 I would expect it to print up to 5 and at that point result in an IndexError. I am not sure why Case 2 reaches 6 and has no IndexError and why Case 3 reaches 6 and does have one. Thanks in advance!
The reason it is not giving you an IndexError comes from how and operations occur in the code. Case 2 will not get to the point of looking for x+2 because it fails on the other operations before.
a = [True, True, True]
if a[0] == False and a[100000] == None:
for example, will never give you an IndexError because it fails on the first if.
This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Closed 6 years ago.
if given a command like:
python 1.py ab 2 34
How to print the next argument while you are currently sitting on the one before. e.g if x is ab then I want to print 2:
import sys
for x in sys.argv[1:]:
print next element after x
I am unsure what you want to print but this syntactic sugar can help:
for x in sys.argv[1::2]:
print x
This prints every other element. So this will return ab 34
for x in sys.argv[2::2]:
print x
This will return 2
The number after the :: is how many slots in the array.
Edit:
To answer your specific question:
val = 1
for index, x in enumerate(sys.argv[1::2]):
val += 1
print sys.argv[index+val]
The index increases by 1 each time, and the val by 1 too, meaning every loop we skip 2 variables. Hence for something like python yourcode.py a 1 b 2 c 3 d 4 output will be 1 2 3 4
How to put spaces between values in a print() statement
for example:
for i in range(5):
print(i, sep='', end='')
prints
012345
I would like it to print
0 1 2 3 4 5
While others have given an answer, a good option here is to avoid using a loop and multiple print statements at all, and simply use the * operator to unpack your iterable into the arguments for print:
>>> print(*range(5))
0 1 2 3 4
As print() adds spaces between arguments automatically, this makes for a really concise and readable way to do this, without a loop.
>>> for i in range(5):
... print(i, end=' ')
...
0 1 2 3 4
Explanation: the sep parameter only affects the seperation of multiple values in one print statement. But here, you have multiple print statements with one value each, so you have to specify end to be a space (per default it's newline).
Just add the space between quotes after the end. It should be:
end = " "
In Python 2.x, you could also do
for i in range(5):
print i,
or
print " ".join(["%s"%i for i in range(5)])
This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
Closed 6 years ago.
I want to print the looped output to the screen on the same line.
How do I this in the simplest way for Python 3.x
I know this question has been asked for Python 2.7 by using a comma at the end of the line i.e. print I, but I can't find a solution for Python 3.x.
i = 0
while i <10:
i += 1
## print (i) # python 2.7 would be print i,
print (i) # python 2.7 would be 'print i,'
Screen output.
1
2
3
4
5
6
7
8
9
10
What I want to print is:
12345678910
New readers visit this link aswell http://docs.python.org/release/3.0.1/whatsnew/3.0.html
From help(print):
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
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.
You can use the end keyword:
>>> for i in range(1, 11):
... print(i, end='')
...
12345678910>>>
Note that you'll have to print() the final newline yourself. BTW, you won't get "12345678910" in Python 2 with the trailing comma, you'll get 1 2 3 4 5 6 7 8 9 10 instead.
* for python 2.x *
Use a trailing comma to avoid a newline.
print "Hey Guys!",
print "This is how we print on the same line."
The output for the above code snippet would be,
Hey Guys! This is how we print on the same line.
* for python 3.x *
for i in range(10):
print(i, end="<separator>") # <separator> = \n, <space> etc.
The output for the above code snippet would be (when <separator> = " "),
0 1 2 3 4 5 6 7 8 9
Similar to what has been suggested, you can do:
print(i, end=',')
Output: 0,1,2,3,
print("single",end=" ")
print("line")
this will give output
single line
for the question asked use
i = 0
while i <10:
i += 1
print (i,end="")
You can do something such as:
>>> print(''.join(map(str,range(1,11))))
12345678910
>>> for i in range(1, 11):
... print(i, end=' ')
... if i==len(range(1, 11)): print()
...
1 2 3 4 5 6 7 8 9 10
>>>
This is how to do it so that the printing does not run behind the prompt on the next line.
Lets take an example where you want to print numbers from 0 to n in the same line. You can do this with the help of following code.
n=int(raw_input())
i=0
while(i<n):
print i,
i = i+1
At input, n = 5
Output : 0 1 2 3 4