Trying to find average yields TypeError: unsupported operand type(s) for +: 'int' and 'str' - while-loop

I am trying to find the average in a list of ages for boys and girls in Python 3.9.1 for an assignment. My code starts by defining a list for both boy and girl ages.
bagelist = [];
gagelist = [];
I then include a while loop to gather the ages and end it by trying to use the sum() / len() function to get the average for both lists.
v4 = input("enter name")
while v4 != "":
v5 = input("enter sex (boy/girl) ")
v6 = input("How old are they? ")
if(v5 == "boy"):
boys += 1
bagelist.append((v6))
elif(v5 == "girl"):
girls += 1
gagelist.append((v6))
v4 = input("Is there anyone else to enter? If not, press ENTER.")
sum(bagelist) / len(bagelist)
sum(gagelist) / len(gagelist)
This just returns the TypeError: unsupported operand type(s) for +: 'int' and 'str' error when I go through the program though and will not average the lists. I have tried using the mean() function as well by typing statistics import mean as well and it does not seem to want to import. I was hoping someone here would be able to tell me how to derive the mean from these lists without receiving this error.
I will say that I apologize if I am not importing the mean function quite right as I am incredibly new to Python as well as programming overall. I do also apologize if my question isn't written well as I am also new to Stack Overflow. Constructive criticism is appreciated on these as well as the question at hand. thank you very much for any help.

Related

Create a new column based on specific character from existing column fail : 'str' object has no attribute 'str'

I hope you can help me. I'm looking for to classify some product based on the size: 40ML or other.
Here is my piece of code:
1. Dataframe creation
test = {'Name':['ProductA 40ML','ProductB 100ML','ProductC 40ML','ProductD 100ML']}
df1=pd.DataFrame(test)
2. Function built for classification
def size_class(row):
if row['Name'].str.contains('40ML'):
val = '40ML'
else:
val = 'other'
return val
df1['size_classification'] = df1.apply(size_class, axis=1)
Error message:
However the function returns the following error: AttributeError: 'str' object has no attribute 'str'
Question
Would you please be able to help me fix this one? I had a look at existing issues but couldn't find any answer addressing this.
I figure out some things you missed in your implementation:
In Python for most of the cases of membership tests, the operator in is more relevant than contains. Membership test operations documentation, see more details in this SOF question: Does Python have a string 'contains' substring method?
The default of the apply function is to look at the value of specific column, so you don't need to apply it on the whole data frame, but only on the relevant column.
The function applied with 'apply' looks separately on every cell's value. In your case, it's a string so you don't need to cast things.
So, the code that fixes your bugs is:
import pandas as pd
test = {'Name':['ProductA 40ML','ProductB 100ML','ProductC 40ML','ProductD 100ML']}
df1=pd.DataFrame(test)
def size_class(row):
if '40ML' in row:
val = '40ML'
else:
val = 'other'
return val
df1['size_classification'] = df1['Name'].apply(size_class)
print(df1.head())

How to assign Pandas.Series.str.extractall() result back to original dataset? (TypeError: incompatible index of inserted column with frame index)

Dataset brief overview
dete_resignations['cease_date'].head()
gives
dete_resignations['cease_date'].value_counts()
gives
of the code above
What I tried
I was trying to extract only the year value (e.g. 05/2012 -> 2012) from 'dete_resignations['cease_date']' using 'Pandas.Series.str.extractall()' and assign the result back to the original dataframe. However, since not all the rows contain that specific string values(e.g. 05/2012), an error occurred.
Here are the code I wrote.
pattern = r"(?P<month>[0-1][0-9])/?(?P<year>[0-2][0-9]{3})"
years = dete_resignations['cease_date'].str.extractall(pattern)
dete_resignations['cease_date_'] = years['year']
'TypeError: incompatible index of inserted column with frame index'
I thought the 'years' share the same index with 'dete_resignations['cease']'. Therefore, even though two dataset's index is not identical, I expected python automatically matches and assigns the values to the right rows. But it didn't
Can anyone help solve this issue?
Much appreciated if someone can enlighten me!
If you only want the years, then don't catch the month in pattern, and you can use extract instead of extractall:
# the $ indicates end of string
# \d is equivalent to [0-9]
# pattern extracts the last digit groups
pattern = '(?P<year>\d+)$'
years = dete_resignations['cease_date'].str.extract(pattern)
dete_resignations['cease_date_'] = years['year']

Error: Kotlin: The floating-point literal does not conform to the expected type Float

