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
Related
When I enter this code the answer ends with 2 characters behind the decimal. How do I make this only have 1 number behind it?
tempature=float(input("Enter the temp(F):"))
formant_tempature = f"{tempature:2f}"
print(round(((int(tempature)-32)*5/9)+273.15,2))
When you used round function you have specified that you want two decimal places. Just replace 2 with a number 1.
print(round(((int(tempature)-32)*5/9)+273.15,1))
You are using the string formatting operator for that ( formant_tempature = f"{tempature:2f}" )
What about formant_tempature = f"{tempature:1f}"
Like if you want it to display 5 decimals, just change it to f"{tempature:5f}"
And so on.
And for the round method, change 2 to 1.
I'm not sure why you'd do any math just to present this rounded, when you can simply use an f-string to specify outputting the temperature with a single decimal place precision.
>>> temperature = 43.8934
>>> print(f"Temperature is {temperature:.1f} degrees")
Temperature is 43.9 degrees
>>> print(f"Temperature is {temperature * 1.8 + 32:.1f} degrees farenheit")
Temperature is 111.0 degrees farenheit
This question already has answers here:
How to print float to n decimal places including trailing 0s?
(5 answers)
Closed 2 years ago.
It's my first week trying to learn how to code.
Rods is input from user so it can be whatever
miles = round(Rods * 0.003125, 20)
print("Distance in Miles = ", miles)
I need this line of code to print 20 decimals. I thought by adding comma 20 it would do so. I then tried looking re-writing it to format{miles: "20.f"}. (Don't remember exactly how the code went)
Any guidance would be appreciated.
Try this snippet:
miles = Rods * 0.003125
print("Distance in Miles = {:.20f}".format(miles))
This code does the calculation first and formats the answer such that it is displayed in 20 decimal places. For displaying only 10 decimal places change to .10f, for 2 decimal places change to .2f and so on.
When calling round() method on floats, the unnecessary leading decimal zeros are not counted, since the number is the same.
You can convert the number to string, use .split(".") on it to separate the decimal and whole number
example: "3.85".split(".") will return a list whose elements are ["3", "85"] digits = str(num).split(".")
Lets take the second element, decimals decimals = digits[1]
Then you take the length of second element that is decimals and subtract it from 20. This will be the amount of zeros to add. newDecimals = decimals + (20 - len(decimals)) * "0"
Now, use the list from before to form a new number
final = digits[0] + "." + newDecimals
Keep in mind that converting it back to a float will remove those zeros.
Try following source code :
miles = Rods * 0.003125
miles_formatted_float = "{:.20f}".format(miles)
print("Distance in Miles = "+miles_formatted_float)
How can I get a string same as input number?
>>> '{:f}'.format(1559628846)
'1559628846.000000'
expect 1559628846
>>> '{:}'.format(1559628846.0001234)
'1559628846.0001235'
expect 1559628846.0001234
>>> '{:}'.format(0.000001)
'1e-06'
expect 0.000001
My real problem is how to concat a string and any number without change the number?
>>> '{},{}'.format('Hi', 1559628846.0001234)
'Hi,1559628846.0001235'
expect 'Hi,1559628846.000123'
A floating point number is displayed on the screen in base 10, but stored on the computer as base 2. There isn't always an exact representation of the base 2 number the computer is using. docs.python.org has a great article on the nuances of that.
That explains the rounding error. As for why python doesn't remember the exact number of digits you were using, it's because storing a floating point number is more efficient than storing the string you started with. Run this test to see the difference:
>>> import sys
>>> fnum = 12345.67890
>>> snum = '12345.67890'
>>> sys.getsizeof(fnum)
16
>>> sys.getsizeof(snum)
36
>>>
In programming, you almost never care about how the number was entered, you just store the floating point representation and make your display layer show the user a pleasing representation that depends on your use case. If you really care what was originally entered, you'll have to store it as a string, not a float.
You need to define the input number as a string. For instance:
print('{},{}'.format('Hi','1559628846.0001234'))
Output: Hi,1559628846.0001234
Otherwise, it will always approximate it.
Another option would be to round it to a certain digit, which is not in the order of the accuracy:
i = round(1559628846.0001234, 5)
print('{},{}'.format('Hi',i))
Output: Hi,1559628846.00012
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.