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.
Related
I've just started learning to code Python today on Grok Learning and I'm currently stuck on this problem. I have to create a code that reads a message and:
read the words in reverse order
only take the words in the message that start with an uppercase letter
make everything lowercase
I've done everything right but I can't get rid of a space at the end. I was wondering if anyone knew how to remove it. Here is my code:
code = []
translation = []
msg = input("code: ")
code = msg.split()
code.reverse()
for c in code:
if c[0].isupper():
translation.append(c)
print("says: ", end='')
for c in translation:
c = c.lower()
print(c, end = ' ')
Thank you :)
You need to iterate for all of the letters in translation but the last and print it separately without the space:
for c in translation[:-1]:
c = c.lower()
print(c, end = ' ')
print(translation[-1], end='')
You can simply use join() and f-strings.
result = ' '.join(translation).lower()
print(f"says: {result}")
This is a common problem:
You have a sequence of n elements
You want to format them in a string using a separator between the elements, resulting in n-1 separators
I'd say the pythonic way to do this, if you really want to build the resulting string, is str.join(). It takes any iterable, for example a list, of strings, and joins all the elements together using the string it was called on as a separator. Take this example:
my_list = ["1", "2", "3"]
joined = ", ".join(my_list)
# joined == "1, 2, 3"
In your case, you could do
msg = "Hello hello test Test asd adsa Das"
code = msg.split()
code.reverse()
translation = [c.lower() for c in code if c[0].isupper()]
print("says: ", end='')
print(" ".join(translation))
# output:
# says: das test hello
For printing, note that print can also take multiple elements and print them using a separator. So, you could use this:
print(*translation, sep=" ")
You could also leave out explicitly setting sep because a space is the default:
print(*translation)
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).
My current code
defname,last_name):
if not isinstance(reg, int) or \
not isinstance(year, int) or \
not isinstance(degree, str) or \
not isinstance(other_name, str) or \
not isinstance(last_name, str) :
print("Invalid string argument")
elif 0<=year<=4:
l.append((reg,year,degree,other_name,last_name))
else: print("Invalid year")
def p
reg,year,degree,other_name,last_name = student.strip().split(" ",4)
reg=int(reg)
year=int(year)
fullName=last_name+ ", " + other_name
thisYear="Year " + str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
how can I do this effectively with the right formats? I am trying to make it so it uses both functions and is checking for valid
Well, for the reason it's printing on that side, that's because of the way you called .split(). Calling it with the 4 will of course restrict it to splitting 4 times. And since it splits from left to right, once it has made its 4th split (ie. after 'Homer'), it will simply return the rest of the string as a whole (ie. 'J Simpson').
If I were you, I would do it like this:
reg,year,degree,*name = student.strip().split(" ")
name = list(reversed(name))
fullname = name[0] + ', ' + ' '.join(name[1:])
Doing *name lets you grab multiple tokens as a list, and then process them however you like.
First off, wouldn't you want it to print Simpson, Homer J?
Secondly, it prints it J Simpson, Homer because this is what your list looks like:[1342347, 2, G401, Homer, J Simpson].
It splits it this way because you told it to split at each space it sees, and to make a maximum of 4 separate strings. It doesn't know that middle names belong to other_name, so you have to do a little more work in your string parsing to get that to behave as desired.
This is because you are limiting the number of splits to 4.
Thus, for the third line, the 4th space that gets split is between "Homer" and "J". Thus, "J" and "Homer" are in the same string after the split.
https://www.tutorialspoint.com/python/string_split.htm
Here is my code at the moment
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
and the output looks like this
Percent off: 5
Percent off: 10
Percent off: 15
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
My question is focusing on this part
Percent off: 5%
10%
15%
20%
I'm struggling to figure out how to only print the Percent off: part once in my for loop.
I really dislike teachers who tell students to accomplish something without having shown them the right tool for the job. I'm guessing you haven't yet been introduced to the string.format() method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver.
Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So:
poff = 'Percent off: '
pad = ' '*len(poff)
p = poff
for percentage in percentagesOff:
print(p ,percentage, end= " ")
p = pad # for all subsequent trips around the loop
Better style would be to allow for the possibility that you might want poff output again (say) at the top of each page of output. So a better way to do the second code block is
for lineno, percentage in enumerate(percentagesOff):
if lineno==0: # can replace later with are-we-at-the-top-of-a-page test?
p = poff
else
p = pad
# p = poff if lineno==0 else pad # alternative shorter form
print(p ,percentage, end= " ")
You can just pull it out of the for loop, then it gets printed only once, or you could "remember" that you already printed it by setting some boolean variable to True(initialized at False) and then checking whether that variable is True or False before printing that part of the string.
Here
percentagesOff = [5, 10, 15, 20]
print("Percent off:\t", percentagesOff[0], '%')
for percentage in percentagesOff[1:]:
print("\t\t", percentage, "%")
Output
Percent off: 5 %
10 %
15 %
20 %
Here is one alternate solution:
percentagesOff = [1,2,3,4,5,6,7,8,9,10]
print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t'
for percentage in percentagesOff[1:]:
print ' '*len('Percent off: '), percentage
The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array.
Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number.
It is interesting excercise......
You can do something like this.
first = True
for p in pe:
if first == True:
print("percent off: ")
first = False
print(p)
else:
....
....
But you would not normally do it this way.
The fact is that python print add line break after your string to be printed. So,
Import import sys and, before your loop, use that:
sys.stdout.write(' $10 $100 $1000\n')
sys.stdout.write('Percent off:')
And now, you can start using print to write your table entries.
You can simply add a if statement with a boolean too.
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