i am very new to coding and stumbled upon my first problem I don't know how to solve:
weight_in_pounds=(input('How much pounds do you weigh? '))
weight_in_kilograms=weight_in_pounds*int(0.45)
print('You weigh '+ weight_in_kilograms +' kg.')
This is what I typed in and this is the result if I run it:
How much pounds do you weigh? 213
You weigh kg.
I have no idea why it doesn't show the answer. For this example I typed in 213 but instead of the result it just shows a space. What did I do wrong?
You're converting 0.45 to an integer. 0.45 as an integer is 0. weight_in_pounds*0 = 0.
You're inputting weight_in_pounds, which makes it a string. Python is a bit weird with types, so a string * 0 is just an empty string.
You should first remove the conversion to an integer on the 2nd line and add a conversion to a float (decimal) to the first. I.E: weight_in_pounds=float(input('How much pounds do you weigh? '))
With very minimal changes you can get it to work:
weight_pound = int(input('How much do you weigh in pounds? '))
weight_kg = weight_pound*0.45
print('You weigh {0} kg.'.format(weight_kg))
The problem is as Brian mentioned. It's a matter of types.
Also you can only concatenate strings and so you'll have to use such formatting to get it to display.
* Repetition - Creates new strings, concatenating multiple copies of the same string
Explaination of operations on strings
You are repeating the same string zero times.
Related
What is the best way to display a specific decimal place in a string. So 23.54 and print only 4. Right now I'm doing this but it dont seem very effective.
money=input("how much money")
totalmoney=(float(money))
totalmoney1=(float("{:.1f}".format(totalmoney)))
totalmoney2=(float("{:.2f}".format(totalmoney)))
totalmoney3 =(round(totalmoney2 - totalmoney1,2))
totalmoney4=(abs(totalmoney3))
print(totalmoney4*100, "cents")
You can just split the String at the decimal and then access whatever decimal place you want.
For example, -1 can be used to access the last Decimal place.
money = input('How much Money: ')
cents = money.split('.')[-1] if '.' in money else 0
print(cents[-1])
(Note: This code sample will not work as expected if there is no decimal place given.)
I think this is what you want...
print(input('How much money? ').split('.')[-1]['your-index-goes-here'])
# this code will still work if there's no decimal point
For eg.
print(str(23.54).split('.')[-1][2]) # returns '4'
Tell me if there's any errors...
if I'd understood your question correctly, you want the second digit after floating point. I guess you could use something like
str(round(totalmoney,2))[-1]
please let me know if it helped.
you multiply a string by 10 and print it, you'll see 10 strings.
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
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.
Having some trouble grasping why this "quick math" formula I was taught in high school does not seem to work correctly.
The premise is to take your hourly salary, double it and add three Zeros, the result will roughly equate to your yearly salary if you work full time 50 weeks out of the year.
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = raw_input("How much money do you earn per hour?")
# Math Work
mult = money * 2
result = mult + str(000)
# Answer
print "you make roughly $%r per year, Working full-time for 50 weeks out of the year" % result
Result:
my result looks something like this: "you make roughly $10100 per year, working full-time for 50 weeks out of the year"
I must be making a mistake in my expression...Simply put, I just do not know
You got all the types wrong.
raw_input acquires a string, so money is acquired as such. Thus, when you do mult=money*2 you are not doubling a number, but a string; writing money*2 thus has the effect of creating a string that is the concatenation of two copies of the string you provided. If you enter 10, mult will be '1010'.
Also, in str(000) 000 is an integer, so it's actually a plain 0; str(000) thus results in '0', which is concatenated to your doubled-string. 1010 concatenated with '0' => 10100.
What you actually want is
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
mult = money * 2
result = str(mult) + "000"
By the way, adding zeroes and the like is fine for humans, but since we are dealing with a computer you can just multiply by 2000:
result = 2000*int(raw_input("How much money do you earn per hour?"))
You're trying to do math with a string. Convert it into an integer first:
money = int(raw_input("How much money do you earn per hour?"))
and multiply instead of trying to add a string to the end
result = money * 2000
Though if you really wanted to, you could convert the integer back to a string to add 3 zeros to the end:
mult = money * 2
strmult = str(mult)
result = strmult + '000'
The raw_input() function returns a string.
When you multiply money by a number, instead of multiplying the integer value, you are multiplying the string value. This results in the variable's new value being a multiple of the string, or the string repeated multiple times. I would suggest using the money=int(money) function on money to turn it into an integer, or better yet money=float(money) to get a floating-point number.
try this
money=int(input('how much you make an hour'))
final_yearly=money*2000
print(final_yearly)
You do realize the following would give you the desired answer, right?
#Math Work
mult = money * 2000
First, money is a string, when you read user input. So when the user inputs 10, you get '10'.
So when you do money*2, you don't get the expected 20. Rather, you get '10'*2, which is '10' concatenated twice, i/e/ '1010'.
Next, 000 is an int that evaluates to 0, the str of which is '0'. What you wanted to add is '000'
I would go about your task this way:
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
mult = money * 2
result = str(mult) + "000"
Alternatively, you could do this as well:
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
result = money*2000 # because adding three 0s is the same as multiplying by 1000
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = raw_input("How much money do you earn per hour?")
# Math Work
result = str(int(money)*2) + '000'
# Answer
print "you make roughly $%r per year, Working full-time for 50 weeks out of the year" % result
I want to put a bunch of floating point numbers into a fixed-width table. That is, I want a maximum of 12 characters used. I want a minimum of 10 decimals used (if available); however, if 10 decimals makes it take up more than 12 characters, then round. My original thought was to try something like this
# I only want 12 characters used total
num1 = 0.04154721841
num2 = 10.04154721841
# not what I want
print "{:<12.11g}".format((num1))
# what I want
print "{:<12.10f}".format((num1))
# not what I want
print "{:<12.10f}".format((num2))
# what I want
print "{:<12.11g}".format((num2))
There has to be a way to achieve this without writing a function to check every number and give formatting based on the above conditions. What am I missing?
I'm not sure this is what you are looking for, since it's not accomplished entirely with the format string, however, you could just use string slicing to lop-off the trailing chars when things get too long:
num1 = 0.04154721841
num2 = 10.04154721841
num3 = 1002.04154721841
print "{0:<12.11g}".format(num1)[:12]
print "{0:<12.11g}".format(num2)[:12]
print "{0:<12.11g}".format(num3)[:12]
outputs:
0.0415472184
10.041547218
1002.0415472
Beyond that, I'd say you should just write a function, though I'm not an expert on the str.format stuff, so I may be missing something.