I am trying to print these two strings alternatively, but cannot find a way around it without using end=''. I am trying to use as little strings as possible, my goal is to use only 2 strings.
num_of_stars = int(input("How many stars would you like on each line?:
"))
lines1 = 0
lines2 = 0
alternator = 0
def line1(num_of_stars):
for i in range(num_of_stars):
print("*", end=' ')
def line2(num_of_stars):
for i in range(num_of_stars):
print(" *", end='')
while lines1 <= 4 and lines2 <= 4:
if alternator == 0:
line1(num_of_stars)
lines1 += 1
alternator = 1
elif alternator == 1:
line2(num_of_stars)
lines2 += 1
alternator = 0
My results have just been this: * * * * * * * * * * * ** * * * * * * * * * * ** * * * * * * * * * * ** * * * * * * * * * * ** * * * * *
It's not clear what you want.
But you probably don't want to use the print( ... , end=...) technique
shown in your code.
It would be much simpler to assign
stars = ['*'] * num_of_stars
line = ' '.join(stars)
and then
for i in range(4):
indent = ' '[:i % 2]
print(indent + line)
The indent string will be empty or a blank,
according to whether i is even or odd.
First of all, the end of the line 2 function is just a blank space, which explains why there are groups of 2 stars grouped together at intervals.
Try this:
num_of_stars = int(input("How many stars would you like on each line?: "))
lines1 = 0
lines2 = 0
alternator = 0
def line1(num_of_stars):
for i in range(num_of_stars):
print("*", end="")
print("\n")
def line2(num_of_stars):
for i in range(num_of_stars):
print("*", end="")
print("\n")
while lines1 <= 4 and lines2 <= 4:
if alternator == 0:
line1(num_of_stars)
lines1 += 1
alternator = 1
elif alternator == 1:
line2(num_of_stars)
lines2 += 1
alternator = 0
Related
I am want to replace a specific part of the string while using textwrap. But I am getting an unwanted line break. I have tried a lot of ways but still, it is not working. here is my code.
import textwrap
import math
def wrap(string, max_width):
wrapper = textwrap.TextWrapper(width = max_width)
word_list = wrapper.fill(text = string)
return word_list
height, width = map(int,input().split())
square = height * width
i = 0
x = []
while i < square:
x.append("-")
i += 1
k = 0
while k < math.floor(height / 2):
line = math.floor(width / 2) + width * k
x[line] = '|'
x[line + 1]= "."
x[line - 1] = "."
for h in range(1, k + 1):
f = h * 3
line_plus = line + f
line_minus = line - f
x[line_plus] = '|'
x[line_minus] = '|'
x[line_minus - 1] = '.'
x[line_plus - 1] = '.'
x[line_minus + 1] = '.'
q = line_plus + 1
x[q] = '.'
k += 1
a = 0
while a < math.floor(height / 2):
line = math.floor(width / 2) + width * a
line_end = (math.floor(width / 2) + width * a) * (-1)
x[line_end - 1] = '|'
if line > width:
x[line_end + 2] = '|'
x[line_end - 4] = '|'
a += 1
listToStr = ''.join([str(elem) for elem in x])
welcome_pos = math.floor(height / 2) * width + (math.floor(width / 2) - math.floor(7 / 2))
s = listToStr[ 0: welcome_pos] + "welcome" + listToStr[welcome_pos + 7:]
print(wrap(listToStr, width) + "\n")
print(wrap(s, width))
my input is 7 21
Output:
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.
----------welcome----
----------|--|--|----
----------|--|--|----
-------------|-------
---
this is my output. But it is giving a space at line 3 which I don't want. I don't know why this is happening. Please help me.
Maybe this is what you want?
code:
#(above the same)
print(wrap(listToStr,width*height))
print(wrap(s,width*height))
result:
5 4
-..|..|..||--|--||--
-..|..|welcome--||--
So I have an application in Python that calculates the variable number in the "PV = nRT" chemical equation. The code is like this:
r = 0.082
# Variables
p = float(input('Pressure = '))
p_unit = input('Unit = ')
print('_____________________')
v = float(input('Volume = '))
v_unit = input('Unit = ')
print('_____________________')
n = float(input('Moles = '))
print('_____________________')
t = float(input('Temperature = '))
t_unit = input('Unit = ')
# Unit Conversion
if p_unit == 'bar':
p = p * 0.987
if v_unit == 'cm3':
v = v / 1000
if v_unit == 'm3':
v = v * 1000
if t_unit == 'c':
t = t + 273
if t_unit == 'f':
t = ((t - 32) * (5 / 9)) + 273
# Solve Equation
def calc():
if p == 000:
return (n * r * t) / v
if v == 000:
return (n * r * t) / p
if n == 000:
return (p * v) / (r * t)
if t == 000:
return (p * v) / (n * r)
and then at the end I run the function to get the result. But the problem is I want to convert the result to a Scientific Number (e.g. 0.005 = 5 x 10^-3). I tried the solution below:
def conv_to_sci(num):
i = 0
if num > 10:
while num > 10:
num / 10
i = i - 1
if num < 10:
while num < 10:
num * 10
i = i + 1
return num + "x 10^" + i
but it didn't work. Any questions?
I'd just use numpy to get scientific notation
import numpy as np
num = 0.005
num_sc = np.format_float_scientific(num)
>>> num_sc
'5.e-03'
Use str.format
"{:.0e}".format(0.005)
This will print:
'5e-03'
Or,
def conv_to_sci(num):
i = 0
while int(num) != num:
num *= 10
i += 1
return "{0} x 10^{1}".format(int(num), i)
conv_to_sci(0.005)
Will give: '5 x 10^3'
I want to print this pattern in Python 3 (I'm a beginner):
What i have tried :
n = 5
for x in range(1, (n+5) //2 + 1):
for y in range( (n+5) //2 - x):
print(" ", end = "")
for z in range( (x*2)-1 ):
print("*", end = "")
print()
for x in range( (n+5)// 2 + 1, n + 5):
for y in range(x - (n+5) //2):
print(" ", end = "")
for z in range( (n+5 - x) *2 - 1):
print("*", end = "")
print()
But the result is like this:
How can I make the middle hollow like in the image?
Thanks.
The coordinates of the points on the hollow rhombus satisfies |x|+|y|==m (where m = n-1). Therefore, you could use
In [29]: m = n-1; print('\n'.join([''.join(['*' if abs(row)+abs(col)==m else ' ' for col in range(-m,m+1)]) for row in range(-m,m+1)]))
*
* *
* *
* *
* *
* *
* *
* *
*
or, equivalently, but without list comprehensions:
n = 5
m = n-1
for row in range(-m, m+1):
for col in range(-m, m+1):
if abs(row) + abs(col) == m:
c = '*'
else:
c = ' '
print(c, end='')
print()
To make the solid rhombus, simply change the condition to abs(row) + abs(col) <= m.
With recursion:
def print_stars(i,n):
if i:
print( ' '*(n-i-1) + '*' + ' '*(2*i-1) + '*')
else:
print( ' '*(n-1) + '*')
# recursive
def r(n, i=0):
print_stars(i,n) # up
if i<n-1:
r(n, i+1) # recurse
print_stars(i,n) # down
# start
r(5)
prints:
*
* *
* *
* *
* *
* *
* *
* *
*
Simple python code without using functions
rows = 7
for i in range(1, rows + 1):
for j in range(1, rows - i + 1):
print(end = ' ')
for k in range(1, 2 * i):
if k == 1 or k == i * 2 - 1:
print('*', end = '')
else:
print(' ', end = '')
print()
for i in range(rows - 1, 0, -1):
for j in range(1, rows - i + 1):
print(' ', end = '')
for k in range(1, 2 * i):
if k == 1 or k == i * 2 - 1:
print('*', end = '')
else:
print(' ', end = '')
print()
Output:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
How to make a "Hollow Diamond In Python 3.10"
You can use this code here:
my personal code
I am new to python, please someone help to draw a shape like below. The program have to take the number of star as an input.
number of star = 7
* *
** **
*** ***
********
*** ***
** **
* *
My code:
count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, pattern_size):
pattern = list(" " * pattern_size)
pattern[:t] = "*" * t
pattern[-t:] = '*' * t
print(''.join(pattern))
star count : 9
* *
** **
*** ***
**** ****
**********
**********
**********
**********
**********
Here's a easy-to-understand example using two for-loops with your approach: One just the inverse of another
count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, int(pattern_size/2)):
pattern = list(" " * pattern_size)
pattern[:t] = "*" * t
pattern[-t:] = '*' * t
print(''.join(pattern))
for t in range(int(pattern_size/2), 0, -1):
pattern = list(" " * pattern_size)
pattern[:t] = "*" * t
pattern[-t:] = '*' * t
print(''.join(pattern))
And a more advanced method would be to use the string method .center() like so:
count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, int(pattern_size/2)):
print((" " * (pattern_size-t*2)).center(pattern_size, '*'))
for t in range(int(pattern_size/2), 0, -1):
print((" " * (pattern_size - t * 2)).center(pattern_size, '*'))
Just like my comment, this is the complete code:
count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, pattern_size):
pattern = list(" " * pattern_size)
len_t = t if t <= (pattern_size / 2) else (pattern_size - t)
pattern[:len_t] = "*" * len_t
pattern[-len_t:] = '*' * len_t
print(''.join(pattern))
Hope this help.
I can only create a filled diamond, i can't figure out how to get it unfilled.`#
# The size of the diamond
N = 7
# The top part (includes the middle row)
i = 0
while i < N // 2 + 1:
print((N // 2 - i) * " " + (2 * i + 1) * "*")
i += 1
# The bottom part
i = 0
while i < N // 2:
print(" " * (i + 1) + "*" * (N - 2 - 2 * i))
i += 1
You just need to print (2*i-1) spaces in between '*' characters instead instead of only '*'. And have to deal with the very top and very bottom separately:
# The size of the diamond
N = 7
# The top part (includes the middle row)
print((N // 2) * " " + '*')
i = 1
while i < N // 2 + 1:
print((N // 2 - i) * " " + '*' + (2 * i - 1) * " " + '*')
i += 1
# The bottom part
i = 0
while i < N // 2 - 1:
print(" " * (i + 1) + '*' + " " * (N - 4 - 2 * i) + '*')
i += 1
print((N // 2) * " " + '*')
*
* *
* *
* *
* *
* *
*
# The size of the diamond
N = 7
# The top part (includes the middle row)
i = 0
while i < N // 2 + 1:
print((N // 2 - i) * " " + "*" +( ((2 * i -1) * " " + "*") if i > 0 else ""))
i += 1
# The bottom part
i = 0
while i < N // 2:
print(" " * (i + 1) + "*" + ( ( " " * (N - 2 - 2 * i - 2) + "*") if i < (N//2-1) else ""))
i += 1
simply print two less spaces than you were printing *'s inbetween two *'s unless on top or bottom.
def diamond(size, sym_func):
s = ''
for row in xrange(size):
for column in xrange(size):
if row > size//2: # if bottom half reflect top
row = size - row - 1
if column > size//2: # if right half reflect left
column = size - column - 1
s += sym_func(row,column,size)
s+= '\n'
return s
def solid(row,column,size):
if column >= (size // 2 - row):
return "*"
return " "
def hollow(row,column,size):
if column == (size // 2 - row):
return "*"
return " "
def circle(row,column,size):
if (size//2-row)**2+(size//2-column)**2 <= (size//2)**2:
return '*'
return ' '
print diamond(size=7, sym_func=solid) # The size of the diamond
print diamond(size=7, sym_func=hollow) # The size of the diamond
print diamond(size=17, sym_func=circle) # The size of the diamond
look at the difference between the hollow and solid symbol functions if you use a >= then you get a solid thing if you use a == for exact comperison then it is just the parimiter