Return outside the function error:(Python) - python

Here, for this code I'm getting an error on return outside the function.
Can I anyone explain why is this so?
import numpy as np
name = input().split(" ")
arr = [int(num) for num in name]
sum=[]
for i in arr:
sum=+i
return sum

return statement only makes sense inside functions. To show or display infos use print(sum)

You are using the return keyword outside of a function. If you want to display the sum on screen use: print(sum).

You can't use the return statement outside a function. It is used to end the execution of a function and return the results of that particular function. You can simply modify your script to a function like this.
import numpy as np
name = input().split(" ")
arr = [int(num) for num in name]
def function_name(array):
sum=[]
for i in array:
sum=+i
return sum
variable_name = function_name(arr)

Related

How can I generate a random value and then use the pop method to remove it?

I am trying to take a random name from a list and then once it has been printed, I want to remove it from that list so that it isn't used ever again. I want to use the pop method but I'm not sure how to take a random name from the list since the pop method (to my knowledge) only accepts integers.
Here is my code:
Boy = ['David','John','Paul','Mark','James','Andrew','Scott','Steven','Robert','Stephen','William','Craig','Michael'
,'Stuart','Christopher','Alan','Colin','Kevin','Gary','Richard','Derek','Martin','Thomas','Neil','Barry',
'Ian','Jason','Iain','Gordon','Alexander','Graeme','Peter','Darren','Graham','George','Kenneth','Allan',
'Simon','Douglas','Keith','Lee','Anthony','Grant','Ross','Jonathan','Gavin','Nicholas','Joseph','Stewart',
'Daniel','Edward','Matthew','Donald','Fraser','Garry','Malcolm','Charles','Duncan','Alistair','Raymond',
'Philip','Ronald','Ewan','Ryan','Francis','Bruce','Patrick','Alastair','Bryan','Marc','Jamie','Hugh','Euan',
'Gerard','Sean','Wayne','Adam','Calum','Alasdair','Robin','Greig','Angus','Russell','Cameron','Roderick',
'Norman','Murray','Gareth','DeanEric','Adrian','Gregor','Samuel','Gerald','Henry','Benjamin','Shaun','Callum',
'Campbell','Frank','Roy','Timothy','Liam','Noah','Oliver','William','Elijah','James','Benjamin','Lucas',
'Mason','Ethan','Alexander','Henry','Jacob','Michael','Daniel','Logan','Jackson','Sebastian','Jack','Aiden',
'Owen','Samuel','Matthew','Joseph','Levi','Mateo','Wyatt','Carter','Julian','Luke','Grayson','Isaac','Jayden'
,'Theodore','Gabriel','Anthony','Dylan','Leo','Christopher','Josiah','Andrew','Thomas','Joshua','Ezra',
'Hudson','Charles','Caleb','Isaiah','Ryan','Nathan','Adrian','Christian']
Girl = ['Emma','Ava','Sophia','Isabella','Charlotte','Amelia','Mia','Harper','Evelyn','Abigail','Emily','Ella',
'Elizabeth','Camila','Luna','Sofia','Avery','Mila','Aria','Scarlett','Penelope','Layla','Chloe','Victoria',
'Madison','Eleanor','Grace','Nora','Riley','Zoey','Hannah','Hazel','Lily','Ellie','Violet','Lillian','Zoe',
'Stella','Aurora','Natalie','Emilia','Everly','Leah','Aubrey','Willow','Addison','Lucy','Audrey','Bella',
'Nova','Brooklyn','Paisley','Savannah','Claire','Skylar','Isla','Genesis','Naomi','Elena','Caroline','Eliana'
,'Anna','Maya','Valentina','Ruby','Kennedy','Ivy','Ariana','Aaliyah','Cora','Madelyn','Alice','Kinsley',
'Hailey','Gabriella','Allison','Gianna,Sarah','Autumn','Quinn','Eva','Piper','Sophie','Sadie','Delilah'
,'Josephine','Nevaeh','Adeline','Arya','Emery','Lydia','Clara','Vivian','Madeline','Peyton','Julia','Rylee',
'Brielle','Reagan','Natalia','Jade'',Athena','Maria','Leilani','Everleigh','Liliana','Melanie','Mackenzie',
'Hadley','Raelynn','Kaylee','Rose','Arianna','Isabelle','Melody','Eliza','Lyla','Katherine','Aubree',
'Adalynn','Kylie','Faith','Marly','Margaret','Ximena','Iris','Alexandra','Jasmine','Charlie','Amaya',
'Taylor','Isabel','Ashley','Khloe','Ryleigh','Alexa','Amara','Valeria','Andrea','Parker','Norah','Eden',
'Elliana','Brianna','Emersyn','Valerie','Anastasia','Eloise','Emerson','Cecilia','Remi','Josie','Reese',
'Bailey','Lucia','Adalyn','Molly','Ayla','Sara','Daisy','London','Jordyn','Esther','Genevieve','Harmony',
'Annabelle','Alyssa','Ariel','Aliyah','Londyn','Juliana','Morgan','Summer','Juliette','Trinity','Callie',
'Sienna','Blakely','Alaia','Kayla','Teagan','Alaina','Brynlee','Finley','Catalina','Sloane','Rachel','Lilly'
,'Ember']
def boyname():
result = Boy.pop(insert code for random name here)
print(result)
print(Boy)
boynames = boyname()
print(boynames)
Simply:
name = Boy.pop(random.randint(0, len(Boy)-1))
But: you should not do that, especially from within a function, as it affects the caller's list (or in your case, the global variable containing the list).
Consider instead the ability to take a random subset (without side effects):
sample = random.sample(Boy, k)
For example, you can go through a random ordering of your list (i.e. sample without replacement), ensuring you will "print" each value just once:
for name in random.sample(Boy, len(Boy)):
...
You can even turn this into a generator, for infinite fun:
from itertools import count
def pick(a, n_loops=None):
"""if n_loops is None: cycle endlessly"""
counter = count()
while n_loops is None or next(counter) < n_loops:
yield from random.sample(a, len(a))
Usage:
name_gen = pick(Boy) # infinite generator: loops around shuffles;
# no repeat during a single loop
list(islice(name_gen, 5))
# or
names = pick(Boy, 1) # one random shuffle of Boy
Another fun example:
for b, g in islice(zip(pick(Boy), pick(Girl)), 4):
print(f'{b} and {g}')
# out:
Carter and Molly
Malcolm and Lydia
Sebastian and Ruby
Charles and Aliyah
Try this code
from random import choice
def boyname():
global Boy
result = choice(Boys)
print(result)
Boy.remove(result)
print(Boy)
boyname()
Something like this would work:
import numpy as np
np.random.seed(1)
def boyname():
"""
Returns a random `boy` from `Boy` (list) while removing from list
"""
idx = np.random.randint(0,len(Boy)-1)
res = Boy.pop(idx)
return res
my_boy = boyname()
print(my_boy)
Can use this
import random
def boyname():
result = Boy.pop(Boy.index(random.choice(Boy)))
print(result)
print(Boy)
return 'End of Program'
boynames = boyname()
print(boynames)
In my opinion, you can try to get the index of a name by random function, and you can define the function like this:
import random
def boyname():
boy_name_list_length = len(Boy)
index_of_name = int(random.random() * boy_name_list_length)
result = Boy.pop(index_of_name)
print(result)
print(Boy)
And call the function like this:
boyname()
Remember just run the Boy and Girl list initialization once!

