How can test a variable if it is an integer? - python

As the title might specify, I want to ask how can I test a variable if it is an integer. I have seen other topics and they don't seem to have code that works or that I know how to use.
print("Enter the weight of the bag in grams.")
weight = float(input()) # float was used as it might be a decimal sometimes
amtcoin = weight / 3.56
How do I test if amtcoin is a integer? As the variable suggests, it is the amount of coins and you cannot have a fraction of a coin.
Thanks.

You can convert to float as you did and then check with is_integer method:
float(weight).is_integer()

amtcoin variable is instance of class you declare it. Declare it as float and if you want to know if it's a fraction or not check amtcoin % 1 == 0

Try something like this:
if int(amtcoin) == amtcoin:
do_something()
If it is int, this condition will be met.

Related

Python: Limit the maximum amount of decimals in all print calls

I have a script with a lot of print calls.
I want to limit all the printed numbers to a maximum of 5 decimals, but changing it by hand with f_strings or formatting would be a lot of work.
Is there any way to specify at the beginning of the script that whenever I call a print function or use an f string, I do not want to know more than 5 (or n) decimals without having to change the formatting of every call I make?
I just care about the representation of the screen. It does not matter to me if the number under the hood has more decimals.
Essentially, instead of having to rewrite each print to this
print(f'{value:.6f}')
I would like somethink akin to this:
#define max_print_length = 10
Thanks!
I have looked for ways to try and change the behaviour of the print function or defining some kind of flag at the beggining of the script but, so far I'm empty handed. I found a couple of solutions but they are for different programming languages.
As I do not think there is a method of setting a float precision for the entire code, maybe a not-so-elegant custom print method that takes in multiple parameters would be useful. For example-
def myprint(dict_to_print: Dict[str,float], precision:int)->None:
to_print = f""
for key, value in dict_to_print.items():
to_print += f"{key}: {value:.{precision}f}\n"
print(to_print)
myprint({'1st': 12.9943943504538, '2nd': 9.4093485739048}, 2)
>>> 1st: 12.99
2nd: 9.41
PS. a one-liner:
def myprint(dict_to_print: Dict[str, float], precision: int) -> None:
print("".join([f"{key}:{value:.{precision}f}\n" for key, value in dict_to_print.items()]))

Not understanding why my program doesnt work

I am pretty new to programming and python. My question is I had these lines running but first I'll explain. I wanted to write a program that would ask your weight in pounds and my program would convert it to kgs. Now here is the correct answer:
weight = input ("What is your weight in pounds? ")
converter = int(weight) * 0.45
print (converter)
Now I wanted it to work for decimals (lbs in decimals). So I wrote this:
weight = input ("What is your weight in pounds? ")
converter = int(0.45) * weight
print (converter)
But the second program doesn't work. Can anyone explain why? Thank you
int(0.45) converts the 0.45 to an integer (whole number) which is truncated to 0 so you are effectively multiplying any input by 0.
In the original program you were taking the input as a string with the input command and then converting that string to an integer with int(weight). If you want to have the program work with decimals then you would want to use float(weight)
In your second program you are casting to int the number 0.45 which evaluates to be 0 In order for this to work with float, just remove the int() before the 0.45 , because it's a floating number the whole expression will be float.
weight = input ("What is your weight in pounds? ")
The above code always returns a string.
If you try running the following after the above line you will notice it prints str, which means its a string data type.
print(type(weight))
Now that we know the type of data store in the variable weight is of str, we need to ensure that we convert it into a number before using it in a mathematical equation.
In your case i understand that, in your second program you want to have your output of the variable converter in decimals.
hence you have to rewrite the line as follows:
converter = 0.45 * float(weight)
In order to ensure that the converter variable holds a decimal value, you can try:
print(type(converter))
if the above line gives the output as float, you have got your intended output.
For future reference, you may refer this link which shows all the data types available in Python: https://docs.python.org/3/library/datatypes.html

Smallest Number in Python

