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 ''
Related
I ask the user to enter it's name and I print the pattern
eg:
W
WO
WOR
WORL
WORLD
s=input("Enter your name")
l=s.split()
i=len(l)
for m in range(0,i):
for s in range(0,m):
print(s)
print()
I have written this program where am I wrong please help. A beginner here
Others have given you code that does what you want it to do; I'll try to explain why your code doesn't do what you think it would do.
#s=input("Enter your name")
# Let's pretend that the given word from the user was 'WORLD' as in your example.
s = "WORLD"
l=s.split()
The above line s.split() uses the default-behaviour of the built-in str.split() method. Which does the following if we look at the help-file:
split(self, /, sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
That means that it will try to split your given string on each whitespace-character inside of it and return a list containing the results. "WORLD".split() would therefore return: ['WORLD']
i=len(l)
This returns 1, because the result of s.split().
Now let's break down what happens inside of the for-loop.
# This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive
for m in range(0,i):
# This is range-command will not execute, because the first value of m will be 0
# Because range is non-inclusive, running range(0, 0) will not return a value.
# That means that nothing inside of the for-loop will execute.
for s in range(0,m):
print(s)
print()
All of this results in only the print() statement inside of the first for-loop being executed, and it will only be executed once because of how the range-function works with the values it has been given.
We can do this without using 2 loops.
s = input("Enter your name")
for i in range(len(s)+1):
print(s[:i])
#Output:
W
WO
WOR
WORL
WORLD
Don't complicate the code unnecessarily.
A string you can think of as a list of characters on which to iterate, without resorting to splitting.
If you use Python's List Slicing, you can point to the positions of the characters you are interested in printing.
Your code becomes:
name = input("Enter your name: ")
for i in range(len(name)):
print(name[:i+1])
I am trying to build a function that will take a string and print every other letter of the string, but it has to be without the spaces.
For example:
def PrintString(string1):
for i in range(0, len(string1)):
if i%2==0:
print(string1[i], sep="")
PrintString('My Name is Sumit')
It shows the output:
M
a
e
i
u
i
But I don't want the spaces. Any help would be appreciated.
Use stepsize string1[::2] to iterate over every 2nd character from string and ignore if it is " "
def PrintString(string1):
print("".join([i for i in string1[::2] if i!=" "]))
PrintString('My Name is Sumit')
Remove all the spaces before you do the loop.
And there's no need to test i%2 in the loop. Use a slice that returns every other character.
def PrintString(string1):
string1 = string1.replace(' ', '')
print(string1[::2])
Replace all the spaces and get every other letter
def PrintString(string1):
return print(string1.replace(" ", "") [::2])
PrintString('My Name is Sumit')
It depends if you want to first remove the spaces and then pick every second letter or take every second letter and print it, unless it is a space:
s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))
Prints:
MnmiSmi
Maeiumt
You could alway create a quick function for it where you just simply replace the spaces with an empty string instead.
Example
def remove(string):
return string.replace(" ", "")
There's a lot of different approaches to this problem. This thread explains it pretty well in my opinion: https://www.geeksforgeeks.org/python-remove-spaces-from-a-string/
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
I'm building an analyzer for a series of strings.
I need to check how much each line is indented (either by tabs or by spaces).
Each line is just a string in a text editor.
How do I check by how much a string is indented?
Or rather, maybe I could check how much whitespace or \t are before a string, but I'm unsure of how.
To count the number of spaces at the beginning of a string you could do a comparison between the left stripped (whitespace removed) string and the original:
a = " indented string"
leading_spaces = len(a) - len(a.lstrip())
print(leading_spaces)
# >>> 4
Tab indent is context specific... it changes based on the settings of whatever program is displaying the tab characters. This approach will only tell you the total number of whitespace characters (each tab will be considered one character).
Or to demonstrate:
a = "\t\tindented string"
leading_spaces = len(a) - len(a.lstrip())
print(leading_spaces)
# >>> 2
EDIT:
If you want to do this to a whole file you might want to try
with open("myfile.txt") as afile:
line_lengths = [len(line) - len(line.lstrip()) for line in afile]
I think Gizmo's basic idea is good, and it's relatively easy to extend it to handle any mixture of leading tabs and spaces by using a string object's expandtabs() method:
def indentation(s, tabsize=4):
sx = s.expandtabs(tabsize)
return 0 if sx.isspace() else len(sx) - len(sx.lstrip())
print indentation(" tindented string")
print indentation("\t\tindented string")
print indentation(" \t \tindented string")
The last two print statements will output the same value.
Edit: I modified it to check and return 0 if a line of all tabs and spaces is encountered.
The len() method will count tab (\t) as one. In some case, it will not behave expectedly. So my way is to use re.sub and then count the space(s).
indent_count = re.sub(r'^([\s]*)[\s]+.*$', r'\g<1>', line).count(' ')
def count_indentation(line) :
count = 0
try :
while (line[count] == "\t") :
count += 1
return count
except :
return count