No output when using nested for loops inside if statements - python

I'm trying to print out a series of patterns based off of the user input. However, when I add an if statement or while loop to it, I get no output even if I selected the correct number. The patterns work if I don't add the loops to it. I'm new to python and don't understand why it isn't printing anything out.
num_draw = input("Please enter the number of the design you would like[1-6] or -1 to quit: ")
#while num_draw != -1:
if num_draw == 1:
for i in range(0, 5):
for j in range(0, i+1):
print("* ",end="")
print()
elif num_draw == 2:
#2
size = 5
isize = size - 2
print ('*' * size)
for i in range(isize):
print ('*' + ' ' * isize + '*')
print ('*' * size)
elif num_draw == 3:
for i in range(5):
for j in range(5):
print(" *"[(j + i + 1)%2], end=' ')
print()
elif num_draw == 4:
for i in range(0, 5):
for j in range(0, i+1):
print("* ",end="")
print()
elif num_draw == 5:
for i in range(0, 5):
for j in range(5, i, -1):
print("# ", end="")
print()
elif num_draw == 6:
k = 8
for i in range(0, 5):
for j in range(0, k):
print(end=" ")
k = k - 2
for j in range(0, i+1):
print("* ", end="")
print()

You were almost correct. The problem was that the keyboard input is always of type str (string, by default) and you are comparing it to numbers of type int (integer). For ex. if you enter 1, then num_draw='1' and so you are checking if '1' == 1: which is False. Similarly, none of your if or elif is True because you are comparing str type with int type.
To make your code work, convert your input type to int as follows:
num_draw = int(input("Please enter the number of the design you would like[1-6] or -1 to quit: "))
Output
Please enter the number of the design you would like[1-6] or -1 to quit:
1
*
* *
* * *
* * * *
* * * * *

As mentioned your input needs to be an int to make proper comparisons. As for your while loop while num_draw != -1: is correct but you need to move your input prompt within the loop so user can reelect an option. setting num_draw = 'x' is just to create a qualifying condition to start the loop
num_draw = 'x'
while num_draw != -1:
num_draw = int(input("Please enter the number of the design you would like[1-6] or -1 to quit: "))

Related

Write a program that prompts the user to enter an integer number from 1 to 9 and displays two pyramids

I have the code for the 1st and the second pyramid, I just don't know how to put it together like how the question is asking. The first code below is for pyramid 1 and second is for the 2nd pyramid.
`
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
`
`
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
`
You just need to run the second loop after the first loop. Also your code for the second pyramid is incorrect so I changed that.
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
for k in range(i,0,-1):
print(k, end=' ')
for k in range(2,i+1):
print(k, end=' ')
count = 0
print()
Since the algorithm for constructing both pyramids is similar, it is better to make a function
def pyramid(n_rows, s_type='*'):
max_width = n_rows * 2 - 1
for i in range(0, n_rows):
stars = i * 2 + 1
side = (max_width - stars) // 2
if s_type == '*':
print(f"{' ' * side}{'* ' * stars}")
else:
side_nums = ' '.join(f'{x+1}' for x in range(0,i+1))
print(f"{' ' * side}{side_nums[1:][::-1]}{side_nums}")
rows = int(input("Enter number of rows: "))
pyramid(rows)
pyramid(rows, s_type='0')
You only need to input the row count once. You may also find using str.rjust easier for formatting.
rows = int(input('Enter a number from 1 to 9: '))
assert rows > 0 and rows < 10
output = [None] * (rows*2)
stars = '*' * (rows * 2 - 1)
for i in range(rows):
output[i] = stars[:i*2+1].rjust(rows+i)
s = ''.join(map(str, range(1, i+2))) + ''.join(map(str, range(i, 0, -1)))
output[i+rows] = s.rjust(rows+i)
print(*output, sep='\n')
Output:
Enter a number from 1 to 9: 6
*
***
*****
*******
*********
***********
1
121
12321
1234321
123454321
12345654321

I am a beginner in python. Can someone help me to get a star pattern like this?

I have tried these steps but I don't know what to do after trying them.
num = int(input("Enter an integer number greater than or equal to 1: "))
if num > 1:
for x in range(0, num):
for y in range(0, x+1):
print("*", end = " ")
print("")
for x in range(num,1,-1):
for y in range(0,x-1):
print("*", end=" ")
print("")
The pattern I would like to get is
*
**
***
**
*
**
*
*
Hope this does the job. The outer for loop is supposed to decrease the height of a hill by one at every iteration and the inner two for loops print the hill for every height.
num = int(input("Enter an integer number greater than or equal to 1: "))
for height in range (num, 0, -1):
for i in range (1, height):
print ('*'*i)
for j in range (height, 0, -1):
print ('*'*j)

concentric square number using python

