How to get a irrational number as a user input in python? Like squared root of 2
something like :
Irrational_Number = float(input("ENTER a Irrational Number : "))
>>> ENTER a Irrational Number : (USER INPUT)
and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.
How User Can do this Directly in command line python (3.8)
I searched this question everywhere but there is nothing about that...
First of all, you're casting your input to a float, so to be precise (which is important if we're bandying around terms like Irrational Number) then we have to highlight the assumption that were talking about approximations to Irrational Numbers here.
That done, there's a few ways you can explore a solution:
The first would be to define a namespace in which you map string names to numeric equivalents - a simple dict could do the trick, like:
numbers_as_words = { "e",2.718281828459045
"pi",3.141592653589793
"phi",1.618033988749895
"sqr2",1.4142135623730951
"feet_to_meters",0.3048
"lbs_to_kg",0.453592
"miles_to_kilometers",1.60934
"gallons_to_litres",3.78541 }
I've padded that out with some non-irrational place-holders too, in case you wanted to embed some simple conversion type logic.
Then, you'd need to take your input as a string, perform a simple replace function on the string to resolve any matching strings, and viola , you've got a mixed numeric/string input method.
def replace_names_and_return_float(user_input, mapping):
for k,v in mapping.items():
user_input = user_input.replace(k,str(v))
return float(user_input)
Irrational_Number = replace_names_and_return_float(input("ENTER a Irrational Number : "), numbers_as_words )
Then it's just up to you to maintain that numbers_as_words dictionary to contain all the substitutions you want to recognise. That could get tedious, but it ought to be enough to get you started.
If you find some official list of irrational number approximations, you might be able to download it, and construct a numbers_as_words mapping as an automated process, but I've not Googled that just now.
Please find below code snippet:
import re
g = input("Enter your irrational number : ")
if g=='pi':
g=math.pi
elif "root" in g:
root=float(re.search('[0-9]+', g).group())
number=float(re.search('(\d+)(?!.*\d)', g).group())
g=number**(1/float(root))
print(g)
Advantage of using this would be:
There is no manual value inserted
You can build it for every symbol present in math lib
Can be extended for other operations as well
Related
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
Am trying to make a simple program to convert binary number to decimal number. I'd like to first write a condtion whether to check the given number is a binary or not. How do i do that?
Except that, the program works normally without any errors but am afraid when a non binary number is given, it still does the job.Input
print("Binary to Decimal")
bin = input("Give a binary number : ")
bin = [int(i) for i in bin]
powers = [i for i in range(len(bin)-1,-1,-1)]
for i in range(len(bin)):
bin[i] = bin[i] * 2**(powers[i])
decimal = sum(bin)
print("The corresponding Decimal digit is : %d"%(decimal))
Output
Binary to Decimal
Give a binary number : 101
The correspnding Decimal digit is : 5
Also if u find any corrections or want to make any suggestions, please feel free to suggest me below.
Try pythonic way is not to test, but to try the conversion and catch the exception if the input is bad. This is the Easier to ask for forgiveness than permission prinicple:
b = input("Give a binary number : ")
try:
print(int(b, 2))
except ValueError:
print("not binary")
If you still want to check an easy test is to use all():
if all(n in ('1','0') for n in b):
# it's all 1's and 0's
You can check that if the string contains any other number rather than 0's and 1's then it is not a binary number.
you can check with regular expression
import re
if re.match("^[01]+$", '011001'):
//then proceed
else:
//do something for non-binary
Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.
I'm making a calculator on Python 3.4. The calculator will ask the user to enter a number. I want to restrict this so they can only enter a number (which I am fine about) or to press the 'C' key to clear the calculator. I seem to be getting stuck with allowing the C as well as any integer. Anyone suggest any way of going about this?
Thanks
You could use this code, assuming the user shall be able to enter numbers consisting of several digits like 1337, but no decimal points. Inputs being mixed of digits and "C" are invalid, "C" only gets detected if the input contains only the letter "C" and nothing else. Leading and trailing whitespaces are ignored.
def get_input():
inp = input("Enter a number or 'C' to clear: ").strip()
if inp.upper() == "C":
return "C"
if inp.isdigit():
return int(inp)
else
return None
This function will return the entered number as integer, or the string "C", or None if the input was invalid.
Assuming you're taking in the user inputs one by one:
import string
allowed = string.digits+'C'
if input in allowed:
doSomethingWith(input)
Is this what you're looking for?
I'm making a game where the "Computer" tries to guess a number you think of.
Here's a couple snippets of code:
askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'
That's the computer asking if it got the number right, using random.randint to generate a random number. The problems are 1) It won't let me combine strings and integers, and 2) Won't let me use the variables as the min and max numbers.
Any suggestions?
It would be better if you created a list with the numbers in the range and sort them randomly, then keep poping until you guess otherwise there is a small possibility that a number might be asked a second time.
However here is what you want to do:
askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))
You save it as a number and not as a string.
As you suggested, randint requires integer arguments, not strings. Since raw_input already returns a string, there's no need to convert it using str(); instead, you can convert it to an integer using int(). Note, however, that if the user enters something which is not an integer, like "hello", then this will throw an exception and your program will quit. If this happens, you may want to prompt the user again. Here's a function which calls raw_input repeatedly until the user enters an integer, and then returns that integer:
def int_raw_input(prompt):
while True:
try:
# if the call to int() raises an
# exception, this won't return here
return int(raw_input(prompt))
except ValueError:
# simply ignore the error and retry
# the loop body (i.e. prompt again)
pass
You can then substitute this for your calls to raw_input.
The range numbers were stored as strings. Try this:
askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'