Making triangles in Python - python

Below is a code I made in Python for our lab activity which makes a triangle.
side = input("Input side: ")
def triangle(x):
print ((x - 1)*" "),"*"
asterisk = "*"
space = side
for i in range(x):
asterisk = "**" + asterisk
space = (space-1) * " "
print space,asterisk
triangle(side)
The output should be this:
*
***
*****
I got the number of asterisks on each row correctly, but I cannot figure out how to make the necessary amount of spaces to make it look like a triangle. Using the above code, which I think might be the solution, always produces an error at line 9. Any help I appreciated. (I'm new here so if I violated some rules please let me know.) Thanks and good day!

You are getting the error(TypeError) because you are assigning the space variable with a string type, and then you are subtracting it in the next loop. Edited code would look like this (In python 2.7) and Never mix 4 spaces and 8 spaces indentation.
side = input("Input side: ")
def triangle(x):
print ((x)*" "),"*"
asterisk = "*"
spaces = side
for i in range(x):
asterisk = "**" + asterisk
spaces -= 1
print ' ' * spaces,
print asterisk
triangle(side)

I write a new one in python3.5,And it may be suit for you.But it is not prefect
side = 4
def triangle(x):
for y in range(1,x):
s = 2*y - 1
b = x - y
print(" "*b+"*"*s)
triangle(side)
Output:
*
***
*****

Here is the code to have an isosceles triangle:
def print_triangle(n):
for i in range(1, n+1):
print (" "*(n-i), end=" ")
print (("*"*i)+(i*"*"))
print(print_triangle(6))
Output:
**
****
******
********
**********
************
None

Related

how to I make the code to print the numbers given and and show what it equals

I tried to make just add print(a+b) and I only got what it equals I don't know what to do I can't find it or look for it online.
You are mixing up printing a string vs. printing an expression.
Printing a string like print('hello world') will print the literal message because you've indicated it's a string with quotes.
However, if you provide an expression like print(a+b), it will evaluate that expression (calculate the math) and then print the string representation of that evaluation.
Now, what you want is actually a mix of both, you want to print a string that has certain parts replaced with an expression. This can be done by "adding" strings and expressions together like so:
print(a + '+' + b + '=' + (a+b))
Notice the difference between + without quotes and '+' with quotes. The first is the addition operator, the second is the literal plus character. Let's break down how the print statement parses this. Let's say we have a = 5 and b = 3. First, we evaluate all the expressions:
print(5 + '+' + 3 + '=' + 8)
Now, we have to add a combination of numbers with strings. The + operator acts differently depending on context, but here it will simply convert everything into a string and then "add" them together like letters or words. Now it becomes something like:
print('5' + '+' + '3' + '=' + '8')
Notice how each number is now a string by the surrounding quotes. This parses to:
print('5+3=8')
which prints the literal 5+3=8
You mean like that:
a = int(input("Give me a number man: "))
b = int(input("Give me another number: "))
print(f'print({a} + {b}) = {a + b}')
print(f'print({a} - {b}) = {a - b}')
print(f'print({a} * {b}) = {a * b}')
print(f'print({a} // {b}) = {a // b}')
print("Look at all those maths!")
Output
Give me a number man: 3
Give me another number: 2
print(3 + 2) = 5
print(3 - 2) = 1
print(3 * 2) = 6
print(3 // 2) = 1
Look at all those maths!

4.16 LAB: Warm up: Drawing a right triangle

This program will output a right triangle based on user specified height triangle_height and symbol triangle_char.
(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character.
(2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character.
I'm having trouble figuring out how to create a space between my characters. Example input is % and 5. My code is:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range (triangle_height):
print((triangle_char) * (i + 1))
my output is:
%
%%
%%%
%%%%
%%%%%
while expected output is:
%
% %
% % %
% % % %
% % % % %
You need to use join(). This would work:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)))
It is adding spaces between every character because strings are iterable.
This may be optimized a bit by having a list of the characters and appending 1 character in each iteration, rather than constructing triangle_char * (i+1) every time.
This should fix the white space errors:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)) + ' ')
for i in range(triangle_height+1):
print(f'{triangle_char} '*i)
I see the popular way so far is using join, but another way while trying to stay true to the original idea is you simply can add a white space after each character. See below:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range(triangle_height):
print((triangle_char + ' ') * (i + 1))
There are some really good suggestions on here. Another approach is to use an incremented variable in a while loop as shown below:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
i = 0
while (i <= triangle_height):
print((triangle_char + ' ') * i)
i += 1
With the example above, i iterates until it is equal to triangle_height and uses polymorphism to generate a quantity of (triangle_height + ' ') based on the value of i. This will generate the right triangle this lab requires. The space is used to format the triangle per lab requirements.
Another method is using the .join() feature, and it certainly would work well here, but is not taught until CH7 of this book where you learn about input and CSV files. I am unsure if your professor would approve of using this, and I am only saying this because my professor was strict about using material not covered.
An additional method mentioned already is to use a for loop with the use of the range() feature containing an expression:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
for i in range((triangle_height + 1)):
print((triangle_char + ' ') * i)
The end point of range() being just triangle_height would not suffice because the value specified as the end point is not included in the sequence. This would make a right triangle with a height of 4 even if triangle_height was 5 Therefore, you must use the expression (triangle_height + 1). From there, the output is set up similarly to my first solution.
Try adding a whitespace in the print statement.
height = int(input())
symbol = (input())
print()
for i in range(height): #Loop for every index in the range 0-height
print((symbol + ' ') * (i + 1)) #Add whitespace to symbol