i try to make square number but i stuck to print * in middle of square, the program should not using list cause this simple basic. i use looping with if else. i have try my best, maybe someone want's help me to fixed it.
sample
input:
5
a
8
output:
88888
8aaa8
8a*a8
8aaa8
8aaa8
my code:
a = int(input("Enter number: "))
b = input("Enter string: ")
c = int(input("Enter number: "))
row = 1
while(row <= a):
column = 1
while(column <= a ):
if(row == 1 or row == a or column == 1 or column == a):
print(c, end = ' ')
elif(row == a / 2 or column == a / 2)://this for * in middle
print("*" - 2, end=" ")
else:
print(b, end = ' ')
column = column + 1
row = row + 1
print()
My code that I have commented in line does not print right results, which should print *.
elif(row == a / 2 or column == a / 2) change your code to elif(row == a // 2+1 and column == a // 2+1) and remove -2 from print('*' - 2)
while(row <= a):
column = 1
while(column <= a ):
if(row == 1 or row == a or column == 1 or column == a):
print(c, end = ' ')
elif(row == a // 2+1 and column == a // 2+1):
print("*", end=" ")
else:
print(b, end = ' ')
column = column + 1
row += 1
print()
You should use Integer Division feature of Python.
You wrote a/2 which gives floating value 2.5.
But, a//2 gives integer 2
Try this for line: 11, 12:
elif((row == 1 + (a // 2)) and (column == 1 + (a // 2))): # this for * in middle
print("*", end=" ")

Can't get output to rotate 180 degrees

I need to make a nested triangle of hash symbols. But I can't get it to rotate 180 degrees like I need it to, I am also not getting the 12 rows like I need to.
This is my code.
n = int(input("Enter a number: "))
for i in range (0, n):
for j in range(0, i + 1):
print("#", end='')
print("")
for i in range (n, 0, -1):
for j in range(0, i -1):
print("#", end='')
print("")
The Input value is 6.
Enter a number:6
#
##
###
####
#####
######
######
#####
####
###
##
#
But I keep getting this:
Enter a number: 6
#
##
###
####
#####
######
#####
####
###
##
#
How do I fix this?
You can use the str.rjust method to align a string to the right:
n = int(input("Enter a number: "))
for i in range(2 * n):
print(('#' * (n - int(abs(n - i - 0.5)))).rjust(n))
Demo: https://ideone.com/27AM7a
A bit late
def absp1(x):
if (x < 0):
return -x - 1
return x
n = int(input("Enter a number: "))
for i in range(-n, n):
for j in range(absp1(i)):
print(' ', end='')
for k in range(n-absp1(i)):
print('#',end='')
print()
You can use this (manually calculating number of spaces and hashtags):
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(" "*(n - i) + "#"*i)
for i in range (n, 0, -1):
print(" "*(n - i) + "#"*i)
Or use rjust:
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(("#"*i).rjust(n))
for i in range (n, 0, -1):
print(("#"*i).rjust(n))
Also this works fine
num = 6
sing = "#"
for i in range(1, num * 2):
if i > num:
spaces = " " * (i - num)
signs = sign * (2 * num - i)
line = "{0}{1}".format(spaces, signs)
elif i == num:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}\n{0}{1}".format(spaces, signs)
else:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}".format(spaces, signs)
print(line)

check if a number combination is found in a list of combinations

I am creating a program in Python simulating multiplication flash cards. I've gotten pretty far but I can't figure out how to not repeat combinations of numbers. How do I check if a pair of numbers has already been presented?
from __future__ import division
from itertools import combinations
import random
amountCorrect = 0
amountMissed = 0
comb = combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 2)
print("Type 0 at any time to exit and see your score.")
while True:
firstNumber = random.randint(1,12)
secondNumber = random.randint(1,12)
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
In short, use a set to store the pairs of numbers you have already used. Here is some code. You never use combinations in your code so I removed it.
from __future__ import division
import random
amountCorrect = 0
amountMissed = 0
highestNumber = 12
print("Type 0 at any time to exit and see your score.")
used = set()
while True:
if len(used) == highestNumber ** 2:
break
while True:
firstNumber = random.randint(1,highestNumber)
secondNumber = random.randint(1,highestNumber)
pair = (firstNumber, secondNumber)
if pair not in used:
used.add(pair)
break
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
I just created an empty set called used, and added a new inner loop. That loop test if the pair of numbers has already been used. If so, it just loops again and tries a new pair of numbers. I also added a variable to store the highest possible number, and test of the used set is full. I end the quiz if it is full. Without this, when all possibilities are tried the program will go into an infinite loop.
Note that this code will allow both 1,2 and 2,1. If you want to allow only one of those, add both (firstNumber, secondNumber) and (secondNumber, firstNumber) to the used set.

Categories