Jump to content

Talk:Python Programming/Basic Math

Page contents not supported in other languages.
Add topic
From Wikibooks, open books for an open world
Latest comment: 13 years ago by Patrick95350 in topic What am I doing wrong?

Running the programme

[edit source]

When I run this programme:

mass_kg = int(raw_input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh %d stone." % mass_stone

The output I get is in an integer format. For example:
What is your mass in kilograms?71
You weigh 11 stone.

When I changed the programme to read

mass_kg = int(raw_input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh %s stone." % mass_stone

Then I get the long string of numbers after the decimal point:
What is your mass in kilograms?71
You weigh 11.1571428571 stone.

The rest of the suggested changes work well when I make this change. Should the programme say %s or is this some sort of quirk on the computer I am using (an apple mac running OS X)? Wobble (talk) 09:40, 29 May 2008 (UTC)Reply

"%s" treats the variable mass_stone as a string rather than a float or integer, when combined with the % operator. Because of how Python works, it is autocasted from a float. See the Python documentation for more information. --Sigma 7 (talk) 15:24, 11 February 2010 (UTC)Reply

note from another user: the program terminates too fast. i can't seem to fix it. —Preceding unsigned comment added by 2l0t0k9 (discusscontribs) 15:50, 8 February 2010

If "terminates too fast" means the window is closing before you can read the output, you're launching it wrong. Either use an interactive interpreter (such as IDLE), or run it from a command prompt. --Sigma 7 (talk) 15:24, 11 February 2010 (UTC)Reply

What am I doing wrong?

[edit source]
import math
a = int(input("What is A? "))**2
b = int(input("What is B? "))**2
c = math.sqrt(a + b)
roundnum = int(input("To how many decimals? "))
print("C is " round(c, roundnum) ".")

I've tried everyting. It's probably something blatantly obvious. --71.136.41.121 (discuss) 20:41, 5 January 2012 (UTC)Reply

I believe you forgot the commas in the print command. Correct code is:

print("C is ", round(c, roundnum), ".")

--Patrick95350 (discusscontribs) 19:52, 20 February 2012 (UTC)Reply