107k views
1 vote
Retype and run, note incorrect behavior. Then fix errors in the code, which should print num_stars asterisks.

while num_printed != num_stars:
print('*')
Sample output with input: 3

*
*
*

This is the code I inputted. It works for the first part of 3 stars but not input of 5.

num_stars = 3

num_printed = 0



while num_printed < num_stars:

print('*')

num_printed += 1

User Metareven
by
8.1k points

1 Answer

3 votes

Final answer:

The issue with the provided code is the hardcoded value of num_stars which is set to three. To fix it, replace it with a variable that takes user input and incorporate the 'end' parameter in the print function to ensure that stars are printed on the same line with spaces in between.

Step-by-step explanation:

The code you provided is almost correct. However, to ensure it functions for any value of num_stars, you need to replace the hardcoded value of num_stars (which is currently set to 3) with a variable that can accept any input. Here is the corrected code snippet:

num_stars = int(input('Enter the number of stars: '))
num_printed = 0

while num_printed < num_stars:
print('*', end=' ')
num_printed += 1

Note the use of end=' 'in the print function. This ensures that stars are printed on the same line with a space separating them, matching the sample output you provided.

\

User Rnrneverdies
by
7.3k points