I am trying to create an arrow out of asterisk's, where the amount of columns is entered by the user. Yes, I do know how to use for loops to accomplish this:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
for x in range(1, columns):
for x in range(x):
print(" ", end="")
print("*")
for x in range(columns,0,-1):
for x in range(x):
print(" ", end="")
print("*")
#output looks like
"""
How many columns? 3
*
*
*
*
*
"""
However my question is, how would I accomplish the same outcome using only while loops?
Thanks
Edit: I was going to post what I had thus far in trying to work it out myself, but it is now of no use!
Thank you all for your efficient varying answers! Much appreciated!
Just for fun, here's a version that doesn't loop using indexing.
def print_arrow(n):
a = '*'.ljust(n + 1)
while a[-1] != '*':
print(a)
a = a[-1] + a[:-1]
a = a[1:]
while a[0] != '*':
a = a[1:] + a[0]
print(a)
# Test
print_arrow(4)
output
*
*
*
*
*
*
*
This should do:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
while x < columns:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x += 1
x = columns
while x > 0:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x -= 1
First, it's better to use functions. And easier if you know that character*number returns that character concatenated number times.
Example:
'*'*10
returns
'**********'
So your program using whiles would follow the same logic.
def print_arrow(k):
i = 0
while(i < k-1):
print(i*' ' + '*')
i +=1
while(i >= 0):
print(i*' ' + '*')
i -= 1
The first while prints the upper part, the last one uses the fact that i = k-1, so just do same in the reversed order.
Example:
print_arrow(3)
returns
*
*
*
*
*
n = int(input( ))
n1 = n//2 + 1
i = 1
while i <= n1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i += 1
i = n - n1
while i >= 1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i -= 1
Arrow pattern of asterisk
-Remember the n value here is always odd
for n = 5
output will be
Related
Trying to make a program that asks the user for a height and a character, and then outputs a hollow triangle to that height using that character. Was trying to firstly make a solid triangle, then solve it from there, but so far have only managed to make a half triangle.
Also, using only for loops and no '*' operator
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < rows:
print(C, end="")
count += 1
print()
rows += 1
this results in this:
*
**
***
****
*****
my goal is this:
*
* *
* *
* *
*********
any help would be appreciated!
Slightly changed your script:
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < 2*rows-1:
count += 1
if count == 1 or count == 2*rows-1 or rows == H:
print(C, end="")
else:
print(" ", end="")
print()
rows += 1
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
for i in range(H):
for j in range(H - i):
print(' ', end='')
for j in range(2 * i + 1):
if j == 0 or j == 2 * i or i == H - 1:
print(C, end='')
else:
print(' ', end='')
print()
There's already an answer, but considering that I had fun doing this little program, and that our solution are not the same :
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 0
while rows <= H:
cols = 0
if rows == H:
while cols <= H*2:
print(C, end="")
cols += 1
else:
while cols <= H*2:
if rows + cols == H or cols - rows == H:
print(C, end="")
else:
print(" ", end="")
cols += 1
print()
rows += 1
Note that I did this with for loops, and just swapped to while loops to paste it here.
The way to get a hollow triangle is to print spaces in a loop.
If you observe the output you need, you'll see that except for the top and bottom lines, every line has only 2 asterisks (*). That means you need a logic that handles spaces.
There are several ways to write the logic, such as treating each vertical halves as blocks of fixed length and just varying the position of the star or actually counting the spaces for each line. You can explore the different ways to achieve what you need at your convenience. I'll present one soln.
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if len(C) != 1:
C = "*"
rows = 1
count = 0
while rows < H:
str = ""
for i in range(H - rows):
str += " "
str += C
if rows > 1:
for i in range(2 * rows - 3):
str += " "
str += C
print(str)
rows += 1
str = ""
for i in range(2 * H - 1):
str += C
print(str)
I have made a change about checking the character. You should not allow characters of more than length 1. Otherwise, the spacing will get messed up
These exercises are meant for you to understand the logic and get comfortable with manipulating code, so do try different variations
This is probably not the most optimized solution but, remember that printing is in general slow as it has to interact with a peripheral (monitor), so try to print in bulk whenever possible. This improves the speed
I need help fixing my code, see below for problem.
I have to write a function that prints out the L shape made up of *'s. Also, the parameter M is an integer between 1 and 80 and is the rows of the shape. The output needs to be N rows, the last of which should comprise N letters of L.
My user input should be the desired rows but its just printing the range, and even that looks a little off. Please assist, if you can... this is what I have so far:
M = int(input())
def solution(M):
result =""
if M > 80:
for row in range(1, 80):
for column in range(1, 80):
if (column == 1 or (row == 1 and column != 0 and column < 1)):
result = result + "*"
else:
result = result + "\n"
print(result)
solution(M)
This is just printing * for each row, unless the row = M in which case it is printing "*" * M and exiting if the value is >= 80 or <= 1 (since you said between 1-80):
import sys
print("Please enter an integer between 1-80:")
M = int(input())
def solution(N):
if N >= 80 or N <= 1:
sys.exit("Please run again using an integer between 1-80")
result = ""
for row in range(1, N+1):
if row < N:
result = "*"
print(result)
elif row == N:
result = "*" * N
print(result)
solution(M)
Then when you run:
[dkennetz#nodecn001 tmp]$ python3 fun.py
Please enter an integer between 1-80:
4
*
*
*
****
M = int(input())
def solution(M):
result_str=""
for row in range(0,M+1):
for column in range(0,M+1):
if (column == 1 or (row == M and column != 0 and column < M)):
result_str=result_str+"*"
else:
result_str=result_str+" "
result_str=result_str+"\n"
print(result_str)
solution(M)
https://ideone.com/UoGj2n
https://www.w3resource.com/python-exercises/python-conditional-exercise-21.php
You can try with this solution. I hope that it's clear enough:
SYMBOL = '*'
def solution(M, N):
result = []
# validations
if M > 80:
M = 80
if N > 80:
N = 80
for row in range(1, M + 1):
if row < M:
result.append(SYMBOL)
else:
# last row
result.append(''.join([SYMBOL for column in range(1, N + 1)]))
return result
# generate rows
result = solution(10, 5) # TODO: use values from input() instead
# print result
for row in result:
print(row)
This is my code, it outputs a multiplication table but it's not what I wanted!
num = int(input("Multiplication using value? : "))
while num <= 10:
i = 1
while i <= num:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
print("\n")
num = num + 1
I am basically creating a multiplication table from the user's input from 1-9.
Ex. If the user inputs "3",
I should get this output:
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9
The reason why you have an infinite loop on your hands is because you are comparing i to num, while also increasing num on every run. If you make sure i is always <= 10, you get your desired output:
while num <= 10:
i = 1
while i <= 10:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
num = num + 1
print("\n")
Even if the code you posted is not pythonic at all (it is very close to what could be written in C language), it nearly works: with minimum modifications, it can be fixed as follows to give your expected ouput:
numInput = int(input("Multiplication using value? : "))
num = 1
while num <= numInput:
i = 1
while i <= numInput:
product = num*i
print(num, " * ", i, " = ", product)
i = i + 1
print("") # no need to add explicit newline character because it is automatically added
num = num + 1
In a more pythonic way, you can also do the following:
numInput = int(input("Multiplication using value? : "))
for i in range(1,numInput+1):
for j in range(1,numInput+1):
print(i, " * ", j, " = ", i*j)
print("")
For this problem it's easier to use for loops.
num = int(input("Multiplication using value? : "))
for left in range(1,num+1): # 1st loop
for right in range(1,num+1): # 2nd loop (nested)
print(left, " * ", right, " = ", left * right)
print() # newline
To understand this problem, look at the two multiplicands: left and right.
Left multiplicand goes from (1-->num), hence the first for loop.
Then, for each value of the left multiplicand, the right multiplicand goes from (1-->num), hence the 2nd loop is nested inside the first loop.
You've lots of logical error. Please have a look at this updated code:
num = int(input("Multiplication using value : "))
i=1 #you haven't initialized this variable
while i <=num:
j=1
while j <= num:
product = i*j #updated
print(i, " * ", j, " = ", product, "\n") #updated
j = j + 1
print("\n")
i = i + 1
Output (for input 3):
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
In Python 3.6+, you can use f-strings with a nested for loop:
num = int(input("Multiplication using value? : "))
for i in range(1, num+1):
for j in range(1, num+1):
print(f'{i} * {j} = {i*j}')
Multiplication using value? : 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
multiplication table using while loop in python
num = int(input("enter the number= "))
i = 1
while i<=10:
print(num, "X", i, "=", num * i)
i = i+1
output
enter the number= 33
33 X 1 = 33
33 X 2 = 66
33 X 3 = 99
33 X 4 = 132
33 X 5 = 165
33 X 6 = 198
33 X 7 = 231
33 X 8 = 264
33 X 9 = 297
33 X 10 = 330
num = int(input("Enter the number: "))
i = 1
print("Mulltiplication of number:", num)
while i<=10:
print(f"{num}X{i}={num*i}")
i = i + 1
Multiplication table 1 to 10
for x in range(1,11):
for y in range(1,11):
print(x*y, end='\t')
print()
print()
input any number to get your normal multiple table(Nomenclature) in 10 iterate times.
num = int(input("Input a number: "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)
num = int(input('Enter the number you want the multiplication table for:'))
i=1
while i<=10:
product = num*i
print(product)
i=i+1
print('Thank you')
Creating a multiplication table using while loop is shown below:
b = int(input('Enter the number of the multiplicaction table : '))
print('The multiplication table of '+ str(b) + 'is : ')
a=0
while a<=11:
a=a+1
c= a*b
print( str(b)+' x '+str(a)+' ='+str(c))
print('done!!!!')
To create a multiplication table in python:
name=int(input("Enter the number of multiplication"))
i=1
while(i<=10):
print(str(name)+"X"+str(i)"="+str(name*i))
i=i+1
Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?
1
232
34543
4567654
567898765
678901109876
This is the code I made:
c = -1
for y in range(1, 7):
print()
print((6-y) * " ", end="")
c += 1
for x in range(1, y+1):
print(y%10, end="")
y += 1
while y - c > 2:
print(y-2, end="")
y -= 1
First of all, I'm guessing that you didn't really want to print that y value of 10; that you really wanted the base-10 reduction to 0. Note that you have an extra character in the pyramid base.
Do not change the value of a loop parameter while you're inside the loop. Specifically, don't change y within the for y loop.
Get rid of c; you can derive it from the other values.
For flexibility, make your upper limit a parameter: you have two constants (6 and 7) that depend on one concept (row limit).
Here's my version:
row_limit = 7
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " ", end="")
for x in range(y, 2*y):
print(x%10, end="")
for x in range(2*(y-1), y-1, -1):
print(x%10, end="")
print()
Output:
1
232
34543
4567654
567898765
67890109876
If you really want to push things, you can shorten the loops with string concatenation and comprehension, but it's likely harder to read for you.
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " " + ''.join([str(x%10) for x in range(y, 2*y)]) + \
''.join([str(x%10) for x in range(2*(y-1), y-1, -1)]), end="")
print()
Each of the loops is turned into a list comprehension, such as:
[str(x%10) for x in range(y, 2*y)]
Then, this list of characters is joined with no interstitial character; this forms half of the row. The second half of the row is the other loop (counting down). In front of all this, I concatenate the proper number of spaces.
Frankly, I prefer my first form.
Here's my implementation.
Python 2:
def print_triangle(n):
for row_num in xrange(1, n + 1):
numbers = [str(num % 10) for num in xrange(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print '{}{}'.format(' ' * (n - row_num), num_string)
Python 3:
def print_triangle(n):
for row_num in range(1, n + 1):
numbers = [str(num % 10) for num in range(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print('{}{}'.format(' ' * (n - row_num), num_string))
Input:
print_triangle(5)
print_triangle(6)
print_triangle(7)
Output:
1
232
34543
4567654
567898765
1
232
34543
4567654
567898765
67890109876
1
232
34543
4567654
567898765
67890109876
7890123210987
n = int(input())
i = 1
while i <= n:
j = 1
spaces = 1
p = i
while spaces <= n - i:
print (" ", end ="")
spaces += 1
while j <= i:
print(p, end = "")
j += 1
p += 1
p -= 2
while p >= i:
print(p, end = "")
p -= 1
print()
i += 1
Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(
EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')
edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have
ar = [1, 2, 3]
and
total = 5
program should display 2, 3 pair. But it will not find 1+3 for total=4.
Here are some general advices:
There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format
print('%d, %d'.format(ar[k], ar[k])
or print result as tuple
print(ar[k], ar[l])
Use for k in range(num) instead of while
hasValue is better to be boolean value
Well, here is my solution (python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
This is how to do for-loops in python:
for x in range(10):
# code for the for loop goes here
This is equivalent to:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
... in C++
(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.
Here is what I think you wish to do:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
or slightly more python way:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1