Add period to python statement without a space - python

I am only three weeks into my Intro to Programming course, so bear with me!
I am writing a code as follows:
number1 = input('Enter the first number: ')
number1 = int(number1)
number2 = input('Enter the second number: ')
number2 = int(number2)
number3 = input('Enter the third number: ')
number3 = int(number3)
ratio12 = int(number1 / number2)
ratio13 = int(number1 / number3)
ratio23 = int(number2 / number3)
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.')
print('The ratio of', + number1, '+', + number3,'is', + ratio13, '.')
print('The ratio of', + number2, '+', + number3,'is', + ratio23, '.')
The code is functional (finally), but I can't seem to get rid of the space before the period on the print statements. Is there a way that I can do that?

The reason why this happens is because you are using commas in your print statements. In python there are a few ways to give the print statement multiple variables, you seem to be mixing two of them together. The ways are as follows.
Concatenate the string.
print('The ratio of ' + str(number1) + ' + ' + str(number2) + ' is ' + str(ration12) + '.')
This way is probably the most basic way. It will join the strings without adding any characters in between them (e.g. no spaces in between unless you add them explicitly.) Also note, that string concatenation won't automatically cast the integers to a string for you.
Pass print multiple arguments.
print('The ratio of', number1, '+', number2, 'is', ration12, '.')
This will automatically add spaces between each argument and is what is happening in your case. The separator (which defaults to a space) can be changed by passing a keyword argument to the print function. For example, print('i = ', i, sep='')
Use string formatting.
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
This way is the most readable and often the best way. It will replace the '{}' sections in you 'template' string with the arguments based into the format function. It does this in order, however you can add an index like this '{0}' to explicitly use an argument by index.

Some string formating makes your live easier:
number1 = 1
number2 = 2
ratio12 = number1 / number2
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
Output:
The ratio of 1 + 2 is 0.5.

You can control the "separator" using the sep argument to print:
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.', sep='')
Note that this will change the spacing between the other items as well.
Also -- You don't need the extra + operators in there. Here's a version without the spaces and with explicit spaces added where I think you want them:
print('The ratio of ', number1, ' + ', number2, ' is ', ratio12, '.', sep='')

You're confused about the concatenation function and print fields. If you're going to concatenate all those strings, just use concatenation. The comma includes the default separator.
print('The ratio of', number1, '+', number2,'is', str(ratio12) + '.')

Try to write to it this way:
print('The ratio of %d + %d is %d.' %(number1, number2, ratio12))
print('The ratio of %d + %d is %d.' %(number1, number3, ratio13))
print('The ratio of %d + %d is %d.' %(number2, number3, ratio23))

That's the way print works when you give it multiple comma separated arguments. The logic behind that is that when you quickly want to print a bunch of variables, it's a pain to manually add widespace.
Well, one thing to try: Get rid of all the , in the print statement. You can just chain strings using the + sign.
So,
print('The ratio of ' + str(number1) + ' ' + str(number2) + ' is ' + str(ratio12) + '.')
If you need even greater control over formatting, you'd want to look into the format function.
print("The ratio of {} + {} is {}.".format(number1, number2, ratio12))

Related

How to add a full stop right behind a float() variable in Python?

I'm trying to write a program for a computer programming course to calculate the area of a triangle, and the expected output is "The area is [insert number here]."
Here's what I have, and I'm frankly stumped on the full stop:
b = input('Base: ')
h = input('Height: ')
a = 0.5 * float(b) * float(h)
print('The area is', a, '.')
It outputs this:
Base: 1
Height: 1
The area is 0.5 .
This is marked as incorrect because of the extra space, how do I get rid of it?
The print default separator argument is ' ' (a space), so try changing that to '' (empty string):
print('The area is ', a, '.', sep='')
Or use + and make it a string:
print('The area is ', str(a) + '.')
Best with string formatting:
f string literal:
print(f'The area is {a}.')
Or %s:
print('The area is %s.' % a)
Or str.format:
print('The area is {}.'.format(a))

How do I get parentheses around my variable? [duplicate]

