So, I'm making a program that asks for user input to define a variable. What I want it to do is keep prompting them to define variables until they terminate the program. I.E. it prompts A1: and they input 2, and then it Prompts A2: and they input 6, and so on, until they press enter without inputting anything. The problem I am having is that I need unique variables for each time it loops. I also want these variables to be able to access the variables defined outside of the function, without using global.
Here is what I've got:
def userinput():
n = 0
while n >= 0:
c = str(n)
v = 'A'+c+':'
v = input(v)
if v != '':
n += 1
else:
while v == '':
break
break
userinput()
As you can see, what it does know is set the user's input equal to v each iteration. I want it to set the first input to A0, then the next iteration, I want it the input to be set to A1, and so on and so forth. Then, after the user has run this, I want to be able to call the variable A1 and get a result. Any ideas?
EDIT:
So, here is my program. It takes input, adds the input to a list, then converts the list items to global variables. I didn't want to use global, but I had to.
def userinput():
n = 0
values = []
while True:
c = str(n)
v = 'A'+c+':'
v = input(v)
values.append(v)
if v != '':
n += 1
else:
while v == '':
values.remove(v)
break
break
for x, val in enumerate(values):
globals()['A%d' % (x)] = val
return values
data = userinput()
Use a list?
def getUserInput():
values = []
while True:
val = input("Enter a value (press enter to finish):")
if not val:
break
values.append(val)
return values
data = getUserInput()
Instead of a while loop, make a for loop wrapped in a while loop, like this:
def userinput():
n = 0
while n >= 0:
for x in range(100):
v = 'A'+x+':'
v = input(v)
if v != '':
n += 1
else:
while v == '':
break
break
userinput()
Once again, here is the answer:
def userinput():
n = 0
values = []
while True:
c = str(n)
v = 'A'+c+':'
v = input(v)
values.append(v)
if v != '':
n += 1
else:
while v == '':
values.remove(v)
break
break
for x, val in enumerate(values):
globals()['A%d' % (x)] = val
return values
data = userinput()
Related
nc = dict(zip(nation,cap))
print("Countries and Capitals :{}".format(nc))
k = 0
while k != 5:
k = input("input : ")
if k == 1:
break
if k != 1:
key = k
print("The capital of {} is {} ".format(key,nc[key]))
#This only makes an error when I type in 1. I want it to stop the program when pressed 1. What can I do about it?
input("input ") returns a string.
You could do:
nc = dict(zip(nation,cap))
print("Countries and Capitals :{}".format(nc))
k = 0
while k != 5:
k = int(input("input : "))
if k == 1:
break
if k != 1:
key = k
print("The capital of {} is {} ".format(key,nc[key]))
input() returns string by default.
So,
You need to take k as integer input using int() function.
k = int(input("input..."))
This one is the only one that goes wrong.
Input
The first line of the input consists of an integer NN, indicating the number of cousins of Cacajao.
In the second line, we will have N values ranging from 1 to N, remembering that each monkey has its own value.
Exit
The output consists of a single line containing the number of cousins of Cacajao that are not in their proper place, if all are in their proper place, print “Each mamaco in its place”.
My code
x = int(input())
first_list = []
sec_list = input().split()
var = 0
for i in range(1,x+1):
first_list.append(i)
new_list = [int(t) for t in sec_list]
if sorted(first_list) == new_list:
print("Each mamaco in its place")
else:
for k in sec_list:
if first_list[var] != k:
var += 1
if var > 0:
print(var)
iterate it's index and compare if sorted list value is same for other list value
else:
for i in range(0,x):
if first_list[i]!=sec_list[i]:
var += 1
or do it this way, no need of another list.
x = int(input())
sec_list = list(map(int,input().split()))
var = 0
for i in range(1,x+1):
if i!==sec_list[i-1]:
var += 1
if var > 0:
print(var)
else
print("Each mamaco in its place")
values = []
while True:
values.append(int(input('Enter a value:')))
if values.append(int(input('Enter a value:'))) == 0:
break
I'm trying to exit the code when an input of 0 is entered. What am I doing wrong?
Each time you call input a new input is being entered, and list.append will add the input to the list and return None, which is not equal to 0.
You can use a variable val to store the input, and use it to test, if you want to store the value 0 in the list, append it before checking:
values = []
while True:
val = int(input('Enter a value:'))
values.append(val) # this will add `0` to the list when it's entered
if val == 0:
break
If you don't want to store it, append it after the if:
values = []
while True:
val = int(input('Enter a value:'))
if val == 0:
break
values.append(val) # this won't add `0` to the list when it's entered
The return of values.append(...) is None. It only updates the variable.
This means your code is always checking None == 0 and will never exit.
a = values.append(int(input('Enter a value:')))
>> Enter a value:0
print(a)
>> None
print(values)
>> [0]
A fix to you code would be:
values = []
while True:
values.append(int(input('Enter a value:')))
if values[-1] == 0:
break
for values[-1], using index -1 is how you get the last value in the list. It's the same as len(values) - 1
After looking around on SO for similair questions and not finding any, I will give it a shot by asking it here. I'll try to be as specific as possible.
Using Python, I am trying to make a piece of code that runs through all possible Harshad numbers and give back an [i] amount of Harshad numbers in a list. To do this, I first made a method isHarshad, which figures out if a number in a list is a Harshad number. Afterwards, I implement this method to print only Hardshad numbers in a list.
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
top = 999999999
for x in (range (1,top)):
if isHarshad(x):
a = a + [x]
count += 1
if count == i:
print(a)
ithHarshad(25)
Running this code returns the first 25 Harshad numbers, which is what I want it to do.
Now my question is: Is it possible to form a loop where it checks a range for Harshad numbers, without making a "top" variable as performed in my code? It feels messy to loop to an arbitrary number like 999999.
I hope my question is a bit clear, and thanks in advance for any input!
Try replacing it with while True: And break the loop when enough numbers are generated. In your code you are running through all the possible numbers which is highly inefficient.
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x = 0
while True:
x += 1
if isHarshad(x):
a = a + [x]
count += 1
if count == i: # Breaks when enough numbers are generated.
break
print(a)
ithHarshad(25)
This will keep adding 1 to x until your count terminates it.
I'm not really sure about what do you mean "checks a range". Did you means you want to show all Hardshad numbers between start to end? Is that true, you can do this:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(start, end):
a = []
count = 0
for x in (range (start,end)):
if isHarshad(x):
a = a + [x]
print(a)
ithHarshad(50,100)
Thanks for the feedback, using a while True: worked for me.
Here is my solution:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x=1
while True:
if isHarshad(x):
a = a + [x]
count += 1
x+=1
if count == i:
print(a)
else:
x+=1
ithHarshad(25)
My way is literally the easiest and smallest way
#get Nums
def getHarshadNums(i):
return [i for i in range(whatever_the_range_is) if isHarshad(i)]
Write a program that asks the user to enter some numbers (positives,
negatives and zeros). Your program should NOT ask the user to enter a
fixed number of numbers. Also it should NOT ask for the number of
numbers the user wants to enter. But rather it should ask the user to
enter a few numbers and end with -9999 (a sentinel value). The user
can enter the numbers in any order. Your program should NOT ask the
user to enter the positive and the negative numbers separately.
Your program then should create a list with the numbers entered (make
sure NOT to include the sentinel value (-9999) in this list) and
output the list and a dictionary with the following Key-Value pairs
(using the input list and the above functions):
I know this is a question that has been on the board 3 times, and I've tried copying other examples, but I still get an error stating I'm missing 1 required positional argument. I've tried changing several things with no resolution. I thought my average functions were working, but at this point I'm not even sure of that. This is also my first time posting anything here, so I'm sorry for poor formatting. Below is my code:
def numList():
values = []
while True:
x = int(input("Enter any amount of numbers or -9999 to quit: "))
if x == -9999: break
values.append(x)
return values
def allNumAvg(values):
whole = []
average = 0
for i in values:
whole.append(i)
average = sum(whole)/len(whole)
return average
def posNumAvg(values):
pos = []
average = 0
for i in values:
if i > 0:
pos.append(i)
average = sum(pos)/len(pos)
return average
def nonPosAvg(values):
non = []
average = 0
for i in values:
if i < 1:
non.append(i)
average = sum(non)/len(non)
return average
print(numList())
def store():
return {'all': allNumAvg(), 'pos': posNumAvg(), 'def': nonPosAvg()}()
print(store())
your functions allNumAvg posNumAvg and nonPosAvg all take 1 argument, values. You're calling them without any arguments. allNumAvg()
try changing to this
values = numList()
def store():
return {'all': allNumAvg(values), 'pos': posNumAvg(values), 'def': nonPosAvg(values)}
Apart for not passing the values and trying to call a dict you are calculating the average before the lists have been filled completely, in your code calculate the average outside the loop when you are finished appending:
def posNumAvg(values):
pos = []
# average = 0 don't need to declare variable
for i in values:
if i > 0:
pos.append(i)
average = sum(pos)/len(pos) # only calculate once when done
return average
In allNumAvg you already have a list of values and you then make another list of the exact same values, just use values itself:
def allNumAvg(values):
average = sum(values )/ len(values)
return average
You can use also use list comprehensions:
def num_list():
# "-9999" is the sentinel value which will break the loop if entered
values = [int(i) for i in iter(lambda:input("Enter any amount of numbers or -9999 to quit: "),"-9999")]
return values
def all_num_avg(values):
average = sum(values) / len(values)
return average
def pos_num_avg(values):
pos = [x for x in values if x > 0]
return sum(pos) / len(pos)
def non_pos_avg(values):
non = [i for i in values if i < 1]
return sum(non) / len(non)
values = num_list()
def store():
return {'all': all_num_avg(values), 'pos': pos_num_avg(values), 'def': non_pos_avg(values)}
I also changed your function names using underscores which is in line with the pep-8 style guide
Ideally when taking user input it is best to use a try/except to catch bad input from the user:
def num_list():
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
return values
values.append(int(inp)) # any input that cannot be cast will raise a ValueError which we catch and then inform the user
except ValueError:
print("Invalid input")
return values
If a user enters no positive or negative numbers then you will also get a zeroDivisionError so you would also need to handle that case by either using try/except again or returning a default values if the list is empty, we can use a default value as we will have already validated the input to make sure is a number:
def non_pos_avg(values):
non = [i for i in values if i < 1]
return sum(non) / len(non) if non else 0
Which can all be done in a single function updating the dict at the end and returning it:
def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
# catch cases where user does not enter a mixture of pos and negative nums of break on the first iteration
# if values etc.. will all evaluate to False for an empty list
store_dict["all"] = sum(values) / len(values) if values else 0
store_dict["pos"] = sum(pos) / len(pos) if pos else 0
store_dict["def"] = sum(non) / len(non) if non else 0
return store_dict
print(store())
Because you are using python3.4 we can also let the statistics module handle the averaging:
from statistics import mean
def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
store_dict["all"] = mean(values) if values else 0
store_dict["pos"] = mean(pos) if pos else 0
store_dict["def"] = mean(non) if non else 0
return store_dict
As per your comment if you want a the dict and the list returned you can return both and unpack:
def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
store_dict["all"] = mean(values) if values else 0
store_dict["pos"] = mean(pos) if pos else 0
store_dict["def"] = mean(non) if non else 0
return store_dict,values
d, vals = store() # unpack
print(d, vals)