I am trying to create a for loop where the user inputs a number n and the output provides the range of values from n to n+6. This needs to all be printed in one row and be right aligned with spaces in between value outputs but no space at the end or start of the output.
So far this is what I've come up with:
n=eval(input("Enter the start number: "))
for n in range(n,n+7):
print("{0:>2}".format(n),end=" ")
However, this results in the following output:
-2 -1 0 1 2 3 4 <EOL>
When the output I want needs to look similar but without the space at the end, like so:
-2 -1 0 1 2 3 4<EOL>
How can I add spaces between values without adding an additional space to the final term?
There are 3 recommendations I could make:
use end="" and insert the whitespaces manually
create a string and print after the loop:
s = ""
for n in range(n, n+7):
s+= str(n)+ " "
s = s[:-1] #remove the ending whitespace
print(s)
which I recommend: Using sys.stdout.write instead print:
print only displays the message after a linebreak was printed. So if there is a long calculation in the loop and there is end=" " you will only see the resulr at the end of all calculations. Use sys.stdout instead
for n in range(n, n+7):
if n < n+7:
sys.stdout.write(str(n)+" ")
else:
sys.stdout.write(str(n))
sys.stdour.flush() #flush output to console
Edit: I evolved a bit and this is what I'd use nowadays:
4. message = " ".join(range(n, n+7))
This puts spaces between all elements of a list. You can choose any separation character instead of a space (or multiple characters).
Related
So here is my problem, I have this program that is supposed to print multiple lines of numbers according to the number of columns and spaces the user inputs:
def main():
from string import Template # We import the Template method as seen in python glossary 7.1.4
s_num, e_num = [int(x) for x in input("Please enter a starting number and an ending number separated by a comma: ").split(',')] #We define the variables, s_num and e_num, as the respective starting point and ending point of the range that the user will input. In addition we call the int() function to make sure the input is an integer.
column, space = [int(x) for x in input("Please enter the number of numbers printed on a row and the number of spaces per item separated by a comma: ").split(',')] #We define the variables, column and space, as the respective amount of rows and amount of spaces that the user will input. In addition we call the int() function to make sure the input is an integer.
print('------------------------------') # We print a line of indents as in the sample
print('\n')
print ('Your print-out of numbers {}-{} using {} colums and {} spaces between numbers:'.format(s_num, e_num, column, space)) #We use the format method to implement the four variables created in the line and including them in the string phrase.
a = Template('$spce') # We create a variable "a" with one template "spce" that we will modify afterwards to implement in it the number of spaces that the user has inputted.
b = a.substitute(spce = ' ' * (space)) # We create a second variable b that will substitute the template "spce" with the number of spaces, by multipling the integers in the space variable by, ' ', a normal space.
counter = 1 # We create a variable called counter that will count the number of lines, in order to know when to go back to line.
for i in range(s_num,e_num + 1): # We invoke a "for" loop in the range of numbers inputted by the user. In addition we add "+1", to also take the last integer of the range.
print ('{}{}'.format(i,b),end='') # We implement the ".format" method as an alternative to print(i+b) since i and b are from different types, and finally we add " end='' " to get back to the line.
if (counter % column == 0 ): # We invoke a conditional statement, so that the program knows when to get back to the line:
print() # In that respect, if the number of lines divided by the amount of rows is nill: then the program goes back to the line.
counter = counter + 1 # We add an additional line to the counter variable, that is counting the lines, and we iterate all over again until all the numbers are printed
main()
But if i input for instance :
Please enter a starting number and an ending number separated by
a comma: 1,32
Please enter the number of numbers printed on a row and the
number of spaces per item separated by a comma: 10,4
I get :
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32
Rather than :
expected output
I tried the format methods using : {:<},{:-},etc but it works at most for two or three different inputs, rather than all of them.
Thanks in advance
To get the desired output replace
print ('{}{}'.format(i,b),end='')
with
print ('{: >2}{}'.format(i,b),end='')
This is minimal improvement. Here 2 is the amount of digits in the largest number. You should calculate it from e_num value - len(str(e_num)) and use the value to create appropriate string to be formatted and printed:
templ = '{' + ': >{}'.format(len(str(e_num))) + '}{}'
And then use it inside your for loop:
print (templ.format(i,b),end='')
Problem: Write a program that creates a pattern like the one below. Let the user input a non-negative integer to determine the number of lines of the pattern.
The sample output would take input, then have one blank line, then each next line would have a # (space) #, with increasing amount of spaces as count continues.
Example, entering the number 4 would produce one empty line; two pounds on the second line; one pound, one space, one pound on the third line; one pound, two spaces, one pound on the last line.
lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
for b in range(a + 1):
print('#', end='')
print()
Above code gives me close to what I want, but it is pounds all across instead of spaces between the two pound signs. I have no idea how to put the spaces there, any help would be awesome.
You can format the output with a variable width:
lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
print('#%*s' % (a, '#') if a else '')
This outputs:
(blank line)
##
# #
# #
Or try:
for a in range(lines):
print('#%s#' % ((a-1)*' ') if a else '')
Example output:
Enter number of lines for pattern: 4
##
# #
# #
I am in an introduction to Anaconda class and I need to write a program to determine how many times a dice roll(s) land on a certain amount of faces. However, I cannot get it to print my answer correctly.
Your problem is your print statement. You try to print a string then something called end then another string, and so forth. I think you want that end to be an end-of-line character.
Instead of printing something like
print("a string" end "another string" end "a third string")
use
print("a string\n" "another string\n" "a third string")
Note that "\n" is the end-of-line character in Python. My code also uses a feature of Python where you can combine string literals by placing them next to each other. Let lets you see the individual lines more clearly. Your code failed because you tried to do this with a string variable, namely end, and you did not even define that variable.
From Python docs: https://docs.python.org/3/library/functions.html#print
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
As you can see, the end is one of the parameters for the print() function, and by default, end=’\n’. So to use it correctly, you just have to change the end variable (which may not be directly applicable to your code)
Here are some examples:
>>> for i in range(3):
print(i, end =' ')
0 1 2
>>> for i in range(3):
print(i, end ='')
012
>>> for i in range(3):
print(i) # by default end=\n
0
1
2
>>>
And also, if I am understanding your logic correctly, the same code can be re-written as such.
import random
RollDice = int(input("Number of Rolls:"))
numbers = [0 for _ in range(6)] # array of 6 spaces with int 0
for i in range(RollDice):
Roll = random.randint(1,6)
numbers[Roll-1] += 1 # the array index starts from 0 hence you need Roll-1
plusMinus = "+-----"*6 + "+\n" # since you are repeating this you might want to assign it to a variable
print(plusMinus + "| 1 | 2 | 3 | 4 | 5 | 6 |\n" + "| " + " | ".join(map(str,numbers)) + " |\n" + plusMinus)
P.S. Rather than attaching an image, please copy and paste your code next time, so that we can copy n paste to test.
I am learning about Python and got to the expandtabs command in Python.
This is the official definition in the docs:
string.expandtabs(s[, tabsize])
Expand tabs in a string replacing them by one or more spaces, depending on the current column and the given tab size. The column number is reset to zero after each newline occurring in the string. This doesn’t understand other non-printing characters or escape sequences. The tab size defaults to 8.
So what I understood from that is that the default size of tabs is 8 and to increase that, we can use other values
So, when I tried that in the shell, I tried the following inputs -
>>> str = "this is\tstring"
>>> print str.expandtabs(0)
this isstring
>>> print str.expandtabs(1)
this is string
>>> print str.expandtabs(2)
this is string
>>> print str.expandtabs(3)
this is string
>>> print str.expandtabs(4)
this is string
>>> print str.expandtabs(5)
this is string
>>> print str.expandtabs(6)
this is string
>>> print str.expandtabs(7)
this is string
>>> print str.expandtabs(8)
this is string
>>> print str.expandtabs(9)
this is string
>>> print str.expandtabs(10)
this is string
>>> print str.expandtabs(11)
this is string
So here,
0 removes the tab character entirely,
1 is exactly like the default 8,
but 2is exactly like 1 and then
3 is different
and then again 4 is like using 1
and after that it increases up till 8 which is the default and then increases after 8.But why the weird pattern in numbers from 0 to 8? I know it is supposed to start from 8, but what is the reason?
str.expandtabs(n) is not equivalent to str.replace("\t", " " * n).
str.expandtabs(n) keeps track of the current cursor position on each line, and replaces each tab character it finds with the number of spaces from the current cursor position to the next tab stop. The tab stops are taken to be every n characters.
This is fundamental to the way tabs work, and is not specific to Python. See this answer to a related question for a good explanation of tab stops.
string.expandtabs(n) is equivalent to:
def expandtabs(string, n):
result = ""
pos = 0
for char in string:
if char == "\t":
# instead of the tab character, append the
# number of spaces to the next tab stop
char = " " * (n - pos % n)
pos = 0
elif char == "\n":
pos = 0
else:
pos += 1
result += char
return result
And an example of use:
>>> input = "123\t12345\t1234\t1\n12\t1234\t123\t1"
>>> print(expandtabs(input, 10))
123 12345 1234 1
12 1234 123 1
Note how each tab character ("\t") has been replaced with the number of spaces that causes it to line up with the next tab stop. In this case, there is a tab stop every 10 characters because I supplied n=10.
The expandtabs method replaces the \t with whitespace characters until the next multiple of tabsize parameter i.e., the next tab position.
for eg. take str.expandtabs(5)
'this (5)is(7)\tstring' so the '\t' is replaced with whitespace until index=10 and follwing string is moved forward. so you see 10-7=3 whitespaces.
(**number in brackets are index numbers **)
eg2. str.expandtabs(4)
'this(4) is(7)\tstring' here '\t' replaces until index=8. so you see only one whitespace
The first line of the pattern has 5 dashes followed by 1 star, the second line has 4 dashes followed by 3 stars, the third line has 3 dashes followed by 5 stars, etc. The last line of the pattern has 0 dashes and 11 stars.
I'm trying to print out the following result. I don't know any changes should be made to my code?
-----*
----***
---*****
--*******
-*********
***********
def printing(dash, star):
for i in dash:
print("-")
for i in star:
print("*")
print(dash, star)
def main():
dash = 5
star = 1
while dash >=0:
printing(dash, star)
dash = dash-1
star = star+2
main()
What's wrong with your code
for i in dash: will try to iterate over every element i in the iterable dash. But you gave it an integer, which is not iterable.
For that to work as-is, you should do for i in range(dash). range(n) returns a list of n integers starting with 0. That way you can iterate dashtimes.
Easier approach
Given that python allows you to multiply strings by integers effectively repeating said strings, and chain them by simply adding them with +, you can have a much simpler approach:
def printing(dash, star):
print '-'*dash + '*'*star
You might be interested in a new algorithm. Try this.
s="-----*"
print(s)
while "-" in s:
s=s.replace("-*", "***")
print(s)
You'll notice the "-" in s line. That's just checking to see if a hyphen is in the string. You can do that since strings act like iterators. You can add as many hyphens as you want in there.
You seem to want for i in xrange(dash). https://docs.python.org/2.7/tutorial/controlflow.html#for-statements
You cant iterate through int, you need to use range()
Try this:
def printing(dash, star):
for i in range(dash):
print("-", end="")
for i in range(star):
print("*", end="")
print()
def main():
dash = 5
star = 1
while dash >=0:
printing(dash, star)
dash = dash-1
star = star+2
main()
output:
-----*
----***
---*****
--*******
-*********
***********
It's probably easier to use Python's string repetition and concatenation operators to build your lines, rather than using loops to print each character separately. If you multiply a string by an integer, it will be repeated that number of times. Adding two strings concatenates them.
Here's a simple function that produces the output you want:
def main():
for dashes in range(5, -1, -1): # dashes counts down from 5 to zero
stars = 1 + 2*(5 - dashes) # the number of stars is derived from dashes
print("-"*dashes + "*"*stars) # just one call to print per line
As #wRAR mentioned, you should use for i in xrange(dash). Another thing is that, you should properly use print to control the newline, \n
In Python 3.X:
def printing(dash, star):
for i in dash:
print('-', end='')
for i in star:
print('*', end='')
print ('')
In Python 2.x:
def printing(dash, star):
for i in dash:
print '-',
for i in star:
print '*',
print ''