How to make output of python function stdout format? - python

I'm trying to solve a problem where I need to create a function but I need the output to be in stdout format. This is the code i have been working on:
def oddNumbers(l, r):
s = ""
if l % 2 == 0:
if r % 2 == 0:
for i in range(l + 1, r, 2):
s += str(i) + " "
else:
for i in range(l + 1, r + 1, 2):
s += str(i) + " "
else:
if r % 2 == 0:
for i in range(l, r, 2):
s += str(i) + " "
else:
for i in range(l, r + 1, 2):
s += str(i) + " "
return s
This code works for single digit outputs but doesn't work for double digit or triple digit answers. How do I get the proper output in stdout format? Any help would be appreciated. thanks!
for example, for oddNumbers(2, 6), I get the ouput:
3
5
which is correct
but for double-digit outputs such as oddNumbers(96, 97), I get the output:
9
7
which is not correct.
i am supposed to get
97
i don't know how to fix this.

Not sure what you mean. The code works for all answers.
def oddNumbers(l, r):
s = ""
if not l % 2:
if not r % 2:
for i in range(l+1, r, 2):
s += str(i) + " "
else:
for i in range(l+1, r+1, 2):
s += str(i) + " "
else:
if not r % 2:
for i in range(l, r, 2):
s += str(i) + " "
else:
for i in range(l, r+1, 2):
s += str(i) + " "
return s
print(oddNumbers(0,10**4))
outputs every other number from 1 to 9999

Related

How can i add a While loop to detect errors in the input in python

So, i am trying to write a code to not only do arithmetic equations, but also, give feedback if there is an error as well as give me 3 tries max. any advice?
arithmetic=input("Enter an arithmetic operation:")
arithmetic= arithmetic.replace(" ", "")
w=arithmetic.split('/')
x= arithmetic.split('-')
y=arithmetic.split('+')
z=arithmetic.split('*')
if ("+" in arithmetic):
a= int(y[0])
b= int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a= int(z[0])
b= int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a= int(w[0])
b= int(w[1])
result = a / b
result = round(result,3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==3):
a= int(x[1])
b= int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==2):
a= int(x[0])
b= int(x[1])
result = a - b
print("The result is = " + str(result))
#tries = 0
#while(tries < 3):
# arithmetic=input("Enter an arithmetic operation:")
# match = arithmetic.find('+')
# print(match)
# if(match == -1):
# print ("Invalid")
# tries += 1
# else:
# tries= 3
I tried to add the while in the beginning. However, when i put an input such as 11 and 12 without the + sign, it just printed the input without giving me an error. why is that?
tries = 0
while tries < 3:
arithmetic = input("Enter an arithmetic operation:")
arithmetic = arithmetic.replace(" ", "")
w = arithmetic.split('/')
x = arithmetic.split('-')
y = arithmetic.split('+')
z = arithmetic.split('*')
try:
if ("+" in arithmetic):
a = int(y[0])
b = int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a = int(z[0])
b = int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a = int(w[0])
b = int(w[1])
result = a / b
result = round(result, 3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 3):
a = int(x[1])
b = int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 2):
a = int(x[0])
b = int(x[1])
result = a - b
print("The result is = " + str(result))
else:
print("Invalid")
tries += 1
continue
break
except ValueError: # for case split not working good due cases like first input is a negative number
print("Invalid")
tries += 1
At the end of your if / else if chain, just add:
else:
print("invalid")
tries += 1
Replace everything you have inside your while loop currently with the uncommented code above it and that should work.

kaprekar numbers

def kaprekar_num(num):
count = 0
while count <= num:
n = 1
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
kaprekar_num(5)
hello guys,
I'm new to python programming and I got a task in class to print the first 5 kaprekar numbers.
(I only have C programming background...)
I have a problem with the "for x in range..." line.. the code doesn't enter the loop and I don't know why.
the program needs to print:
Number: 9, Left: 8 + Right: 1 = 9
Number: 10, Left: 10 + Right: 0 = 10
Number: 45, Left: 20 + Right: 25 = 45
Number: 55, Left: 30 + Right: 25 = 55
Number: 99, Left: 98 + Right: 1 = 99
I will appreciate some insights :)
for loop was fine, you had some logic issue, which you haven't handled, like when n==1 and when len(sqr)==1.
def kaprekar_num(num):
count = 0
n=1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
if sqr==1:
print("Number: " + str(n) + " = " + str(n))
count+=1
n+=1
elif length>1:
for x in range(1,length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
else:
n+=1
kaprekar_num(5)
How you're managing the n value is incorrect. It should be set before the loop starts, then after each try, regardless of the outcome, it should increment.
def kaprekar_num(num):
count = 0
# Start n at one, and don't reset it on each loop
n = 1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
count += 1
# This number is a Kaprekar number, so break out of the loop
break
# Regardless of the status of this number, try the next one
n += 1
kaprekar_num(5)
And as a recommendation: I'd highly recommend you look into stepping through the code with a debugger in the future. If you had done so, you'd have seen that n is not changing fairly quickly.
you've set the loop to repeat once i think, if you meant to put n instead of 1, i think thats the problem.
Try to set the loop to this instead
for x in range(n, length):

space-separated string of all positive numbers that are divisible by 2.For example, even_numbers(6) returns “2 4 6”

def even_numbers(maximum):
return_string = ""
for x in ___:
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(1)) # No numbers displayed
def even_numbers(maximum):
return_string = ""
for x in range(1,maximum+1):
if x%2==0:
return_string += str(x) + " "
return return_string.strip()
You can use this
def even_numbers(maximum):
return_string = ""
for x in range(2, maximum + 1, 2):
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # prints 2, 4, 6
def even_numbers(maximum):
return_string = ""
for x in range(0, maximum + 1):
if x != 0 and x % 2 == 0:
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # Should be 2 4 6
print(even_numbers(10)) # Should be 2 4 6 8 10
print(even_numbers(1)) # No numbers displayed
print(even_numbers(3)) # Should be 2
print(even_numbers(0)) # No numbers displayed

