I can't figure out how you find a percentage of a variable in Python. This is the example of the code:
money =546.97
week=0
for i in range(10):
money=money+16
money=money+(5% money)
print('you have',money,'dollars')
week=week+4
print(week)
i = i +1
It always just adds 21 because it sees 5% and gives the equation (5% money) the value of 5.
While the % symbol means "percent of" to us, it means an entirely different thing to Python.
In Python, % is the modulo operator. Takes the thing on the left, divides it by the thing on the right, and returns the remainder of the division.
>>> 9 % 4
1
>>> 9 % 3
0
So when you do 5% money, Python reads it as "divide 5 by money and return the remainder". That's not what you want at all!
To answer the question, we need to look at what a percentage is. Percent comes from Latin per cent, meaning "per one hundred things". So "five percent" literally means "take five out of every hundred things." Okay, great! So what?
So to find a percentage of a number, you must multiply that number by its decimal percentage value. 5% is the same thing as 0.05, because 0.05 represents "five one-hundredths" or "five things for every hundred things".
Let's rewrite your code a little bit (and I'll clean up the formatting somewhat).
money = 546.97
for i in range(10):
week = i * 4
money += 16
money += (0.05 * money)
print("On week {week} you have {money:.2f} dollars.".format(week=week, money=money))
I made a few adjustments:
Instead of manually incrementing both i and week, let the loop take care of that; that's what it's for, after all!
Replaced (5% money) with (0.05 * money), which is how Python will understand what you want
Replaced your print statements with a single statement
Used the advanced formatting {__:.2f} to produce a number that cuts off to just two decimal places (which is usual for money, but you can erase the :.2f if you want the full floating-point value)
See 6.1.3 — Format String Syntax for more information about how these arguments work
Replaced statements like money = money + x with money += x because it's more concise and easier to read to advanced programmers (in my opinion)
Adjusted whitespace around operators for readability
The % symbol in python is the modulo operator in python.
It doesn't compute a percent, rather x % y determines the remainder after dividing x by y.
If you want the percentage of a variable, you just have to multiply it by the decimal value of the percent:
money * .05
# 5 % of money
Related
I'm making a simple program where it calculates your average salary per year by just asking a couple questions. So when it calculates it I want it so it has commas and gets rid of hanging zeros.
calculation = (hourly_rate * hours) * 52
format = "{:,}".format(calculation)
format_2 = "{:2f}".format(float(calculation))
#Formatting big numbers to include commas
print("{0}, your average salary for the {1} job, is ${2} per year."
.format(name, occupation, format_2))
The math is 13.65 * 32 * 52 = 22,713.6
But my output is: $22713.600000
What I want: $22,713.06
I believe you're missing a period. I've also simplified things a little:
calculation = (float(input(f"How many hours do you work in a typical week? ")) * float(input(f"Your hourly rate is: "))) * 52
print("Your average salary is ${:,.2f}".format(calculation))
Your second variable format is a python special word, try to call it format_1, and this
should help you
You can use round function to remove zeros
round(decimal,1) # 1 is number of digits you want to round off
And check this link for the commas - Commas
height = float(input("What is your height in meters?"))
weight = float(input("What is your weight in kg?"))
sum = weight/height/height
print('The sum is {0} divided by {1} divided by {1} equals {2}'.format(weight,height,sum))
Life will be easier for you, as a programmer, if you use google. And I mean no offence. In this case, just query for python round.
In this particular case, if you want to round a float called BMD to two decimal places then you would use the following expression,
round(BMD,2)
You might also be interested in how to use formatting to achieve a similar result. First I deliberately set BMD to a value that has only two decimal places. I can print it as-is but I have no control. In the second case, I set BMD to a value for quite a few decimal places but this time I limit the number of output decimal places.
In my opinion, it's safer to use round and then use the first formatting option because the second option could stumble with a value such as 345.22 (which occupies more than four columns overall).
>>> BMD = 5.21
>>> print ('BMD is {}'.format(BMD))
BMD is 5.21
>>> BMD = 5.213333333333333
>>> print ('BMD is {:4.2f}'.format(BMD))
BMD is 5.21
i'm relatively new to Phyton programming so excuse me if this question seems dumb but i just cant find an Answer for it.
How do i convert a number like lets say 1337 to 13,37€
All I have for now is this Code Sample:
number = 1337
def price():
Euro = 0
if number >= 100
Euro = Euro + 1
But obviously i need to put this in some kind of for-loop, kinda like this:
number = 1337
def price():
Euro = 0
for 100 in number:
Euro = Euro + 1
But this doesn't seem to work for me.
EDIT:
Also, how do i convert that number correctly if i just divide by 100 i get 13.37 but what i want is 13,37€.
Because Python does not support any currency symbols in numbers, you need to convert a number to a string and append the currency ("€") character to it: str(13.37) + "€":
def convertToCent(number):
return '{:,.2f}€'.format(number/100)
As #ozgur and #chepner pointed out the so called "true division" of two integers is only possible in Python 3:
x / y returns a reasonable approximation of the mathematical result of the division ("true division")
Python 2 only returns the actual floating-point quotient when one of the operands are floats.
The future division statement, spelled "from __future__ import division", will change the / operator to mean true division throughout the module.
For more information see PEP 238.
This shouldn't be hard to guess:
number = 1337
def price(number):
return (euro / 100.0)
print prince(number)
Going through a self-learn book they gave you some code to find how many times a specific digit is in an integer or not. How did they automatically know to use modulo 10? Is this something you as a programmer learn a trick for in your CompSci classes?
def num_zero_and_five_digits(n):
count = 0
while n:
digit = n % 10 # This divides w/10 for remainder. How did they know to use 10?
if digit == 0 or digit == 5: #These can be changed to whatever digits you want.
count = count + 1
n = n / 10
return count
I understand the code, but don't own it. What I mean is that if I was asked to 'write code' that would find how many times a certain digit is in an integer, I would personally
do something like this:
integer = str(22342445)
looker = list(integer)
counter = 0
find = raw_input("What number are you looking for")
for num in looker:
if find == num:
print "We found it!"
counter += 1
print "There are %d, %s's in %s" % (counter, find,integer )
Now, my main questions are:
What if someone wants to look for the integer "10" or higher? How
can I account for that in the first solution?
What steps would you personally take to come up with a solution like the first? How would you just "know" that you needed to do modulo 10?
The exercise itself is improperly defined. Rather than looking for a specific number it should instead ask about looking for a specific numeral. This restricts it to, since we use decimal (base-10) numbers (by which I mean that we use the base-10 representation of numbers), one of 10 possibilities. And since we use base-10 numbers, we need to divide by and take the modulus of 10 to separate the number into its digits so that we can compare the numerals. If we were talking about a hexadecimal number instead then we would use 16 to separate the digits, for octal we would use 8, etc.
Ok, I may have totally butchered the phrasing of this question since I can't quite word it but here's what I'm trying to do:
I have a CPU percentage displayed as characters in a string which show up on a display. If the cpu were at 52% I'd want the string to be CPU:[#####] 64% CPU:[######] but 77% CPU:[#######/] etc.
The only method I can thing off is having 20 if statements each with their own version of the string which shows dependant on the int percentage's value. I feel this would be a horrible way of doing it and wanted to know if there is a better way I can do this?
Assuming you want the number of hashes to be the “tens digit” of the CPU percentage, this simple function will do it:
def cpu_usage_str(cpu_percentage):
return 'CPU:[%s]' % ('#' * cpu_percentage / 10)
print cpu_usage_str(52)
print cpu_usage_str(64)
print cpu_usage_str(72)
(This assumes Python 2, with floor division. You’d need to tweak it slightly for Python 3.) We use the * operator to repeat the '#' string the appropriate number of times.
output:
CPU:[#####]
CPU:[######]
CPU:[#######]
Alternatively, if you’d like to round to the nearest ten (so 36% becomes CPU:[####], say), then this will do the trick:
def alt_cpu_usage_str(cpu_percentage):
return 'CPU:[%s]' % ('#' * int(round(cpu_percentage / 10.0)))
First we divide by 10.0 to get a float between 0.0 and 10.0. Then round takes us to the nearest whole number. This is represented by a float, so we convert it to an int and then repeat the string as before.
If we want a backslash to indicate whether we're under/over 5, then we need to consider cpu_percentage % 10 (the % is the modulo operator). Here's a function which does it:
def with_slashes_cpu_usage_str(cpu_percentage):
hashes_str = '#' * int(round(cpu_percentage / 10))
slash_str = '/' * (cpu_percentage % 10 >= 5)
return 'CPU:[{hash}{slash}]'.format(hash=hashes_str, slash=slash_str)
We construct the hash and slash strings separately. The bool cpu_percentage % 10 >= 5 is coerced to 0 or 1, which gives us the slash, or not, depending on whether or not we're in the upper half of that 10.
If you want [ ]5% not to print that trailing slash, then change to a strict inequality.
You can repeat a string using *, e.g. '#'*5 gives '#####'
print "CPU:[%s]"%('#'*(percentage/10))