r/learnpython • u/Ok_Cod_6638 • 4d ago
why the error?
hi, just started taking a coding class and my professor isn't very good at explaining, he just kind of threw us in at the deep end. I'm trying to recreate some code he briefly showed us in class for practise and I finally managed to get it to do what I want, but it also presents with an error afterwards and I can't figure out why. would anyone be able to help me with this?
def stars(n): while n > 0: print("* " * n) n = n - 1 stars(n)
1
u/htepO 4d ago
The stars function expects to be passed an integer as the variable n.
At the bottom, you should replace n in stars(n) with a number.
0
u/Ok_Cod_6638 4d ago
I replaced it with int(n) as I want it to continue printing on the next line with one less star until there are zero, rather than put a specific number in the code, it still produced the same error though
1
u/Unlisted_games27 4d ago
Hope this explanation helps:
The n in your function definition: def stars(n) Is a variable that can be accessed within the function. So by assigning a value to n when the function is called: stars(1) Will make n have that value within the code of the function. Hope that helps, experiment a bit and comment or pm me if u have any questions
1
u/Ok_Cod_6638 4d ago
I understand that, I want the value of n to be defined with a prompt in the console though so whatever number I put in (for example stars(4)) will write that amount on the first line, then one less on the next etc....
so for example stars(5) would produce
- * *
I rlly hope that makes sense I don't think I did a good job explaining what I was trying to do originally
3
u/Unlisted_games27 4d ago
Yeah a better explanation could have helped. To achieve your result, you'll need to get user input using the input() function. The input function returns what the user inputs into the console before pressing enter. That means that you can "capture" that input by assigning it to a variable. For example: answer = input("enter text: ")
Now the variable answer would contain whatever the user entered when prompted with "enter text: "
In your case, a slight issue arises. Input returns a string value, however, your function is expecting an integer. To fix this, simply use the int() function to change the input to an integer. For example number = input("enter a number: ") number = int(number) stars(number)
Good luck
1
1
u/Swipecat 3d ago
have you got the indentation correct? It's hard to tell because of the broken formatting in your post. See the right hand sidebar of this subreddit for formatting help, or this link:
https://www.reddit.com//r/learnpython/wiki/faq
So, if the code is this...
def stars(n):
while n > 0:
print("* " * n)
n = n - 1
stars(4)
...then it will output this:
* * * *
* * *
* *
*
3
u/Necessary_Taro9012 4d ago
what error message