Python code doesn't print anything, just gives code 0 - python

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))

Related

calculate the sum of the digits of any three digit no(in my code loop is running every time help in correction)

my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))

Asterisk Triangle in Python (using recursion)

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.

Python codecademy digit_sum

the task was discussed in
codecademy Practice Makes Perfect digit_sum
Where you need to sum the digits of a positive number.
I use the string way to decide the task (not the floor dividing).
My code is
def digit_sum (n):
total = 0
for digit in range(len(str(n))):
total += int(n[digit])
return total
number = raw_input("Please print a long number: ")
print digit_sum(number)
It works all right with 1001 as well as with 434.
However, the program says:
Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "'int' object has no attribute 'getitem'" error.
What can be wrong when the code is working?
Thanks!
you did not convert n to string, so when you call n[i] it will raise exception
def digit_sum(n):
return sum( int(i) for i in str(n) )
Evert, Jerzyk, Galaxian, thanks for the comments. Thanks for you I saw it: I casted n to str only in one place (3rd line) and thought that this was enough since the 4th line is inside the for loop. I edited the code to
def digit_sum (n):
total = 0
n = str(n)
for digit in range(len(n)):
total += int(n[digit])
return total
number = int(raw_input("Please print a long number: "))
print digit_sum(number)
And now it works!
Galaxian, ShadowRanger, thanks for your short code, I tried it and it' fine!
I haven't caught yet this brief way of coding. By the way I searched for info about map function and found this:explanation on zip, map, lyambda

Recursive function python, cannot print an output

I have just started to program in python, and I am stuck with a problem regarding recursion.
The program seems to compile, however, the print output is not shown.
Here is the program:
print 'type s word'
s = raw_input()
print 'enter a number'
n = raw_input()
def print_n(s, n):
if n<=0:
return
print s
print_n(s, n-1)
the output i get is:
xxxx#xxxx-Satellite-L600:~/Desktop$ python 5exp3.py
type s string
hello
add the number of recursions
4
xxxx#xxxx-Satellite-L600:~/Desktop$
What is wrong, and how can I get the program to show an output?
Your posted code defines the function print_n but never calls it. After the function definition place a print_n(s, n).
Once you do this you'll find some errors caused by the fact the n is currently a string (raw_input returns a string). Use int(a_string) to convert a string to an integer. Calling your function like this will solve the issue
print_n(s, int(n))
Or do
n = int(raw_input())
The complete code:
s = raw_input('type a word: ')
n = int(raw_input('enter a number: '))
def print_n(s, n):
if n <= 0:
return
print s
print_n(s, n-1)
print_n(s, n)
try n = raw_input() -> n = int(raw_input())

Python Factorial program help

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

Categories

Resources