Generating raw_inputs based on user input? [Python] - python

Is there any way to generate a number of raw_inputs (With unique variables) based on user input? So, say I had this:
if choice == 1:
noelemen = int(raw_input("Enter total amount of elements: "))
Would there be any way to make it so the integer put in that raw_input field would then "generate" the required amount of raw_inputs? I'd suppose, if it was possible, that it'd make use of functions or something similar, but I'm a bit confused about how I'd get it done to be able to do that.
What I have currently is this:
if noelemen == 1:
first = raw_input("Enter element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
if weight1 is not None:
total_weight = weight1
print "Total mass =", total_weight
if noelemen == 2:
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
weight2 = float(elemen_data.get(second.lower()))
if weight1 is not None:
total_weight = weight1 + weight2
print "Total mass =", total_weight
Which is probably a pretty messy way of doing it, particularly as I'd have to go up to perhaps something like 10 elements, or perhaps even beyond.
So, to repeat... Any way to generate raw_inputs with unique variables based on user input?

how about something like this?
elements = []
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
# will prompt "Enter Element 1: " on the first iteration
userInput = raw_input("Enter Element %s" % (i+1, ))
elements.append(userInput)
Example case:
>>> Enter total amount of elements: 2 # now hit enter
at this point, the value of the variable numberOfPrompts will be 2.
The value of the variable elements will be [], i.e. it is an empty list
>>> Enter Element 1: 3.1415 # hit enter
numberOfPrompts stays 2,
elements will be ['3.1415']
>>> Enter Element 2: 2.7182
elements will be ['3.1415', '2.7182']
Now the for-loop is done and you got your user inputs conveniently in the 0-indexed list elements, which you access like a tuple (array):
>>> elements[1]
2.7182
Edit:
After reading your comment I noticed what you intend to do and, just like the other answer stated, it would be best to use a dictionary for this. This should work:
elements = {}
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
# will prompt "Enter Element 1: " on the first iteration
userInput = raw_input("Enter Element %s" % (i+1, ))
userInput = userInput.lower()
elements[userInput] = float(elem_data.get(userInput))
now elements will look like this:
{'oxygen':15.9994, 'hydrogen':1.0079}
you can iterate over all keys like this (to find out, which elements have been entered):
for element in elements.keys():
print element
# output:
oxygen
hydrogen
To get all values (to sum them up, for instance), do something like this:
weightSum = 0
for weight in elements.values():
weightSum += weight
print weightSum
# output:
17,0073
Keep in mind that this example is for python 2.x. For python 3.x you will need to adjust a couple of things.

I would use a dictionary for this:
noelemen = int(raw_input("Enter total amount of elements: "))
elem={}
for x in xrange(1,noelemen+1):
elem[x]=raw_input("Enter element: ")

Related

How can I find the amount of duplicates an element has within a list?

In this code, I have a user-generated list of numbers and have to find the amount of duplicates a specific element has within that list. I am getting an error in the function. How do I fix this?
def count(list,y):
new_list = []
for j in range(0,x):
if(list[j]==y):
new_list.append(list[j])
else:
pass
print(new_list)
length = len(new_list)
print("The number {} appears {} times in the list".format(y,length))
list = []
x = int(input("Please enter the size of the list you want to create: "))
for i in range(0,x):
value = input("Please enter value of list : ")
list.append(value)
print("The list of the values you entered : {}".format(list))
y = int(input("Which element do you want to find the number? : "))
count(list,y)
There were multiple issues in your code.
In the loop in function count instead j you are using i as index.
initiation of loop index till range(0,x) => x is not defined as the variable is not assigned in this scope, instead use len of the list.
All the inputs added to the list were strings and the one that was searched was an integer.
Other suggestions:
do not use list as a variable name as it is a keyword.
Below this code I am also providing a shorter version of the function count.
def count(mylist,y):
new_mylist = []
for j in range(0,len(mylist)):
print(mylist[j])
if(mylist[j]==y):
new_mylist.append(mylist[i])
else:
pass
length = len(new_mylist)
print("The number {} appears {} times in the mylist".format(y,length))
mylist = []
x = int(input("Please enter the size of the mylist you want to create: "))
for i in range(0,x):
value = int(input("Please enter value of mylist : "))
mylist.append(value)
print("The mylist of the values you entered : {}".format(mylist))
y = int(input("Which element do you want to find the number? : "))
count(mylist,y)
Shorter version
def count(mylist,y):
length = mylist.count(y)
print("The number {} appears {} times in the mylist".format(y,length))
one issue, you're trying to acces the i'th element in list, but i is not initialized. Try replacing i with j
for j in range(0,x):
if(list[i]==y):
new_list.append(list[i])
If you don't mind me taking liberties with your code, here's an example using the Counter from collections. Note that it doesn't do exactly the same thing as your code, as Counter doesn't use indexes as you were using before.
from collections import Counter
input_counter = Counter()
while True:
value = input("Please enter a value (or nothing to finish): ")
if value == '':
break
input_counter[value] += 1
print(input_counter)
y = input("Which number do you want to count the instances of? ")
print(input_counter[y])

printing matrix (2-d) in python

I'm trying to print this code into a matrix but keep getting:
line 22, in <module>
print(matrix[i][j], end=" ")
IndexError: list index out of range
This is my code:
A basic code for matrix input from user
R = int(input("Enter the number of runners:"))
C = int(input("Enter the number of days to log:"))
names_runners = []
runners_time =[]
# Initialize matrix
matrix = []
# For user input
for i in range(R): # A for loop for row entries
a = []
names_runners.append(input("enter name of runner" + str(i+1)))
for j in range(C): # A for loop for column entries
runners_time.append(int(input("enter time for day" + str(j+1))))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end=" ")
print()
The first thing that pops out to me is that the number R is never initialized. I don't know if you maybe did this somewhere else in your code, but perhaps make sure that you have a valid value of R.
The second thing I'm noticing is that in the first outer for-loop, you create an empty list a = []... and then don't do anything with it. Make sure you're appending the actual data you care about into the matrix, because right now you're inserting it into unrelated lists and then appending an empty list. Hence, when you try to iterate over as many items as there are in your names_runners and runners_times lists, you end up going out-of-bounds.
I think it would be better to use dictionary in your case, here:
runners_dict = {}
runners_total = 2
days_to_log = int(input("Enter the number of days to log:"))
for i in range(runners_total):
runner_name = input("enter name of runner" + str(i+1))
runners_dict[runner_name] = []
for j in range(days_to_log):
todays_time = int(input("enter time for day" + str(j+1)))
runners_dict[runner_name].append(todays_time)
print(runners_dict)
Results:
Enter the number of days to log:2
enter name of runner1joe
enter time for day1123
enter time for day2321
enter name of runner2bill
enter time for day1123
enter time for day2321
{'joe': [123, 321], 'bill': [123, 321]}

