Issue in printing a right angle triangle in Python - python

I am trying to learn Python basics. I am designing a code that would print a triangle, code posted below. The expected output of the program must be a triangle from the right side not from the left which part of the code to modify to get the expected output.
The output of the program should not be like below
I want the output to be like this
Any help on this is highly appreciated. Thanks
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
rows = n
for num in range(rows+1):
for i in range(1, num+1):
if num % 2 == 0:
#print(end="" '#')
print('#',end="")
else:
#print(num)
print(num,end="")
print(" ")

We can use a list to create the elements (when it's an odd number just append the value in number times otherwise character '#' number times as the description said )of the triangle and then use a for loop to print them as below:
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
result = [idx*'#' if idx % 2 == 0 else f'{idx}'*idx for idx in range(1, n+1) ]
for i in range(len(result)):
print(' '*(n-i-1), result[i])
The result would be:
1
##
333
####
55555
Hope this can help you :)

Checking your code with the input (5) gives the output (1##333####55555 )
but the following code for the same input (5) gives the output (55555####333##1 )
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
rows = n
for num in range(rows, 0,-1):
for i in range(num+1, 1,-1):
if num % 2 == 0:
#print(end="" '#')
print('#',end="")
else:
#print(num)
print(num,end="")
print(" ")
Hope this answer your question

Related

How to keep track of console output lines in Python?

I'm trying to find the number of numbers divisble by 2 in 0-100, I have used a range() function and n1=n1+1 to generate 0 to 100, then with an if statement display only numbers wholely divisble by 2.
For the life of me I cannot find a way to count the number of times 0's are printed in the console, I googled count() but that seems to work for opening other files not the one you are in.
n1 = 1
for x in range(100):
dTwo = n1 % 2
if (int(dTwo) == 0):
print(n1)
n1 = n1 + 1 #generates 0 to 101
#how to I keep track of the number of 0s outputted in console after this step?
Any help would be greatly appreciated
count = 0
v = list()
for i in range(1, 101):
if i % 2 == 0:
print(i)
count += 1
v.append(i)
print(f'Number of values divisible by 2 = {count}')
print(f'Values that are divisible by 2: {v}')
As much as I get, I think you want to count number of zeros? If I am right then this is the code
count=0
while True:
y=input("Enter again : Y/N ")
if y=='Y':
n=int(input("Enter numbers as you wish :"))
if n==0:
count=count+1
elif y=='N':
break
print("Total 0's : ", count)

How do I get Python to print from 1 to user input?

I'm trying to solve the scenario with these conditions:
Ask the user to enter a number
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number. If it is an even number, do not display the number.
If the user enters a number that is 0 or less, display error
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
Your solution will be :
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run. I hope you understand.
You have to check the condition num <= 0 as soon as the user enters the number:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)

count divisors problem in python using while

i try to count divisor if number have 4 divisors will print "elegant number" else "not elegant number" but i have trouble while print it i have finished to show divisors from number but my program can't show elegant number or not. i have your opinion to fixed it. here my code:
N = int(input("enter number: "))
i = 1
factor = 0 # this for count divisors but doesn't right
while (i <= N):
if(N%i==0):
print(i)
factor+=i # this for count divisors but doesn't right
i+=1
if(factor==4):
print("elegant number")
else:
print("not elegant number")
i have put comment in line which line for count divisors.
I think the main issue inside the code was adding factor += i instead of factor += 1 (to account for a new divisor).
Also, the placement of the factor += 1 condition had to be inside the if-statement.
Here is an updated version of the code:
N = int(input("enter number: "))
factors = 0
for i in range(1,N+1): # Add N+1 to loop over "i=N" as well
if N%i == 0:
print(i)
factors += 1
if factors == 4 :
print("elegant number")
else:
print("not elegant number")
Please let me know in the comments section if you need further help. Cheers,
PS. Alternative version using a while-loop:
N = int(input("enter number: "))
factors = 0
i = 1
while i<=N:
if N%i == 0:
print(i)
factors += 1
i += 1
if factors == 4 :
print("elegant number")
else:
print("not elegant number")

hailstone program in python

i have to write a hailstone program in python
you pick a number, if it's even then half it, and if it's odd then multiply it by 3 and add 1 to it. it says to continue this pattern until the number becomes 1.
the program will need methods for the following:
accepting user input
when printing the sequence, the program should loop until the number 1.
print a count for the number of times the loop had to run to make the sequence.
here's a sample run:
prompt (input)
Enter a positive integer (1-1000). To quit, enter -1: 20
20 10 5 16 8 4 2 1
The loop executed 8 times.
Enter a positive integer (1-1000). To quit, enter -1: 30
30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
The loop executed 19 times.
Enter a positive integer (1-1000). To quit, enter -1: -1
Thank you for playing Hailstone.
right now i have this:
count = 0
def hailstone(n):
if n > 0
print(n)
if n > 1:
if n % 2 == 0:
hailstone(n / 2)
else:
hailstone((n * 3) + 1)
count = count + 1
i don't know what to do after this
Try to think in a modular way, make two functions: check_number() and user_call(). Check_number will verify if the current number in the loop is odd or even and the user_call() just wraps it to count how many times the loop did iterate.
I found the exercise in a great book called Automate Boring Stuff with Python, you have to check it out, if you don't know it already.
Here's my code. Try to use what serves you the best.
from sys import exit
def check_number(number):
if number % 2 ==0:
print(number // 2)
return(number // 2)
else:
print(number*3+1)
return number*3+1
def user_call(number):
count = 0
while number != 1:
count += 1
number = check_number(number)
return count
if __name__ == "__main__":
try:
number = int(input('Give a number \n'))
count = user_call(number)
print('count ',count)
except Exception as e:
exit()
you can use global
visit https://www.programiz.com/python-programming/global-keyword to learn more
import sys
res = []
def hailstone(number):
global res
if number > 1:
if number % 2 == 0:
res.append( number // 2 )
hailstone(res[len(res)-1])
else:
res.append(number * 3 + 1)
hailstone(res[len(res)-1])
return res
number = int(input('Enter a positive integer. To quit, enter -1: '))
if number <= 0 or number == 0:
print('Thank you for playing Hailstone.')
sys.exit()
else:
answers = hailstone(number)
for answer in answers:
print(answer)
print('The loop executed {} times.'.format(len(answers) + 1))
I used recursion to solve the problem.
Heres my code:
Edit: All criteria met
count = 0
list_num = []
def input_check():
number = int(input("Enter a positive integer (1-1000). To quit, enter -1: "))
if number >= 1 and number <= 1000:
hailstone_game(number)
elif number == -1:
return
else:
print("Please type in a number between 1-1000")
input_check()
def hailstone_game(number):
global count
while number != 1:
count += 1
list_num.append(number)
if number % 2 == 0:
return hailstone_game(int(number/2))
else:
return hailstone_game(int(number*3+1))
list_num.append(1) # cheap uncreative way to add the one
print(*list_num, sep=" ")
print(f"The loop executed {count} times.")
return
input_check()
Additional stuff that could be done:
- Catching non-integer inputs using try / except
Keep in mind when programming it is a good habit to keep different functions of your code separate, by defining functions for each set of 'commands'. This leads to more readable and easier to maintain code. Of course in this situation it doesn't matter as the code is short.
Your recursive function is missing a base/terminating condition so it goes into an infinite loop.
resultArray = [] #list
def hailstone(n):
if n <= 0: # Base Condition
return
if n > 0:
resultArray.append(n)
if n > 1:
if n % 2 == 0:
hailstone(int(n/2))
else:
hailstone((n * 3) + 1)
# function call
hailstone(20)
print(len(resultArray), resultArray)
Output
8 [20, 10, 5, 16, 8, 4, 2, 1]
Here's a recursive approach for the problem.
count=0
def hailstone(n):
global count
count+=1
if n==1:
print(n)
else:
if n%2==0:
print(n)
hailstone(int(n/2))
else:
print(n)
hailstone(3*n+1)
hailstone(21)
print(f"Loop executed {count} times")

How to not count negative input

is there a way to keep the counter going without counting the negatives and only to stop when the input is zero?
count = 0
total = 0
n = input()
while n != '0':
count = count + 1
total = total + int(n) ** 2
n = input()
print(total)
Here is an example of execution result.
Input: -1 10 8 4 2 0
Output: 184
Since you want only number to enter the loop you can use isnumeric() built in function to check that.
You need if() : break here.
num = input()
...
while(isnumeric(num)):
...
if(num == "0"):
break;
The response you wait for is:
ignore negative number
count positive numbers
stop when input is 0
count = 0
total = 0
n = int(input())
while (n != 0):
count += 1
if (n > 0):
total = total + n**2
num = int(input())
print(total)
Your code was already OK except that you did not cast the number n into int and you did not test n to take away negative values.
Execution:
When you enter -1 10 8 4 2 0, it should show 184
You can parse your Input to an integer (number) and check if it's larger than zero:
count = 0
total = 0
num = int(input())
while number != 0:
if number < 0:
continue
count += 1
total = total + num**2
num = int(input())
print(total)
The difference between pass, continue, break and return are:
pass = ignore me an just go on, usefull when you create a function that has no purpose yet
continue = ignore everything else in the loop and start a new loop
break = break the loop
return = end of a function - a return statement can be used to give an output to a function but also as a way to break out of the function like the break statement does in loops.

Categories