Why is my code not displaying the output? - python

I have written a program that reads integers until the user enters a 0, which stores the integers and then returns the sum of integers. But its not displaying the output, what went wrong?
def readList():
n=int(input())
while n!=0:
n=int(input())
return n
def calSum(n):
n=myList
myList = readList()
sum = calSum(myList)
print(sum)

calSum was assigning myList to n, but it was INSIDE the calSum and anything OUTSIDE this def was unable to read it, as it is local variable.
Same thing about n from readList. It's local. So "n" in readList and "n" in calSum does not exist outside those functions and can not be used anywhere else.
You were able to use "n" from readList, only because you used return, which returned this value to the rest of the program. And in the very same way you have to make in in calSum to make it work.
Google for global and local variables in python for more information on topic :)
def readList():
n=int(input("Input from readList"))
while n!=0:
n=int(input("Looped input from readList"))
return n
def calSum(n):
n=myList
return n #Added return as student suggested
myList = readList()
sum = calSum(myList)
print(sum)

This should be what you're looking for
The readList function appends to a list and then returns the list, as apposed to return just the first number as it was doing previously.
The calcSum function uses Python's built-in sum function to calculate the sum of all the integers in the list.
def readList():
myList = []
n=int(input())
while n!=0:
n=int(input())
myList.append(n)
return myList
def calSum(n):
return sum(n)
myList = readList()
sum = calSum(myList)
print(sum)

Related

Is there a way to take conditions for for loop as an input in python? I am having trouble with this code

I recently had an idea of doing sigma(Σ) using python
So, I wrote this code.
def sigma(i,target,condition='i'):
if condition=='i':
a=0
for f in range(i,target+1): #the loop sums all the numbers from i to the target given
a+=f
print(a)
'''if user enters a condition than,
every number will follow condition and then be added to each other'''
else:
lis=list()
condition for i in range(i,target+1):
lis.append(i)
print(sum(lis))
but the code I wrote above just gives me a wrong output as it takes the variable condition as type 'string'.
The problem is actully to take the argument condition not as a string
for example, let's say user entered:
sigma(1,100,condition='i'*2)
so the code should run for loop like this:
i*2 for i in range(i, target+1)
but it runs like this:
'ii' for i in range(i, target+1)
For what I can understand, you should pass an anonymous function as argument to accomplish what you are looking for.
Consider that this is not a valid syntax: i*2 for i in range(i, target+1), so I consider it as a pseudo code explained by your comment.
You should change your method in this way:
def sigma(i, target, condition='i'):
if condition=='i':
a=0
for f in range(i,target+1):
a+=f
print(a)
else:
lis=list()
for i in range(i, target+1):
lis.append(i)
print(condition(sum(lis)))
So that if you call sigma(1,100,'i') #=> 5050 you fall in the true part of the statement.
For the false part of the statement you need to call the method passing a lambda expression as parameter:
sigma(1,100, lambda i: 2*i) #=> 10100
It happens that the argument condition when passed as lambda works as if it was defined as:
def condition(i):
return 2 * i
I would like to point out that the sum of the first n natural numbers is given by a math formula, so you don't need a loop:
n * (n + 1) // 2
Also should be better to return a value than to print.
I'd rewrite the method:
def sigma_2(i, target, condition=None):
sum_i_to_target = (target*(target+1)-(i-1)*i)//2
if condition is not None:
return condition(sum_i_to_target)
else: # need to check that condition is a lambda function
return sum_i_to_target
So call this way:
sigma_2(2, 20) #=> 209
sigma_2(2, 20, lambda i: 2*i) #=> 418
You've initialized i from what I can see from your code as a string.
If you would like for the compiler to read it as int then initialize i as int.
For example:
i=1

A recursive function is entered to print smaller and equal numbers

I want to write this function, but it doesn't work
def less(number):
while number>0:
return less(number-1)
print(less(5))
You have to use if instead of while. See the code:
def less(number):
if number>0:
print(number)
return less(number-1)
less(5)

Remove minimum from list without min() in Python

