Calculate powers of 2 from user input - python

I'm totally new to programming. Picked up a PDF and I'm trying out Exercises given. But now I'm stuck with the following task:
Write a Python program that allows the user to enter any integer
value, and displays the value of 2 raised to that power. Your program
should function as shown below
What power of two? __
Two to power of __ is __
I think it should start something like this:
x=input("What power of two? ")
but what's next? or is it right at all?

If you get an error with pow(2, x) it's probably because of typing, you should convert the string from input to a number, like int or float
>>> e = float(input('What power of two?'))
What power of two?1.2
>>> pow(2, e)
2.2973967099940698

It's pretty simple, really.
Python has this operator for Powers: **
e.g. print(2**10) will print 1024.
One more thing- you'll have to type x = int(input("*Whatever you want to enter*")), as input() returns a String.

Related

How do I print numbers from 1 to n in python in a single line without spaces?

print(*range(1, int(input())+1), sep='')
This was the code I found in a discussion on hacker rank. But I did not understand it.
Can anyone please explain this?
So, from what I can tell, this is how it works:
int(input())
This takes input from the user.
Next;
range(1,...+1)
This creates a range from 1 to our number we inputted earlier. The +1 means that it will include the max number.
And then:
print(*...,sep='')
The * sign, from what I can tell, just effectively returns each value in our range one to be printed.
The sep='' just means each value is separated by '' or nothing.
Hope this is useful to you.
[EDIT]
More on star and double star expressions in this post:
What does the star and doublestar operator mean in a function call?
Ok so we have print function. Inside we have this strange *range(1, int(input())+1) this is range function which return value from 1 to n (n is typed in input) in a form of a range object. * unpack this object to form like: 1 2 3 4 ... with spaces, so we have this sep='', keyword argument that makes separation from space to '' (no separate between).
Also you can do it like that:
n = input("Type integer value: ")
try:
[print(x+1,end="") for x in range(int(n))]
except ValueError:
exit("Typed string not number")

How to get a irrational number as a user input in python?

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

Converting Binary to Decimal in python (without built in binary function)

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.

Division issues? [duplicate]

This question already has answers here:
Using integer division in Python
(2 answers)
Closed 8 years ago.
Basically i made this program to practice python ( i am a complete noob at it), i am quite enjoying python, as my first programming langauge ever learnt or in the process of i feel very accomplished when completeing a program that works ( even if it is hello world). So anyways, i made a small program using techniques i had learnt from books and stuff from the internet and i have an issue, the program works fine, without problems but at the end there is a division where it justr goes wrong, it cannot divide anything unless it makes a whole number (eg. 100/20=5 but if i did 20/100 it would equel 0 and not 0.2), this also effects it if the number is going to be negative it just panics. i tried 15/20 to see if it was rounding but it still said 0.Any help would be fantastic ^_^
here is the code:
a=100
b=50
c=10
z=110
o=5
zoo=z+o+o
print "What is the value of zoo if:"
print "z=110"
print "o=5"
print "zoo=z+o+o"
import time
time.sleep(5)
print zoo,"of course!"
import time
time.sleep(1)
print "Wait..",a+b-(c)*3,"is the same as zoo except we just did it there using other code!"
import time
time.sleep(3)
print "We did it using 100+50-(10)*3 which then adds to zoo or 120!"
import time
time.sleep(3)
print "were gonna try something fun now!"
import time
time.sleep(2)
print "Please pick a number:"
number=int(raw_input())
print "and another:"
another=int(raw_input())
print "the two numbers you chose multiplied together makes",number*another
import time
time.sleep(2)
print "ok now were going to take your two numbers and divide them"
print "Your two numbers divided=",number/another
import time
time.sleep(1)
print "Ok im bored now, im going to go, have a nice day ^_^"
and here is the awnser with a problem:
What is the value of zoo if:
z=110
o=5
zoo=z+o+o
120 of course!
Wait.. 120 is the same as zoo except we just did it there using other code!
We did it using 100+50-(10)*3 which then adds to zoo or 120!
were gonna try something fun now!
Please pick a number:
15
and another:
20
the two numbers you chose multiplied together makes 300
ok now were going to take your two numbers and divide them
Your two numbers divided= 0
Ok im bored now, im going to go, have a nice day ^_^
oh and im on python 2.7.6
Add above this line:
print "Your two numbers divided=",number/another
this code:
number, another = number + .0, another + .0
The reason your code doesn't work is because you're using int's. When you divide with integers, they return an integer or a whole number. You need to convert the numbers to floats by adding .0 to the numbers. This will allow you to get absolute division results.
You can add
from __future__ import division
at the top of your file. Then the default division strategy will be what you expect, i.e. floating point division. Python 2.7 does integer division by default.
The / quotient of two int's, in Python 2.x, is an int.
The / quotient of one int and one float, in Python 2.x, is a float.
The / quotient of two floats, in Python 2.x, is a float.
The / quotient of two int's, in Python 3.x, is a float.
The / quotient of one int and one float, in Python 3.x, is a float.
The / quotient of two floats in Python 3.x, is a float.
The // quotient of two int's, in Python 3.x, is an int.
The // quotient of one int and one float, in Python 3.x, is a whole-number float.
The // quotient of two floats in Python 3.x, is a whole-number float.
In Python 2.x, you can "from __future__ import division" at the top of your module, to get the 3.x behavior.
So since you're using 2.x, you probably should either "from __future__ import division" at the top of your module, or convert one or both of your int's to float with float(int_var) prior to / division.
To add to all answers. In some languages (including python) division operator result depends on value types being used e.g.:
>>> 1 / 2 # integer divided by integer
0
>>> 1.0 / 2 # float divided by integer
0.5
15/20 = 0 when performing an integer division since the result is less than 1. Therefore it truncates to 0.
// is used for dividing integers and / for floats- you are using the wrong operator so you get an incorrect result:
>>> 15 / 20
0
>>> 15 // 20
0.75
You can fix this by adding from from __future__ import division to your script. This will always perform a float division when using the / operator and use // for integer division- so just do what you are doing and it will return the expected result:
>>> from __future__ import division
>>> 15 / 20
0.75
I would use the above solution, with the import; but there are other ways. Another option would be making at least one of the operands a float, e.g. float(number) / another.
>>> number = 15
>>> another = 20
>>> float(number) / another
0.75
The above works because the result of the division depends on value types being used, in Python.

Is there any way to use raw_input variables in random.randint?

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)) + '?'

Categories

Resources