Python - Getting an Identation error out of the file

I am trying to make a little program in python, nothing complicated, but extremely long. Just now, I modified one condition for an 'if' statement, and then ran it through the MacOS terminal, since it has a Python shell / IDLE (I don't know how is it called in english).
My document has exactly 456 lines, and the 'IndentationError' I get is at 'line 457' and here is the output :
File "/Volumes/my usb key/MAIN_0.3.py", line 457
^
IndentationError: expected an indented block
I really dont know what to do with that, since the last lines of my programs are all comments. If you want some code, I'll try to put it simply (and in english) for you all, but I would like to know first if it isn't a problem with running it in 'Terminal', because it is really weird.
EDIT : here is some code :
#coding= utf-8
#here I put a lot of variables(38), which are all 'int' or 'randint(x, y)'
#then I define some functions, which are all calculus
#here is the main loop :
while (a!=10) and (b > 10):
function_a(a)
c=0
while (c != 1) and (b > 0):
while b != 0:
print "\n"
d=randint(0,20)
if 0 <= d <= 3: #commentary explaining my program for my buddies at school
b=function_b(b, e, f, g, h, i, j, a, k, l)
if b <= 0: #commentary
m += n
p += a_b
if p > 1000: #commentary
p -= 1000
k += 1
print " BRAVO !"
print " now", k
time.sleep(1)
b += b_levelup
e += e_levelup
f += f_levelup
print " you won", b_levelup, "points"
time.sleep(1)
print " you won", e_levelup, "points"
time.sleep(1)
print " you won", f_levelup, "points"
time.sleep(1)
print "\n"*2
if 3 < d <= 8: #commentary
b=function_b(b, e, f, g, q, r, s, a, k, t)
if b <= 0: #commentary
m += u
p += v
if p > 1000: #
p -= 1000
k += 1
print " BRAVO !"
print " now", k
time.sleep(1)
b += b_levelup
e += e_levelup
f += f_levelup
print " you won", b_levelup, "points"
time.sleep(1)
print " you won", e_levelup, "points"
time.sleep(1)
print " you won", f_levelup, "points"
time.sleep(1)
print "\n"*2
if 8 < d <= 14: #commentary
b=function_b(b, e, f, g, w, x, y, a, z, k, a_a)
if b <= 0: #commentary
m += n
p += a_b
if p > 1000: #commentary
p -= 1000
k += 1
print " BRAVO !"
print " now", k
time.sleep(1)
b += b_levelup
e += e_levelup
f += f_levelup
print " you won", b_levelup, "points"
time.sleep(1)
print " you won", e_levelup, "points"
time.sleep(1)
print " you won", f_levelup, "points"
time.sleep(1)
print "\n"*2
if 15 <= d <= 16:#commentary
a_c += 1
function_c()
if d == 17: #commentary
a_d += 1
function_d()
#boss commentary
if (d == 18) and (a_d == 0):
print " mkay"
time.sleep(2)
print " nope"
print " next door"
#commentary
if (d == 18) and (a_d >= 1):
print " arrived"
time.sleep(2)
print " wanna go ?"
print " yes - 1"
print " No - any other"
a_e=input(" ")
if a_e == 1:
#boss commentary
Comments aren't statements, so when you do
if something:
# Comment
The if has no body. That's a syntax error. If you want a do-nothing placeholder body, that's what the pass statement is for.
if something:
# Comment
pass

Why is my list index out of range?

def main():
print("You haved activated Weather Pro 3.0")
rain_inputs()
rain_calc()
def rain_inputs():
global rain
rain = []
for x in range(1, 13):
try:
rain_meter = float(input("What is the rainfall? "))
rain.append(rain_meter)
if x == 4:
print("8 more months to go!")
elif x == 7:
print("5 more months to go!")
elif x == 9:
print("2 more to go! Smash those keys!")
elif x == 13:
return
except Exception as err:
err = ("You should be putting in numbers!")
print(err)
rain_calc is supposed to calculate the total of all listed inputs.
def rain_calc():
rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
rain_math2 =(rain[5] + rain[6] + rain[7] + rain[8])
rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
rain_total =(rain_math + rain_math2 + rain_math3)
print(rain_total)
main()
The error occurs in rain-math3:
Programming/RainFall.py", line 30, in rain_calc rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
IndexError: list index out of range
rain[12] is out of range because rain only has 12 elements in it. You missed rain[4], so you probably wanted this:
def rain_calc():
rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
rain_math2 =(rain[4] + rain[5] + rain[6] + rain[7])
rain_math3 =(rain[8] + rain[9] + rain[10] + rain[11])
rain_total =(rain_math + rain_math2 + rain_math3)
print(rain_total)

Categories

Resources