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)
Related
Like if I have a 8.225 I want 8.22 not 8.23. DO I have to use it as a string first then convert to float? Or is there a simpler way?
Could not print the decimal without rounding off.
yes . you can use a string for converting.
Like this : num = '8.225' num = float(num) print(type(num)) print('Float Value =', num)
I think this code can solve your problem.
You may take reference from below python function which shall convert a float to 2 decimal places without rounding off:
def round2(x):
return float(str(x)[:str(x).index('.')+3])
Alternatively, You can also convert to int after multiplying by 100 then divide again by 100 :
def round_to_2(x):
return int(x * 100) / 100
Usually there wouldn't be any performance difference b/w two unless same operations is repeated millions of times in a loop.
So, I have to create a python script that given 2 fractions and an operand will print the result of the operation. This was intended to be solved by firstly asking for one fraction and saving it into a variable, then ask for another fraction and lastly ask for the operand. But out of curiosity I've tried to give this problem a different point of view.
My idea was to ask for the full operation and save the input string into a variable, then with the function exec() I could get the decimal result of the given operation, finally to deal with decimals my idea was to multiply by 10 to the power of the number of decimal digits and then dividing by 10 to that same power, this way I could have a fraction as a result. So I went on to code and managed to program this out, my only issue is that the number of decimal digits is limited so normally the result that my script returns is a very big fraction that is very close to what the real fraction is. So I was wondering if there is any workaround for this. Here is my code and an example for further explanation:
op = input('Enter operation: ')
try:
exec('a = ' + op)
except:
print('Invalid operation')
def euclides(a, b):
while a != 0 and b != 0:
if a < b: b = b%a
else: a = a%b
if a == 0: return b
elif b == 0: return a
print(f'{int(a*10**len(str(a).split(".")[1])/euclides(a*10**len(str(a).split(".")[1]),10**len(str(a).split(".")[1])))}/{int(10**len(str(a).split(".")[1])/euclides(a*10**len(str(a).split(".")[1]),10**len(str(a).split(".")[1])))}')
EXAMPLE:
op input => 4/3+5/7
Result of script => 5119047619047619/2500000000000000 = 2.04761904761
Result I'm looking for => 43/21 = 2.047619 period
Thank you for your help in advance
What are your constraints as to what standard or add-on modules you can use? Without taking into account constraints you haven't specified, there are much better ways to go about what you're doing. Your problem seems to be summed up by "the result that my script returns is a very big fraction" and your question seems to be "I was wondering if there is any workaround for this?". There are a number of "work arounds". But it's pretty hard to guess what the best solution is for you as you don't tell us what tools you can and can't use to accomplish your task.
As an example, here's an elegant solution if you can use regular expressions and the fractions module, and if you can assume that the input will always be in the very strict format of <int>/<int>+<int>/<int>:
import re
import fractions
op = input('Enter operation: ')
m = re.match(r"(\d+)/(\d+)\+(\d+)/(\d+)", op)
if not m:
raise('Invalid operation')
gps = list(map(int, m.groups()))
f = fractions.Fraction(gps[0], gps[1]) + fractions.Fraction(gps[2], gps[3])
print(f)
print (float(f))
print(round(float(f), 6))
Result:
43/21
2.0476190476190474
2.047619
This answers your current question. I don't, however, know if this violates the terms of your assignment.
Could just turn all natural numbers into Fractions and evaluate:
>>> op = '4/3+5/7'
>>> import re, fractions
>>> print(eval(re.sub(r'(\d+)', r'fractions.Fraction(\1)', op)))
43/21
Works for other cases as well (unlike the accepted answer's solution, which only does the sum of exactly two fractions that must be positive and must not have spaces), for example:
>>> op = '-1/2 + 3/4 - 5/6'
>>> print(eval(re.sub(r'(\d+)', r'fractions.Fraction(\1)', op)))
-7/12
Checking:
>>> -7/12, -1/2 + 3/4 - 5/6
(-0.5833333333333334, -0.5833333333333334)
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
I failed an exam because of one question. The task is:
"Design a program that converts any number from any system to decimal.
We confine to the systems in the range from 2 to 22."
So there I am. I know the binary[2], octal[8], decimal[10] and hexadecimal[16] systems. There's 1 point for each conversion system, so it has to be a converter:
2->10
3->10
...
22->10
I have no idea how is that possible. I asked my professor after the exam how to do it and he said: "Just x to the power of y, multiply, and there it is. There's the same rule for all of them."
I might be mistaken in what he said because I was in the post-exam state of consciousness. Do you guys have any idea how to solve it?
I see that there were a few questions like that on stackoverflow already, but none of them does not solve the problem the way my professor said. Also, we started learning Python ~4 months ago and we haven't learned some of the options implemented in the replies.
"""IN
str/int, any base[2-22]
OUT
decimal int or float"""
The int() built-in function supports conversion of any number to any base. It requires a passed correct number within the base or else throws a ValueError.
Syntax: int('string', base) converts to decimal
Example:
Conversion of a number 3334 to base 5
>>> int('3334',5)
469
Conversion of number 3334 to base 9
>>>int('3334', 9)
2461
Conversion of the above to hex-decimal number
>>>hex(int('3334', 9))
'0x99d'
I just coded the answer but was too slow. This code follows exactly daTokenizers solution
def converter(number, base):
#split number in figures
figures = [int(i,base) for i in str(number)]
#invert oder of figures (lowest count first)
figures = figures[::-1]
result = 0
#loop over all figures
for i in range(len(figures)):
#add the contirbution of the i-th figure
result += figures[i]*base**i
return result
converter(10,22)
>>> 22
converter(52,16)
>>> 82
the basic stages are so:
understand what base you are in (to my understading this is given as var to you)
for each of the chars in the input number you multiply it by the base to the power of the location. so "654",base 17 -> "6*17^2 + 5*17^1 + 4*17^0"
the sum is your answer.
If n is the number, to convert from base 'other' to decimal, try this:
>>> other2dec = lambda n, other: sum([(int(v) * other**i) for i, v in enumerate(list(str(n))[::-1])])
>>> other2dec(71,8)
57
>>> other2dec(1011,2)
11
My program is meant to allow the user to create a character that has two attributes with values. The attributes are called strength and skill. The attribute values are created by a random number between 1 and 12 being divided by a number between 1 and 4. The outcome is added to 10. The thing is decimals can occur, so i want my program to round down decimals. I want it to round down even if the number is for example 5.6. Then is would become 5. I have not a clue how to implement this to my current code. I would also like the information to be saved to a text file but this is less important. I'm a noob at python and i would appreciate the help, thanks.
My current code
from random import randint
Strenght = 10
Skill = 10
while True:
character = str(input("Enter name of your character\n"))
if character:
print("Your characters name is",character)
print("They have",Strenght + randint(1,12)/randint(1,4),"Strenght")
print("And",Skill + randint(1,12)/randint(1,4),"Skill")
if input("Would you like to make another character? \n").lower() not in ("yes","y"):
break
You want to use the math.floor() command. It always rounds down.
>>> import math
>>> print (math.floor(5.6))
5.0
You can also round up with math.ceil() or round to the nearest integer with round().
Since both of the numbers you're dividing are integers, you can use the integer divide // to produce an integer output with the remainder dropped.
>>> print 17 // 3
5
>>> from __future__ import division
>>> print 17 / 3
5.66666666667