How to separate strings multiplied by integer in Python?

Let's say we have a text "Welcome to India". And I want to multiply this string with 3, but to appear with comma delimitation, like "Welcome to India, Welcome to India, Welcome to India". The thing is I know this piece of code could work:
a = 'Welcome to India'
required = a * 3 # but this code is not comma-delimited.
Also, this piece of code doesn't work as well
required = (a + ", ") * 3 # because it puts comma even at the end of the string
How to solve this problem?
", ".join(["Welcome to India"]*3)
Based on the part of your code that you say doesn't work well because it adds a comma to the end, you can modify it like this:
required = (a + ", ") * 2 + a
Or if you don't like it, you can use sum instead of multiply, it's not the optimal way, for sure, but it will work:
a = 'Welcome to India'
required = a + ", " + a + ", " + a
Define Function and you can use it.
def commaFunc(value, count):
buffer = []
for x in range(count):
buffer[x] = value
return ",".join(buffer)

How do I add spaces between characters in an output statement when I am multiplying

For this program, the goal is to output a right triangle based on a user specified height triangle_height and symbol triangle_char. We are meant to create a triangle out of a user-inputted height and character, created by repeating a string to make a new string. So far I have:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for x in range(1, triangle_height + 1):
print(x * triangle_char)
Which runs and outputs a tringle of the inputted height made of the inputted character however, the printed triangle is supposed to have spaces between every character
(ex: * not: *
* * **
* * * ***
How do I get spaces in between the printed characters?
You can just add a ' ' character after triangle_char like so:
for x in range(1, triangle_height + 1):
print(x * (triangle_char + ' '))
This does not produce trailing spaces at the ends of the lines.
Instead it uses the very pythonic way of joining lists
triangle_height = 5
triangle_char = "*"
for x in range(triangle_height):
print(" ".join(triangle_char * (x+1)))

How can I prevent print slides when the value changes?

I'm making a fighting game with HP bars etc. I did almost everything except HP bars. I simply can't stop it slides when the first HP bar's value changes. How can I fix it?
def get_hpbar(hpoints, hpoints2, name1, name2):
bar1 = hpoints2 / 2
bar2 = hpoints / 2
print(name1, " " * 64, name2)
print("HP[{}]:".format(hpoints2), int(bar1) * "|", " ", end="")
print("HP[{}]:".format(hpoints), int(bar2) * "|")
Example of unwanted situation
Example of wanted display
Thanks in advance!
One easy way to solve the problem without worrying about formatting is just add spaces to make the gap constant.
def get_hpbar(hpoints, hpoints2, name1, name2):
bar1 = hpoints2 / 2
bar2 = hpoints / 2
print(name1, " " * 64, name2)
print("HP[{}]:".format(hpoints2), int(bar1) * "|", int(50-bar1) * " " ," ", end="")
print("HP[{}]:".format(hpoints), int(bar2) * "|")
Since you're relying on character count for alignment, you likely want to "pad" the hp bar with empty slots (spaces) to keep them at 100 size, while reducing the printed characters at will.
e.g.
|||||||||| < before hit
|||||| < after hit (fill with spaces)
You can use the string method ljust to help you with that. e.g.
hp_bar = ('|' * hp).ljust(100, ' ')
print(hp_bar)
The ljust method justifies content to the left (ljust = left justify) by padding the right with character until the string reaches the specified size.

Categories