How to have a sequence variable within a for loop

def main():
for row in range (7):
assignment = int(1)
if row == 1:
for assignment_number in range(0,8):
assignment_number+1
for i in range(0,7):
assignment_mark = float(input(("Please enter your mark for assginment" assignment_number,": "))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
main()
So this is my code above,
I'm basically trying to work out how I could say for each input variable "Please enter your mark for assignment x (from 1 up to 7).
Which will loop, so once they enter it for assignment 1, it then asks the same question for assignment 2.
I hope this makes some sense. I'm new to programming in general and this just happens to also be my first post on stack! Be gentle (:
Thanks!
There are a few problems with your code:
assignment_number+1 without assigning it to a variable does nothing, and even if you did, that value would be lost after the loop. If you want to offset the numbers by one, you can just use range(1, 8) or do +1 when you actually need that value of that variable
in your second loop, your loop variable is i, but you are using assignment_number from the previous loop, which still has the value from the last execution, 7
you have to store the values for assignments_mark and assignment_weight somewhere, e.g. in two lists, a list of tuples, or a dict of tuples; since assignment numbers start with 1 and not 0, I'd recommend a dict
You can try something like this, storing the marks and weights for the assignments in a dictionary:
assignments = {}
for i in range(7):
assignment_mark = float(input("Please enter your mark for assginment %d: " % (i+1)))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
assignments[i+1] = (assignment_mark, assignment_weight)
print(assignments)
Let the loop do the counting, then use string formatting.
And you only need a single loop to collect each pair of events
from collections import namedtuple
Assignment = namedtuple("Assignment", "mark weight")
assignments = []
for idx in range(7):
print("Please enter data for assignment {}".format(idx+1))
mark = float(input("mark: "))
weight = float(input("weight:"))
assignments.append(Assignment(mark, weight))
print(assignments)

Try and Except with a list and multiple inputs

I am making a D&D style character generator and I am rolling the stats for them and allowing them to allocate them to the ability score they want. I would like to have the ability to start at the same stat they were at vs the entire section over again.
Here is what I have
from random import randint
def char_stats():
# roll 4 D6s drop the lowest number and add the highest 3
s1,s2,s3,s4,s5,s6 = ([],[],[],[],[],[])
for x in range(4):
s1.append(randint(1,6))
s2.append(randint(1,6))
s3.append(randint(1,6))
s4.append(randint(1,6))
s5.append(randint(1,6))
s6.append(randint(1,6))
stat1 = sorted(s1)
stat2 = sorted(s2)
stat3 = sorted(s3)
stat4 = sorted(s4)
stat5 = sorted(s5)
stat6 = sorted(s6)
return sum(stat1[1:]),sum(stat2[1:]),sum(stat3[1:]),sum(stat4[1:]),sum(stat5[1:]),sum(stat6[1:])
a = list(char_stats())
print "Please choose one of the following for your stat: {}".format(a)
while len(a) > 0:
try:
Strength = int(raw_input('Please input one of these stats for your Strength:\n'))
if Strength in a:
a.remove(Strength)
print a
Wisdom = int(raw_input('Please input one of these stats for your Wisdom:\n'))
if Wisdom in a:
a.remove(Wisdom)
print a
Intelligence = int(raw_input('Please input one of these stats for your Intelligence:\n'))
if Intelligence in a:
a.remove(Intelligence)
print a
Constitution = int(raw_input('Please input one of these stats for your Constitution:\n'))
if Strength in a:
a.remove(Constitution)
print a
Dexterity = int(raw_input('Please input one of these stats for your Dexterity:\n'))
if Dexterity in a:
a.remove(Dexterity)
print a
Charisma = int(raw_input('Please input one of these stats for your Charisma:\n'))
if Charisma in a:
a.remove(Charisma)
except ValueError:
print "Incorrect Input"
continue
I have tried nesting each of the if statements (which I believe is very bad form) and have similar results. I have also tried grouping all the inputs into the try and not the calculations and have gotten the same results. Any advice?
You need to use the "loop until valid" logic for both the format (int) of the input, and the value (is it in the list of rolled stats?). The basic logic is this:
while True:
# get input
# check input
# if input is valid,
# break
In your case, this looks something like
while True:
user = input("Please enter a stat to use")
if user.isnumeric():
stat_choice = int(user)
if stat_choice in a:
break
Now, to make effective use of this, you need to parametrize your six stats and put those into a loop:
stat_name = ["Strength", "Wisdom", ...]
player_stat = [0, 0, 0, 0, 0, 0]
for stat_num in range(len(player_stat)):
while True:
user = input("Please input one of these stats for your" + \
stat_name[stat_num] + ": ")
# Validate input as above
player_stat[stat_num] = stat_choice
Note that you can similarly shorten your char_stats routine to a few lines.
Does that get you moving?
You have at least one function in your code (char_stats) so I feel like you know how to do functions.
This is a great place to use a function.
My suggestion, for this code, would be to write a function that incorporates the try/except, the asking of the question, and the checking against the stats list.
Something like this:
def pick_a_stat(stats, prompt):
"""Prompt the user to pick one of the values in the `stats` list,
and return the chosen value. Keep prompting until a valid entry
is made.
"""
pass # Your code goes here.

How do i order the numbers a user inputs?

I am basically wondering how i can store the users inputs and put them in order from least to greatest to help them find median mode or range.
from __future__ import division
amtnum = 0
sumofnums = 0
print "Hello, This program will help find the mean of as many numbers as you want."
useramtnum = input("How many numbers will you need to enter: ")#asks user to say how many numbers there are
while amtnum < useramtnum: #Tells program that while the amount of numbers is less than the users input amt of numbers to run.
amtnum = amtnum + 1 #Tells that each time program asks for number add one to amt of numbers
entnum = (int(raw_input("Enter a number:"))) #Asks user for number
sumofnums = entnum + sumofnums #Adds users number to all values
print "The amount of your numbers added up were:", sumofnums
print "The average/mean of your numbers were:", (sumofnums/useramtnum)
put 'em in a list and sort it
mylist = []
while ...
mylist.append(entnum)
mylist.sort()
print mylist
Utilize the basic data structure called a list!
Before your while loop, create a list (aka array)
user_input_list = []
After you get the individual number from the user in the while loop, add the input to the list (in the while loop)
user_input_list.append(entnum)
After the while loop, sort the list (it will sort in place)
user_input_list.sort()
Then the list has every input from the user in sorted order, least to greatest.
To access the last item in the list, use array accessors.
user_input_list[-1]
To access median, utilize the fact you can use the length of the list. Access the length(list)/2 item
user_input_list[int( len(user_input_list) / 2)] #int cast used to remove decimal points
I am by no means a Python expert (as in, this is like my third python program), but I think it's generally easier to call functions, be it in Python or in any other language. It makes code more readable.
These are all basic math functions, so I don't feel I deprived you of knowledge by just writing them. I did, however, leave the range function for you to write. (Since mylist is sorted, I'm sure you can figure it out.)
This allows the user to continually enter numbers and have the mean, median, and mode spit back at them. It doesn't handle non-integer input.
from collections import Counter
from decimal import *
def getMode(l):
data = Counter(l)
mode = data.most_common(1)
print "mode:", mode
def getMean(l):
length = len(l)
total = 0
for x in l:
total = total + x
mean = Decimal(total) / Decimal(length)
print "mean:", mean
def getMedian(l):
median = 0
length = len(l)
if (length % 2 == 0):
median = (l[length/2] + l[length/2 - 1])/2.0
else:
median = l[length/2]
print "median:", median
mylist = []
print "Enter numbers to continually find the mean, median, and mode"
while True:
number = int(raw_input("Enter a number:"))
mylist.append(number)
mylist.sort()
getMean(mylist)
getMedian(mylist)
getMode(mylist)
Solution to solve your problem :
Use a list : More on Lists
Example :
numbers = []
while amount < counter:
...
numbers.append(num)
print sorted(numbers)
You can take a look at modification of your code below.
numbers = []
print "Hello, This program will help find the \
mean of as many numbers as you want."
while True:
try:
counter = input("How many numbers will you need to enter: ")
except:
print "You haven't entered a number."
else:
break
amount = 0
while amount < counter:
try:
num = input("Enter a number: ")
except:
print "You haven't entered a number."
else:
amount += 1
numbers.append(num)
print "The amount of your numbers added up were:", (sum(numbers))
print "The average/mean of your numbers were:", ( (sum(numbers)) / counter)
print "My list not in order:", numbers
print "My list in order:", sorted(numbers)

Categories