Copyright © Wei MEI, MLMS™—all rights reserved. 🀤
Python can store and manipulate numbers. Python has two types of numeric values: integers (whole numbers) or float (numbers with decimal places)
When naming variables follow the PEP-8 Style Guide for Python Code
Converting to numeric values
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int(‘010’, 0) is not legal, while int(‘010’) is, as well as int(‘010’, 8).
The integer type is described in Numeric Types — int, float, complex.
Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.
Return a floating point number constructed from a number or string x.
If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be ‘+’ or ‘-‘; a ‘+’ sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:
sign ::= “+” | “-” infinity ::= “Infinity” | “inf” nan ::= “nan” numeric_value ::= floatnumber | infinity | nan numeric_string ::= [sign] numeric_value
Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity.
Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.
For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__().
If no argument is given, 0.0 is returned.
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.
For a general Python object x, complex(x) delegates to x.__complex__(). If __complex__() is not defined then it falls back to __float__(). If __float__() is not defined then it falls back to __index__().
Note: When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex(‘1+2j’) is fine, but complex(‘1 + 2j’) raises ValueError.
Numeric Data Types¶
So now you’ve learned how to work with strings, let’s take a look at how we work with numbers inside our Python code as well. Just like strings numbers can be stored inside variables.
We always want to give those variables nice meaningful names get in the habit of that right away, and we can pass those variables into functions like the print statement.
So the print statement can take a variable that contains a string, a variable that contains a number.It really doesn’t matter either way, it’ll just print what it’s received out onto the screen.
1 2 3
# You can use variables to store numeric values pi = 3.14159 print(pi)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
days_in_feb = 28 # The print function can accept numbers or strings print(days_in_feb) # The + operator can either add two numbers or it can concatenate two strings # it does not know what to do when you pass it one number and one string # This line of code will cause an error print(days_in_feb + ' days in February') # You need to convert the number to a string to display the value # This line of code will work print(str(days_in_feb) + ' days in February')
So I’ve got Visual Studio open. Let’s go and take a look at some code. So I’m going to create my variable pi 14159 I know of is more digits and app but I’ve gotta stop somewhere and I’m storing that value in a variable and then I can just print that value up on the screen using control S to save here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Because the variables are assigned numeric values when created # Python knows they are numeric variables first_num = 6 second_num = 2 # You can peform a variety of math operations on numeric values print('addition') print(first_num + second_num) print('subtraction') print(first_num - second_num) print('multiplication') print(first_num * second_num) print('division') print(first_num / second_num) print ('exponent') print(first_num ** second_num)
1 2 3 4 5 6 7 8 9 10
# Python has to guess what datatype a variable should be # since the input function returns a string, the variables it populates # will hold string values first_num = input('Enter first number ') second_num = input('Enter second number ') # Because first_num and second_num are string variables the + operator # concatenates them just like concatenating first_name and last_name print(first_num + second_num)
1 2 3 4 5 6 7 8 9 10 11
first_num = input('Enter first number ') second_num = input('Enter second number ') # If you have a string variable containing a number # And you want to treat it as a number # You must convert it to a numeric datatype # int() converts a string to an integer e.g. 5, 8, 416, 506 print(int(first_num) + int(second_num)) # float() converts a string to a decimal or float number e.g. 3.14159, 89.5, 1.0 print(float(first_num) + float(second_num))
Check the following script and try to find the mistake:
1 2 3 4 5 6
# Ask a user to enter a number # Ask a user to enter a second number # Calculate the total of the two numbers added together # Print 'first number + second number = answer' # For example if someone enters 4 and 6 the output should read # 4 + 6 = 10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Ask a user to enter a number first_number = input('Enter a number: ') # Ask a user to enter a second number second_number = input('Enter another number: ') # Calculate the total of the two numbers added together answer = float(first_number) + float(second_number) # Print 'first number + second number = answer' # For example if someone enters 4 and 6 the output should read # 4 + 6 = 10 print(first_number + ' + ' + second_number + ' = ' + str(answer)) # If you do not want the decimal places you could round the answer print(first_number + ' + ' + second_number + ' = ' + str(round(answer)))