I'm trying to put multiple interest rates from one input into a list. I'm assuming just putting a comma between them wont separate them into different variables in the list? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?
interest_rates_list = []
while True:
investment = input("Please enter the amount to be invested ")
periods = input("Please enter the number of periods for investment maturity ")
if int(periods) < 0:
break
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list.append(interest_rates)
If you input is something like:
4 5 12 8 42
then you can simply split it up by space and assign to values list:
values = input().split()
If your input something like 4,5,12, then you need to use split(',').
You can split the input string into several string and then convert it to float. This can be done in one line.
interest_rates = list(map(float, interest_rates.split(",")))
Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.
The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character.
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")
If you take the input, you can convert it to a string by using:
str(interest_rates)
Let this be variable A
So, A = str(interest_rates)
Now, to seperate each entry of the interest rates, we do:
interest_rates_list = A.split(' ')
This function literally splits the string at all spaces and returns a list of all the broken pieces.
NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character. Could be ',' or ';' or ':', etc.
Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing
for i in interest _rates_list:
i = float(i) #or int(i) based on your requirement
Related
Write a function called justify that takes a list of strings and a filed size then returns a single string. The return string will have the original words spaced out in a string of length size. e.g.
justify([“this”, “is”, “a”, “test”],20) à “this is a test”
We are putting 11 characters in a 20 space field, so we have 9 extra spaces. There are 3 places between the words, so we have 3 spaces between each word. If the extra spaces do not divide exactly you can distribute the extra spaces as you like.
'justify([“all”, “too”, “easy”],15) à “all too easy”'
If the field size is too small to add one space between the words then ignore the field size and return the answer with one space between each word.
def justify(x,y):
amount = len(x)-1
final = "".join(x)
ohmy = len(final)
spaces = y - ohmy
real = spaces / amount
print(real)
just = []
length = int(input("length: "))
while True:
hi = input("word: ")
if hi == "end":
break
else:
just.append(hi)
justify(just,length)
This is what I have? Any help?
Seems like you need to
calculate the space taken up by all the words/strings;
find the difference between the limit and the space taken by the words;
divide that difference by the number of gaps between words;
use that result to decide where and how many spaces to put between the words;
construct a string with the words and the spaces.
add logic to check if length of words is greater than field space and react to that
As a foreword, I'm quite new to python, and coding in general.
I'm trying to get the following code to find the specific values in the foodgroups tuple that match with user input (ie: Dairy, Nuts, and Grain) and attach them to Output (ie: Dairy and Nuts). The line with Output was gotten from another website when I was first making this. The code works when the user provides an input that only contains one item without any symbols or spaces (ie: Dairy) but anything extra causes Output to be blank when printed.
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
Output = list(filter(lambda x:userinput in x, foodgroups))
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
print(Output,"is present in your list, " + userinput)
else:
print("Negative.")
I've thought of swapping around foodgroups and userinput, but that results in a TypeError, and turning the tuple into a string has Output always return blank.
I've asked others how to fix this, but they've had no better luck. Any help is appreciated!
If userinput is a comma separated string then split it and use a list:
userinput = input("Enter foodgroups ate in the last 24hrs : ")
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
uin = userinput.split(",")
grp = []
for x in uin:
if x in foodgroups:
grp.append(x)
grp is the user defined foods in foodsgroup
The main thing is that you want to use split to separate individual words from the user input into a list of words. I also swapped x and seafoods in your lambda.
If the user separates each word by one or more spaces, here's how to change your code to work:
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
userfoods = userinput.split()
Output = list(filter(lambda x: x in userfoods, foodgroups))
print(Output,"is present in your list, " + str(userinput))
As other's mention, you need to use split() to separate individual items in the input:
userfoods = userinput.split()
But even after that your if condition isn't correct:
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
The thing to realize here is that or and in are operators that only work with the immediately adjacent 2 values. We can add parentheses to see how this works:
if (((foodgroups[0] or foodgroups[1]) or foodgroups[2]) or (foodgroups[3] in userinput)):
This means that foodgroups[0] or foodgroups[1] evaluates to just the value of foodgroups[0], so foodgroups[1] is basically ignored. This isn't what you want. Instead, you need to check in for each item:
if foodgroups[0] in userinput or foodgroups[1] in userinput or foodgroups[2] in userinput or foodgroups[3] in userinput:
But as you can see this gets very lengthy. So using a loop or list comprehension or generator expression can reduce the amount of code you need to write as others have already shown.
I am using Python 3. I want the user to input the interest and I know that they will answer it with a % symbol following it.
My current syntax is:
interest = input ('Enter the interest ')
(Does using raw_input help? It didn't even work somehow.)
If you only need to parse out % symbols, you can use the replace function, like so:
interest = input('Enter the interest ').replace('%', '')
This replaces any % character from your input with an empty string (thus, removing it).
If the input is going to be 10% only, you will be able to do the following:
interest = input("Enter interest: ")
interest = interest[:-1]
If the user enters 10 % for example, you could always do:
interest = input("Enter interest: ")
interest.strip(' ')
interest = interest[:-1]
If you are sure the user will only input numbers I suggest using str.replace()
This will remove the % sign:
interest = input ('Enter the interest ').replace('%','')
In: 20%
Out: 20
Otherwise you'll need RegEx with python's re module.
This example will ignore any non-digit characters and will only output the digits.
import re
interest = input ('Enter the interest ').replace('%','')
regex_match = re.findall(r'\d*',interest)
out = ''.join(regex_match)```
In: 2a0ac%
Out: 20
Breakdown:
import re - Imports the re(Regex) Module
interest = input ('Enter the interest ').replace('%','') - Grabs the input and replaces the % with nothing
regex_match = re.findall(r'\d*',interest) - This will output all matched digits as a list.
The r'' just tells python that it is a raw string so it won't get parsed.
\d matches a single digit [0-9]
and the * just tells the parser to Match the expression before it (\d) until it finds no more results.
out = ''.join(regex_match) - This will combine all list items into a string.
I'm new to Python and am trying to make a simple program to calculate mean median and mode from numbers input by user. So far I have:
num=[]
UserNumbers=int(input("Enter number sequence separated by spaces: "))
num.append(UserNumbers)
print (num)
I want the user to be able to input multiple int's separated by spaces, however my code only accepts one number. The mean/median/mode part shouldn't be hard as I'm just going to use statistics package in 3.4; just need help with gathering input.
You have to parse the answer if you want it this way.
UserNumbers=input("Enter number sequence separated by spaces: ")
nums = [int(i) for i in UserNumbers.split()]
EDIT:
Duplicate of this question
You can use this one line:
user_numbers = [int(num) for num in raw_input
("Enter number sequence separated by spaces: ").split()]
Notes:
Read about PEP-8
Read about split
List comprehension
def entree_liste():
liste_entier = []
liste_nombre = int(input("Enter list of number separate by space :"))
for chiffre in range(liste_nombre):
liste_entier.append(chiffre)
print(liste_entier)
and my error
liste_nombre = int(input("Enter list of number separate by space :"))
ValueError: invalid literal for int() with base 10: '22 33 44 55'
Basically, I am asking the user for a list of int. If I do liste_entier = list(liste_nombre) they count space as an integer and I don't want to have space in my list only the integer.
The function int() will convert a single value to integer. But you have one giant string with many integer values embedded in it. To solve this problem, first split the giant string into a collection (in this case, a list) of smaller strings, each containing only one integer and then convert each of those strings separately.
To perform the splitting operation, you can use the Python string method .split(). That will return a list of strings. Each of those strings can then be converted to integer:
# get list as string
list_nombre = input("Enter list of numbers separated by space:")
# create list of smaller strings, each with one integer-as-string
list_of_int_strings = list_nombre.split(' ')
# convert list of strings to list of integers
list_of_ints = []
for int_string in list_of_int_strings:
list_of_ints.append(int(int_string)
However, in Python we would more concisely write:
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = ([int(s) for s in list_nombre.split(' ')])
liste_entier = list(map(int, input("Enter list of number separate by space :").split()))
As #Larry suggests, this is a reasonable way to write this in Python
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [int(s) for s in list_nombre.split()]
The problem is that it's not possible to handle exceptions inside the list comprehension. To do this, you may want to write your own, more robust/helpful conversion function
def convert_int(s):
try:
return int(s)
except ValueError as e:
print e
return None
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [convert_int(s) for s in list_nombre.split()]
What you should do is read in the string, of ints separated by spaces then explode it, and case the entires to int.
input = raw_input("Enter list of number separate by space :")
input.split()
then cast he elements to int
its always safer to read in strings, then deal with the return.
The int() function will only take a string that contains only digits. Since a space is not a digit, it will cause an error. To fix this problem, first split the string into a list of smaller strings, and then convert each of the smaller strings into an integer if possible.
string = input('Enter list of space separated numbers: ')
numbers = [int(n) for n in string.split() if n.isdigit()]