I have seen multiple "python asterisk triangles" and their solutions, but I am stuck on creating an asterisk triangle using recursion (without a loop, which would make it much easier in my opinion.) Below is the current code I have:
def main():
num = int(input("Enter an integer: "))
triangle = draw_triangle(num)
print(triangle)
def draw_triangle(n):
if n == 0:
return
else:
return ("*" * n + '\n') + draw_triangle(n - 1)
main()
When I run the code, I receive "TypeError: must be str, not NoneType." I have done some research and still do not completely understand what this error is telling me. I apologize if this question was asked before, I was unable to find one dealing with any recursive functions. Thank you.
return to return ""
Input: 5
Output:
*****
****
***
**
*
This error occurs because you return a blank value. Try returning a blank string instead
Solution:
In line 9:
replace return with return ''
The code is working properly but there is just a slight problem.
When testing with base case i.e. if n == 0: the return must be set to something, if not it will return None. Thus after the input number reaches 0 it returns None anything that returns None is interpreted as a failed case in python so
Here is a work around:
def draw_triangle(n):
if n == 0:
return ''
else:
return ("*" * n + '\n') + draw_triangle(n - 1)
def main():
num = int(input("Enter an integer: "))
triangle = draw_triangle(num)
print(triangle)
main()
Thus after reaching n == 0 case the program will return a blank string and continue.
Related
so I'm very noobish, I got this python code that I found somewhere in my folders, because I started learning python a while ago, and I need this code for class today. Thing is, it doesn't print anything, it just indicates that there's no problem with it. Can you help me? I need to sc the code and sc the output, if you can guide me to what line of code im missing or anything really.. thanks
def square(n):
word = int(raw_input('Enter number here: '))
if len(word) > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
First of all, using Python 3, you need to replace raw_input with input. Secondly and most importantly, integer does not work with len function and you should compare your integer directly. To handle potential type mismatch, use following code (you can put it in a loop or do any other modifications)
def square():
n = input('Enter number here: ')
try:
n = int(n)
except TypeError:
print("Input is not a number")
else:
if word > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
# Let's call the function
square()
By the way, I think calling integer variable word is not very self-descriptive.
I think this will work:
def square(n):
number = int(input('Enter number here: '))
if number > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
I'm relatively new to Python and I decided to try and code a relatively simple collatz conjecture where the user enters a number (integer). The code is just a simple function that calls itself. i is a list that should have every number that the function calculates appended to it. I'm new to executing Python scripts and I have tried using the IDLE shell to run the code. It asks me what number I want but when I enter a number nothing is printed? I'm sure I just need to edit a small bit of this code (or maybe it's all wrong yikes) but does anybody have any idea why my script returns nothing? Sorry about this and thanks.
Here's the code:
l = input("Enter a number: ")
l = int(l)
i = []
def collatz(n):
if n==1:
return i
if n%2 == 0:
n = n/2
i.append(n)
return collatz(n)
else:
n = ((n*3) + 1) / 2
i.append(n)
return collatz(n)
print(i)
collatz(l)
There are three returns before your print and one of them is inside an else statement, which means that at least one of them will be executed, so your print won't even be reached to be executed, you should move it right after the function definition to see something:
def collatz(n):
print(i) # <= print here
if n==1:
....
See more about the return statement. A snippet:
return leaves the current function call with the expression list (or None) as return value.
As others have mentioned, all of the execution paths in your function end in a return statement, so that print call is unreachable. So if you want each value of n or i to be printed you need to move the call to somewhere that it will be reachable. ;)
Also, there's a little bit of redundancy in that code. You don't need
i.append(n)
return collatz(n)
in both the if and else branches, you can move them outside the if...else block.
Here's a modified version of your code. I've also changed the / operators to // so that the results of the divisions will be integers.
i = []
def collatz(n):
print(n)
if n==1:
return i
if n%2 == 0:
n = n // 2
else:
n = ((n*3) + 1) // 2
i.append(n)
return collatz(n)
# Test
print(collatz(12))
output
12
6
3
5
8
4
2
1
[6, 3, 5, 8, 4, 2, 1]
I've looked on the site to try and figure out how to do this but I'm still stuck.
My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :
def reverse_digits(num):
return int(str(num)[::-1])
However, my code needs to 1) test if it is a negative and keep it negative (so -8765 returns -5678) and 2) I think I should test to see if num is actually an int.
So far I have
def reverse_digits(num):
num = str(num)[::-1]
if num == '-':
minus = 1
num = num[:-1]
else:
minus = 0
int(num)
if minus == 1:
num = num*-1
else:
num = num
return num
It works for digits without a '-', but returns '' when it has a '-'.
I was originally trying to put the test to see if it is an int at the beginning od the loop like
if (num != int):
print("wrong type")
sys.exit()
else:
(the rest of my above code)
but that wouldn't work for me. Should I put all the code in a while loop so I can use continue/break?
Thanks!
Just don't put the - into the reversed string:
def reverse_digits(num):
return (-1 if num<0 else 1) * int(str(abs(num))[::-1])
Try to use the isdigit() string method.
def reverse_digit(num):
num_str = str(num)[::-1].strip('-')
if not num_str.isdigit():
<do what u want>
if num < 0:
return -int(num_str)
else:
return int(num_str)
I am new to Python and I am taking Codecademy lessons required by my teacher. The instructions read, Define a function factorial that takes an integer x as input.
Calculate and return the factorial of that number.
For my code, I put,
def factorial(x):
if x == 1:
return factorial('n' - 1)
When I clicked save and submit code, it gave me this error message,
unsupported operand type(s) for -: 'str' and 'int'
I tried looking at the codecademy Q and A forum, but I didn't find anything feasible. I even went on this site and looked up what the error message meant. I looked at the hint provided by codecademy and it just made me more confused! Please help. Any feedback/ advice is always helpful. Thanks!
You are trying to subtract the number 1 from the letter n. Instead you should subtract 1 from the number you were given.
As far as I can tell, you are trying to make a factorial function using recursion. Your code has a few problems:
def factorial(x):
if x == 1:
return factorial('n' - 1)
First of all, on line 3 you are trying to subtract 'n' (a String) from 1 (an Integer). Remove the quotes to fix this.
Secondly, (if my previous statement was correct) your function takes input as x, not n. You are probably trying to do:
def factorial(x):
if x == 1:
return factorial(x - 1)
You are passing a string 'n' in to your factorial method. There are two problems with this:
1) You cannot perform a subtraction operation by trying to do 'n' - 1 (string type - int type).
2) You most likely meant to pass x instead of 'n'.
Next, your recursive algorithm for checking a factorial is incorrect.
You need to take the number, multiplied by the return of calling the factorial method again, but passing the number subtracted by 1. But then you need your "exit" condition, which is when the number reaches a value below 1:
def factorial(x):
if x < 1:
return 1
else:
return x * factorial(x - 1)
The error shows that you are trying to manipulate two things of different types, integer and string. Ans also it seems that your function "factorial" will only work if you give it an integer number 1. You can simply do this with while loop; (keep in mind the TYPES of things you want to manipulate).
def factorial(x):
n=1
total = x
last_int = x
while n < total:
x = x * (last_int-1)
n += 1
last_int -= 1
return x
if __name__ == "__main__":
while 1:
number = raw_input("enter number: ")
result = factorial(int(number))
print 'factorial number for ' + str(number) + ' is ' + str(result)
There's also another way to fix the task. You can use range with a negative step -1 and multiply from x to 1:
def factorial (x):
total = 1
if x < 1:
return total
else:
for i in range(x, 0, -1):
total *= i
return total
Here is what i wrote:
number = raw_input('Enter an integer= ')
if number < 0:
print 'Invalid number'
else:
for k in range(1,(number)):
number *= k
print number
I want to be able to input any number (that is greater than 0), but when i input a number say 4 (the factorial of 4 is 24) i get this error:
Traceback (most recent call last):
File "problem.py", line 6, in <module>
for k in range(1,(number)):
TypeError: range() integer end argument expected, got str.
I don't understand what it means and as far as i know the code should be working, Please Help!
This works perfectly: factorial.py
#!/usr/bin/env python
# imports go here
__author__ = 'Michael O. Duffy'
__status__ = "Development"
def factorial(n):
""" Calculate a factorial of an integer """
factorial = 1
if n < 0:
print 'Invalid number'
else:
for k in range(1,n+1):
factorial *= k
return factorial
if __name__ == '__main__':
for number in range(1, 20):
print 'n: ', number, 'n!: ', factorial(number)
You should know that this is an inefficient, academic implementation that shouldn't be used in any serious application. You'll be a lot better off using a gamma or lngamma implementation and a dictionary cache to save on calculations if you use values repeatedly:
http://mathworld.wolfram.com/GammaFunction.html
What about recursion?
def factorial(n):
if n < 0:
print("ERROR!") # throw error, return -1, or whatever
elif n <= 1:
return 1
else:
return n * factorial(n - 1)
raw_input returns a string, not an integer. Create an integer this way:
number = int(raw_input('Enter an integer= '))
The user might type something besides an integer, in which case you might want to handle that possibility.
while True:
try:
number = int(raw_input('Enter an integer= '))
except ValueError:
print "That wasn't an integer"
else:
break
using xxxxx.py
num=int(raw_input("Enter a number"))
n=1
while num>=0:
n=n*num
num=num-1
print "Factorial of the given number is: ",n