Is it possible to append to an outside list form inside a function?

I'm defining a function that performs calculations and needs to return the answer and put that answer into a list. I'm eventually going to get the average of the list, among other things, but I'm just curious if I can put the calculation formulas inside the function, and have it append to a list that was defined outside of the function. The reason for that is that I have multiple calculation formulas, and have to create multiple functions. I've simplified its essence here:
def triangle_perimeter(x):
perimeter = (x * 3)
perimeters = []
x = input("Input a number: ")
triangle_perimeter(x)
perimeters.append(perimeter)
print(perimeters)
return a value from your function and pass that to your append() call.
You will also need to cast your input() as int() as it normally stores a string.
def triangle_perimeter(x):
## Return value from function ##
return x * 3
perimeters = []
x = int(input("Input a number: "))
## Call append, appending the returned value from function ##
perimeters.append(triangle_perimeter(x))
print(perimeters)

Change result by function - python3

I need to generate random number with 4 various literature,
so i wrote this program:
import random
def rand():
i=0
n=""
while i<4:
a = str(random.randint(0,9))
if a not in n:
n +=a
i+=1
return n
print (rand)
The content of the function is correct, but the function cause to strange result :
<function rand at 0x000001E057349D08>
what am I missing?
You are printing the reference to the function itself instead of invoking it. To invoke it, you need to follow it with parenthesis (()):
print (rand())
# Here ----^

Write a function which squares a number and then use it to write a function which takes three integers and returns the sum of their squares

Im new to python and cant figure out how to get these functions to call themselves. It asks for an input but no matter what gives 0 as the output. Can someone help debug?
userinput = input("Enter three numbers: ")
userinput = userinput.split(',')
finalsum = 0
finaldata = []
def formatinput(x):
sqrdata = []
for element in x:
sqrdata.append(int(element))
return(sqrdata)
def findsquare(x):
return (x*x)
def sumthesquares(y):
for element in y:
temp = findsquare(element)
finaldata.append(int(temp))
finalsum = finalsum + temp
return finalsum
def findthesquares(userinput):
finalsum = sumthesquares(formatinput(userinput))
print(finalsum)
Have you actually tried running your code? From what you've posted, it looks like you never actually call your functions...
They're defined, but you're missing the actual calls, like formatinput(userinput).
For future reference, if you put something like print("Got here!") into your functions, you can test that they're being called.

Why is my code not displaying the output?

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)

Categories

Resources