This question already has answers here:
Print Combining Strings and Numbers
(6 answers)
Closed 4 years ago.
I'm doing one of my first assignments and I can't find out how to put parentheses around a variable when I go to print it.
I've tried
(xs)
{xs}
[xs}
But none get parentheses around it
(print)("Hello user! Welcome to the program!")
name = input("What is your name?")
(print)("Hello", name)
x = input("What is your favorite number?")
y = int(x) // 2
xs = str(x)
ys = str(y)
z = ("Did you know that half of your favorite number" + ' ' + xs + ' ' + 'is' + ' ' + ys + '?')
print(z)
For the 2nd to last line of code I want it to say Did you know that half of your number (5) is 2?
5 is just an example number but I want it in parentheses!
Do it like so:
z = ("Did you know that half of your favorite number" + ' (' + xs + ') ' + 'is' + ' ' + ys + '?')
you just need to add the pharentesis in the right place, something like this:
z = ("Did you know that half of your favorite number" + ' (' + xs + ') ' + 'is' + ' ' + ys + '?')
I am not exactly sure if that is what you need but you just have to concat "(" and ")" around your variable.
>>> y = "number"
>>> print ( "(" + y + ")" )
(number)

Python - simple interest

I am trying to write a code for myself that will give me an answer for simple interest, I will use same concept and later make compound interest. I am having trouble with my rate. when I do it as a percentage like
r = int(input("rate %: ")
and I type 5.4 it does not work so I tried it in a decimal form like this
r = int(input("Rate 0."))
i get the same answer at end if i do 0.045 and 0.45
so how do i fix this problem
here is my entire code
while True:
while True:
print('Working out for SIMPLE INTEREST')
p = int(input("Principl:"))
r = int(input("Rate 0."))
t = int(input("Time yrs:"))
i = p*r
i = i*t
a = p + i
print("Interest = " + str(i))
print("Accumalated = " + str(a))
print(str(p) + ' x ' + str(r) + ' x ' + str(t) + ' = ' + str(i) + ' | ' + str(p) + ' + ' + str(i) + ' = ' + str(a))
int converts the input string to an integer, which is a whole number like 4 or 5. For 5.4, you want a floating point number, which you can make using the float function:
r = float(input("rate %: "))
(For professional usage, you might even consider the arbitrary-precision decimal package, but it's probably overkill in your situation.)
It is because int does not support decimal numbers
So change int(input('something...')) to input('sonething...')

Python unexpected EOF while parsing : syntax error

I am trying to do a simple toto history with a dictionary and function however I have this funny syntax error that keeps appearing that states "unexpected EOF while parsing" on the python shell when I try to runs it. I re-looked over and over however I cannot find the error. I used input for input of integers therefore I do not think that the problem might lie with the input or raw_input. Please help me ! Below are my codes and the error on the python shell.
options()
choice = input ("Enter your choice: ")
print
while choice != -1:
if choice == 1:
print("Choice 1")
for key in toto_book:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
elif choice == 2:
print("Choice 2")
draw = raw_input("Enter draw date(dd/mm/yy): ")
if draw in toto_book:
print (draw + "\t" + "Day: " + toto_book[draw][0] + "\t" + "Winning Numbers: " + str(toto_book[draw][1]) + 'Additional Number: ' + toto_book[draw][2])
else:
print draw + ' cannot be found.'
There is a syntax error at the elif choice == 2: line.
Updated
As pointed out by #cricket_007, this answer is based on the false assumption that Python 3 is being used. Actually, Python 2 is being used and the only serious problem is that the call to str is missing a closing parenthesis.
You are using Python 3 in which print is a function, not a statement (as it is in Python 2).
This is the line causing the problem:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
Add parentheses to make print a function call, i.e. print(...):
print(key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1]) + 'Additional Number: ' + toto_book[key][2])
Also, the call to str() was missing the closing parenthesis.
There is a similar problem on line 15.
Other problems:
input() returns a string, not an integer so your if choice ==
statements will never be true. Either convert choice to an integer
with choice = int(choice) after the input(), or use a string in
the if statements, e.g. if choice == '1'.
The while loop is infinte, and unnecessary for the code shown (perhaps it is a work in progress?).

is the print statement correct?

I have to add str(iterMul(a,b)) to obtain what I want. Is it the proper way to do it?
def iterMul(a,b):
result = 0
while b > 0:
result += a
b -=1
return result
a=int(raw_input('Enter an integer: '))
print('')
b=int(raw_input('Enter an integer: '))
print('')
print (str(a) + ' times '+str(b)+' is equal to '+ str(iterMul(a,b)))
Thanks in advance!
Use string formatting instead:
print '{0} times {1} is equal to {2}'.format(a, b, iterMul(a,b))
String formatting automatically transforms integers to string when interpolating the values, and is more readable than print value, ' some text ', othervalue, ' more text and ', thirdvalue.

Categories