Summary : In this program, we will learn about the concept of data types – int vs float .
Here is the program
# Calculate mean without using list data structure # In this program, we will learn about # 1. int vs float print ( "Enter grades to calculate mean/average grade. type e to exit") sum = 0 mean = 0 count = 0 while True : grade = input ( " - ") if grade == "e" : break else : grade = float(grade) sum = sum + grade count = count + 1 mean = sum/count print ( "Average class grade is ",mean)
In every programming language, there is a concept called data types You already know what variables are. However, not all variables can hold all types of data. It is very similar to how you store beer in a pitcher and whiskey in a jar.
However, unlike other programming languages like C or Java, you don’t have to do explicitly specify the type before declaring the variable. It is done for you automatically – rather intelligently by Python. Once it does that, you can very well evaluate what type of variable it has become.
For example, if you look at the code below, what type does grade represent ? You can check it using the built-in function type ( )
grade = input ( " - ") print( type(grade) )
and the result would be a string
A string is a built-in data type in python that can hold a string of characters. But why did grade default to character string and not a number ? Well, in this case, the input function converts whatever the user enters into a string. Here is a sneak peak into the Python documentation on what the input () function does
Now, we want to add and calculate the average of all the grades, right ? In this case, we want the user input to be numeric not a string. That is where type conversion comes in.
While python makes some assumptions on the type of data that a variable should contain, you as a programmer are the final judge of it – and in this case, we need to do some type conversion – from string to a float. We want a float and not int because, we want decimals as well – and that is why we do this.
grade = float(grade)
Python supports 4 different numeric types