I was making a simple maths calculator in kotlin, an error appeared on my screen when I tried to initialize the value of one of the variables used as 0.00 for float integer.
var x:Float= readLine()!!.toFloat()
var y:Float= readLine()!!.toFloat()
var sum:Float=0.00// the error message is showcased in this line
sum=x+y
println("Addition " + sum)
This is a key difference between Java and Kotlin. Kotlin does not do numeric type promotion like Java does. The comments to your question are showing you how to deal with this, by either matching up the two types Double and/or Float to begin with, or by explicitly converting one or the other so that the two types match up.
Your problems goes away if you make use of Kotlin's ability to infer variable types by taking the type specifications off of your variable definitions. The fact that Kotlin infers types is one reason it does not promote numeric types. Mixing the two would lead to a lot of confusion.
Here's an example of how to fix and simplify your code's type mismatch issues using type inference:
var x = readLine()!!.toFloat()
var y = readLine()!!.toFloat()
var sum = x + y
println("Addition " + sum)
I understand that this may be just test code that you're using to understand Kotlin better. With that said, I'll point out that this code will crash if your user types in non-numeric input. You could fix this by putting a try/catch around your input lines, and providing an nice error message. You might want to put each input in a loop, continuing to ask for an input until the user does provide a response that is of the expected format.

Getting a Maybe instead of an Array's value

New to elm here, and at first it's driving me absolutely crazy not knowing the ins and outs of this picky language (even after reading a sh**load about it because it's just so different and finicky...I guess that's the nature of a functional lang) so when you try doing a simple thing it's like pulling hair at first.
I am getting the following error:
The right side of (==) is causing a type mismatch.
29| get 0 arrayOfValues == 'X'
^^^
(==) is expecting the right side to be a:
Maybe Char
But the right side is:
Char
Hint: With operators like (==) I always check the left side first. If it seems
fine, I assume it is correct and check the right side. So the problem may be in
how the left and right arguments interact.
Test:
it "blah blah blah" <|
let
someArray =
[ 'P', ' ' ]
in
expect (MyModule.doSomething someArray 'P') to equal 1
MyModule
doSomething : List Char -> Char -> Int
doSomething arrayOfValues symbol =
let
grid =
fromList arrayOfValues
found =
get 0 arrayOfValues == symbol
in
if found then
1
else
0
Now I'm assuming but not sure, that it's getting Nothing or something when trying to pull the first value out of my array but not sure. Maybe Char I assume is returning Nothing? donno, probably have other issues going on with it too.
I'd like to get the code above working, then refactor..I'm sure there's probably a more elegant way to code what I've coded above but first thing's first, fixing this error and understanding it better with the existing code. The error message while nice isn't that obvious to me as to how and what to handle. I have assumptions but not fully sure how to handle the behavior here of whatever is causing the issue.
Array.get returns a value wrapped in a Maybe because there might not be a value present at the specified index in the array. If you want to check whether the value at index 0 present and equal to 'X', you can compare to Just 'X':
get 0 arrayOfValues == Just 'X'
Like the error message says, the compiler found that the left side of == is a Maybe Char and the right is Char. You need to convert one to another to use ==. In this case, you probably want to change the right side as I suggested above.

Does the += operator just not exist in VBA?

I'm trying to incriment the value in a cell, but despite documentation saying Visual Basic allows the += operator, it's just giving me "Compile error: Expected: expression".
Range("CellName").Value += 1
Is what's breaking, but if I do
Range("CellName") = Range("CellName") + 1
It works fine
No, it doesn't exist in VBA.
VB.NET might take += (though I'm not even sure about that).
You'll have to use
Range("CellName").Value = Range("CellName").Value+1
A good reference can be found here
An "official" list of VBA-operators can be found in VBA help here:
Help --> Microsoft Visual Basic Help --> Visual Basic for Applications Language Reference --> Visual Basic Language Reference --> Operators --> Arithmetic Operators (online here )
Maybe controversially, but the next advice would have saved me lots of time and headaches:
I'd say it's better to forget everything about VB and focus at VBA, as the two are different languages. People don't mention "Oh, OCaml, APL, PHP or Fortran have increment operators", as it's off-topic if the scope is VBA. In the same way, what VB has or has not is off-topic, and usually it only adds to the confusion because it's resemblance. Better use the MS-Office provided "local" Visual Basic for Applications Language Reference as provided by the help system, or online:
http://msdn.microsoft.com/en-us/library/office/gg264383%28v=office.15%29.aspx
It's really annoying. I made the following functions to make my life a bit easier:
' ++
Function pp(ByRef x, Optional y = 1)
x = x + y
pp = x
End Function
' --
Function mm(ByRef x, Optional y = 1)
x = x - y
mm = x
End Function
Doesn't really help your situation as you'd still have to type the same amount:
Range("CellName") = pp(Range("CellName"))
but for simple loop increments it helps :
do while cells(x,1) <> ""
pp x
loop
No it does not have it for numbers, e.g. see http://msdn.microsoft.com/de-de/library/215yacb6%28v=vs.80%29.aspx / http://msdn.microsoft.com/en-us/library/cey92b0t.aspx