Return value used in another function - Python - python

I want to write 2 functions. One function that takes input from a user and adds it to a list. The 2nd function takes the list returned from the 1st function and prints out each element separated by a space. I think I am close, but something isn't right. Typing -999 doesn't stop the loop, and I can't tell if I am calling the functions correctly...
Any ideas?
def listFunc():
num = 0
list1 = []
while num != -999:
x = int(input('Enter a number, -999 to quit: '))
list1.append(x)
return list1
def formatFunc(y):
final = str(y)
' '.join(final)
print(final)
formatFunc(listFunc())

It should be the same variable used in while loop.
num = int(input('Enter a number, -999 to quit: '))
if num != -999:
list1.append(num)
and
# final = str(y) This is not required, why cast list as str
final = ' '.join(final)

x = int(input('Enter a number, -999 to quit: '))
list1.append(x)
num=x
will work!

You are calling the functions correctly if you intend on printing the inputs of listfunc. However the inputs will not be saved to a variable in global scope and will thus be locked out from any future use.
Additionally, listfunc currently does no input validation. It is possible to input any strings in the input. The while loop doesn't end because the condition in the while is never met.
Rewriting it according to your conditions yields:
def listfunc():
someList = []
while True:
x = input("Enter a number, exit to quit")
if 'exit' in x.lower():
break
elif x.isdigit():
someList.append(x)
else:
print("Input not recognized try again")
return someList
def formatFunc(v):
print(''.join(str(i) + ' ' for i in v)
Do you see why this works?

Related

Keep asking for numbers and find the average when user enters -1

number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)

How to return to menu by a special key?

Is there any simple method to return to menu by entering a special key? If the user made a mistake while entering the input, user can return to main menu by pressing # (a special key) key at the end of the input.
x = input("Enter first number: ")
Here, user enter 5, but want to exit by input #. So, x = 5#
I tried some including this
x=input("Enter first number: ")
print(int(a))
if x == "#":
exit()
Also tries this too
for x in ['0', '0$']:
if '0$' in x:
break
But, unable to handle numbers and string values together.
while True:
x = input()
if x[-1] == '#':
continue
# other stuff
this should work
Try
user_input = input("Enter your favirote deal:")
last_ch = user_input[-1]
if(last_ch == "#"):
continue
else:
//Your Logic
int(x) will not work if it contains characters other than numbers.
use this construction (# will be ignored by converting a string to int)
x=input("Enter first number: ")
print(int(x if "#" not in x else x[:-1])) # minus last if has #
if "#" in x:
exit() # or break or return, depends what you want

Python one line for loop input

I don't know how to get input depending on user choice. I.e. 'How many numbers you want to enter?' if answers 5, then my array has 5 spaces for 5 integers in one line separated by space.
num = []
x = int(input())
for i in range(1, x+1):
num.append(input())
Upper code works, however inputs are split by enter (next line). I.e.:
2
145
1278
I want to get:
2
145 1278
I would be grateful for some help.
EDIT:
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
This seems to work. But why I'm getting "Memory limit exceeded" error?
EDIT:
Whichever method I use, I get the same problem.
x = int(input())
y = input()
numbers_list = y.split(" ")[:x]
array = list(map(int, numbers_list))
print(max(array)-min(array)-x+1)
or
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
array = list(map(int, num))
print(max(array)-min(array)-x+1)
or
z = int(input())
array = list(map(int, input().split()))
print(max(array)-min(array)-z+1)
Assuming you want to input the numbers in one line, here is a possible solution. The user has to split the numbers just like you did in your example. If the input format is wrong (e.g. "21 asd 1234") or the number does not match the given length, the user has to enter the values again, until a valid input is made.
x = int(input("How many numbers you want to enter?"))
while True:
attempt = input("Input the numbers seperated with one space")
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)==x:
print(num)
break
else:
print("You have to enter exactly %s numbers! Try again"%x)
except:
print("The given input does not match the format! Try again")
The easiest way to do this would be something like this:
input_list = []
x = int(input("How many numbers do you want to store? "))
for inputs in range(x):
input_number = inputs + 1
input_list.append(int(input(f"Please enter number {input_number}: ")))
print(f"Your numbers are {input_list}")
Is there a reason you want the input to be on one line only? Because you can only limit how many numbers you store (or print) that way, not how many the user inputs. The user can just keep typing.
You can use this without needing x:
num = [int(x) for x in input().split()]
If you want the numbers to be entered on one line, with just spaces, you can do the following:
x = int(input("How many numbers do you want to store? "))
y = input(f"Please enter numbers seperated by a space: ")
numbers_list = y.split(" ")[:x]
print(f"We have a list of {len(numbers_list)} numbers: {numbers_list}")
Even if someone enters more than the amount of promised numbers, it returns the promised amount.
Output:
How many numbers do you want to store? 4
Please enter numbers seperated by a space: 1 4 6 7
We have a list of 4 numbers: ['1', '4', '6', '7']
Try this.
x = int(input())
num = [] # List declared here
while True:
try:
# attempt moved inside while
# in case input is in next line, the next line
# will be read in next iteration of loop.
attempt = input()
# get values in current line
temp = [int(val) for val in attempt.split(" ")]
num = num + temp
if len(num) == x:
break
except:
print('Error2')
Maybe the bot was passing integers with newline instead of spaces, in which case the while loop will never terminate (assuming your bot continuously sends data) because every time, it will just re-write num.
Note - this code will work for both space as well as newline separated inputs

Can input exist within a defined function in Python?

I am trying to shorten the process of making lists through the use of a defined function where the variable is the list name. When run, the code skips the user input.
When I run my code, the section of user input seems to be completely skipped over and as such it just prints an empty list. I've tried messing around with the variable names and defining things at different points in the code. Am I missing a general rule of Python or is there an obvious error in my code I'm missing?
def list_creation(list_name):
list_name = []
num = 0
while num != "end":
return(list_name)
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
list_creation(list_Alpha)
print("This is the first list: " + str(list_Alpha))
list_creation(list_Beta)
print("This is the second list: " + str(list_Beta))
I want the two seperate lists to print out the numbers that the user has input. Currently it just prints out two empty lists.
You need to move the return statement to the end of the function, because return always stops function execution.
Also, what you're trying to do (to my knowledge) is not possible or practical. You can't assign a variable by making it an argument in a function, you instead should remove the parameter list_name altogether since you immediately reassign it anyway, and call it like list_alpha = list_creation()
As a side note, the user probably wants to see the whole "To end, type end as number input" bit before they start giving input.
Dynamically defining your variable names is ill advised. With that being said, the following code should do the trick. The problem consisted of a misplaced return statement and confusion of variable name with the variable itself.
def list_creation(list_name):
g[list_name] = []
num = 0
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
g[list_name].append(num)
g = globals()
list_creation('list_Alpha')
print("This is the first list: " + str(list_Alpha))
list_creation('list_Beta')
print("This is the second list: " + str(list_Beta))
There are a couple of fundamental flaws in your code.
You redefine list_name which is what Alpha and Beta lists are using as the return.(list_name = [] disassociates it with Alpha and Beta so your function becomes useless.)
You return from the function right after starting your while loop(so you will never reach the input)
In your function:
list_Alpha = []
list_Beta = []
def list_creation(list_name):
# list_name = [] <-- is no longer Alpha or Beta, get rid of this!
num = 0
...
The return should go at the end of the while loop in order to reach your input:
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
return(list_name)

How to accept user input of a sequence?

I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x

Categories