I am trying to remove the minimum value from a list of randomly generated numbers without using the minimum function or the remove function.
I created a function minremo, but I am unsure of what the return value should be to make it actually work. Thus far, I have a method of removing the minimum.
def minremo(lst):
lst.sort()
lst.reverse()
lst.pop()
return n
import random
number_list = []
for count in range(10):
number = random.randint(1, 100)
number_list.append(number)
print(number_list)
print(minremo(number_list))
The algorithms to remove the minimum works at file-level scope though:
import random
number_list = []
for count in range(10):
number = random.randint(1, 100)
number_list.append(number)
print(number_list)
number_list.sort()
number_list.reverse()
number_list.pop()
print(minremo(number_list))
But it does not work within the function itself. I'm not sure what I should return within the function. What should the return be within this function?
Return the list that you just modified (lst).
def minremo(lst):
lst.sort()
lst.reverse()
lst.pop()
return lst

Python 'for' function

I am trying to write a code that returns every prime palindrome with three digits. Here is my code:
def digpalprim():
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
return x
I've already defined the prime(x) function, it works well, that stage just determines whether x is prime or not. All in all the code works, except that it only gives me the first such a palindrome. I don't really understand why, shouldn't the program consider all the numbers between 100 and 1000? Please help?
Your function returns as soon as it finds the first such palindrome; return exits a function.
Collect your finds in a list and return that:
def digpalprim():
palindromes = []
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
palindromes.append(x)
return palindromes
or you can make your function a generator by replacing the return with a yield statement:
def digpalprim():
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
yield x
Now you'll have to iterate over this function or use list() to 'pull' all values out:
all_palindromes(digpalprim())
or
for palindrome in digpalprim():
print(palindrome)
You are returning the function the first time you encounter one.
def digpalprim():
palprimes = []
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
palprimes.append(x)
return palprimes
This creates a list at the start of the function and appends each valid palindrome prime to that list, then returns the entire list (after completing all loops) instead of returning just the first one encountered.
Just remember, if Python hits a return statement, it's going to stop function execution right there and return that value regardless of any additional loops or code you may intend to be executed.
The function returns and ends as soon as the first result is found.
You may wish to add the results to a list and then print out the list.
return x This statement causes the program to return to the calling function once this statement is encountered. To return all you may put it in an list. For e.g:
you can have a list called values and append it to it, and finally return it at the end
For such small tasks, I prefer using list comprehensions:
palindromes = [x for x in range(100, 1000) if (prime(x) == 'prime') and (str(x) == str(x)[::1])]
Or (equivalently):
condition = lambda f: prime(f) == 'prime' and str(f) == str(f)[::1]
palindromes = [x for x in range(100, 1000) if condition(x)]

recursive function in class in python

I don't know, why isn't working that code in python. The problem is, that I can get numbers, but sometimes some numbers are uniform. And I want to do 5 different numbers between 1 and 90.
class lottery:
def __init__(self):
self.price = 50
def list(self):
numbers = []
for i in range(0,5):
numbers.append(random.randint(0,90))
for i in range(1,5):
for j in range(0,i-1):
if (numbers[i]==numbers[j]):
game.list()
return numbers
game = lottery()
game.list()
Or is there any better way to solve my problem?
Thanks!
Use random.sample:
def list(self):
return random.sample(xrange(90), 5)
This is (especially for large values of 5) much more efficient than starting over every time your randomization creates a repeat, and also avoids the possibility of overflowing the stack.
First of all you should import the random module:
import random
The problem is that you are not returning the result that you get from the recursive call, therefore you are still returning the list with repeated numbers. It should be:
def list(self):
numbers = []
for i in range(0, 5):
numbers.append(random.randint(0, 90))
for i in range(1, 5):
for j in range(0, i - 1):
if (numbers[i] == numbers[j]):
return self.list() # return
return numbers
note that self is used to access to the instance of the class that calls the method. Also, don't forget to print the results:
game = lottery()
print game.list()
Note:
Don't use list as the name of a variable or method because it will hide the built-in definition of list.

Categories

Resources