PROBLEM STATEMENT: Write a Python script to determine the smallest positive double number in Python.
Your code should produce a variable called smallest_num which is the smallest double number in Python.
Your script should determine this value in a systematic manner. You may NOT simply call a built-in function that returns this value or access a built-in variable that contains this information. This includes np.finfo() and other built-in functions or variables.
The setup code gives the following variables:
Your code snippet should define the following variables:
Name Type Description
smallest_num floating point The smallest number possible in Python
Attempted Solution
import numpy as np
import math
def machineEpsilon(func=float):
machine_epsilon = func(1)
while func(1)+func(machine_epsilon) != func(1):
machine_epsilon_last = machine_epsilon
machine_epsilon = func(machine_epsilon) / func(2)
return machine_epsilon_last
sum_f = machineEpsilon(np.float64)
smallest_sum = float(sum_f)
print(isinstance(smallest_sum, float))
print(smallest_sum)
Output
True
2.220446049250313e-16
However, I am unable to get the correct answer. As the true smallest number is much smaller than the printed value. I know this number will be underflow to zero and I might want to do some comparison here. But i am a bit stuck. Any thoughts?
Probably the most reasonable thing to do would be to directly compute the next double-precision float after 0.0:
smallest_num = np.nextafter(0, 1)
This does not simply call a built-in function that returns the smallest positive double-precision float, or access a variable pre-set to that value. However, people get weird when they see function call syntax in problems like this, so it risks being marked incorrect anyway.
Taking advantage of how IEEE754 floating-point representation and rounding works, we can start with 1.0 and divide by 2 until the next division would underflow:
smallest_num = 1.0
while smallest_num / 2:
smallest_num /= 2

How can an average equation be added to this?

I am taking GCSE programming and have be set a task to create a program which takes "n" amount of numbers and works out the average.
#presets for varibles
nCount = 0
total = 0
average = 0.0
Numbers = []
ValidInt = False
#start of string
nCount = (input("How many numbers? "))
print(nCount)
while not ValidInt:
try:
int(nCount)
ValidInt = True
except:
nCount = input("Please Enter An Interger Number")
#validation loops untill an interger is entered
for x in range (int(nCount)):
Numbers.append(input("Please Enter The Next Number"))
This is what i have so far but cannot think how i can code it to work out an average from this information? Any help is much appreciated, Thank you(i am not looking for answers just help in what function as i should use)
You're really close to the answer. Looks like you've got everything setup and ready to calculate the average, so very good job.
Python's got two built-in functions sum and len which can be used to calculate the sum of all the numbers, then divide that sum by how many numbers have been collected. Add this as the last line in your program and check the output.
Note: Since inputs were taken as integers (whole numbers) and the average will usually be a non-whole number, we make one of the numbers a float before calculating the average:
print(sum(Numbers)/float(len(Numbers)))
Edit: Or, since you've got a variable that already holds how many numbers the user has input, nCount, we can use this calculation, which will give the same answer:
print(sum(Numbers)/float(nCount)).
Try both and choose one or make your own.

Parameter in Python

Let's say there is a parameter n. Can n be any numbers? For example, question like this: Given a non-negative number num, return True if num is within 2 of a multiple of 10. This is what I am thinking:
def near_ten(num):
n = int #So I assume n can be any integer
if abs(num - n*10) <=2:
return True
Return False
However, there are two problems. First, in n*10, * is a unsupported operand type cuz I thought I could use Python as a calculator. 2nd, I cannot just simply say n = int, then n can be viewed as a variable as any number (or integer) in a math function. If there is a way that I could use n in that way, then life would be so much easier.
Finally I figure it out in another way which doesn't include "n" as a parameter:
def near_ten(num):
if num%10<=2:
return True
if (num+2)%10<=2:
return True
return False
However, I'm still curious about "n" as a parameter mentioned before. Since I'm just a starter, so this is really confusing.
In Python, int is a type. Types are first-class objects in Python, and can be bound to names. Of course, trying to multiply a type by a number is usually meaningless, so the operation is not defined by default. It can be referred to by the new name though.
n = int
print(n(3.4))
print(n('10') == 10)
Here is a much simpler solution:
def near_mult_ten(num):
return abs(num - (num+5) // 10 * 10) <= 2
Edit: Fixed.
try this:
d=a%10
if d<=2 or d>=8:
return True
return False
I am new to coding as well so forgive any mistakes.
i am not sure if you have ran your code or not, but python is a high level interpreted language, python CAN distinguish between variable types and therefore you do not need to explicitly declare them, your function header is valid.
you can also do operations between integers and floats/doubles without the need of casting, python already handles that for you
your function will raise an error in any compiler, ur n variable is declared, you have defined it, but you have not initialized it

Categories

Resources