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.
Related
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))
I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()
I'm trying to write a script that when called prompts a user for a string and it displays the string forward, backward, tests if 2 strings are the same, and tests if a string is a palindrome. I want to test the individual functions for correctness before I input a menu, however the output when calling palindrome() function seems irregular. Any help on why the two statements in the palindrome() function prints this way would be appreciated.
string = raw_input('Enter a string\n>>>')
def forward():
for i in string:
print i,
return str(i)
def backwards():
back = len(string) - 1
while back > 0:
print string[back],
back -= 1
return str(string[back])
def match():
next_string = raw_input('Enter another string')
if string.upper() == next_string.upper():
print 'the strings ', string, ' and ', next_string, ' match.'
else:
print 'the strings ', string, ' and ', next_string, ' do not match.'
def palindrome():
print backwards() # When I don't print this call it only displays the last value in the string
y = forward() # When I do print this call it displays the last value in the string twice
# This is the only way where these calls are opposite
palindrome()
I'm pretty new to python, and I wonder how I can print objects of my class fracture. The str funcion is set properly, I guess
def __str__(self):
if self._denominator == 1:
return str(self._numerator)
else:
return str(self._numerator)+'/'+str(self._denominator)
because of
>>>print ('%s + %s = %s' % (f1,f2,f1+f2))
1/3 + -1/4 = 1/12
Now I'd like to print it properly as a sorted array, and I hoped to get something like
>>>print(', '.join(("Sam", "Peter", "James", "Julian", "Ann")))
Sam, Peter, James, Julian, Ann
But this didn't work for my fracture or even for numbers (like print(' < '.join((1,2,3))))
All I got was:
for i in range(len(fractures)):
if i+1 == len(fractures):
print (fractures[i])
else:
print (fractures[i], end=' < ')
Is this really the best solution? That's quite messing up the code, compared on how easy this works with strings...
If you want to print "1 < 2 < 3" all you need to do is change the type from an int to a string as such:
print(' < '.join(str(n) for n in (1,2,3)))
You have to convert the ints to strings first:
numbers = (1, 2, 3)
print(' < '.join(str(x) for x in numbers))
You can convert your array using map:
print(' < '.join(map(str,(1,2,3))))
You can convert integers to string.
print(' < '.join((str(1),str(2),str(3))))
I am trying to create a simple program that reads a string of 4 digits, makes sure it is indeed 4 digits, makes sure there are no non-digits, then separates the first two digits from the last two and adds them together. I can make it all work but I still got this error:
ValueError: invalid literal for int() with base 10:
This only happens when I try a string such as '456f'.
What can I change to fix this?
Code:
s = input('please type a 4-digit integer \n')
valid = True
for c in s:
if len(s)!= 4:
valid = False
if not c.isdigit():
print (c, 'is not a valid input')
number = int(s)
firstOne = number // 100
secondOne = number % 100
sum = firstOne + secondOne
x = '/'
if valid == True:
print('your integer is ' + str(number), x, 'first two digits are ' + str(firstOne), x, 'second two digits are ' + str(secondOne), x, 'sum of two new numbers is ' + str(sum))
else:
print(len(s), 'is an invalid amount of digits')
You are checking whether all the characters are digits, but this check has no consequences -- you just carry on even when you found invalid characters. This makes the code fail with the quoted error message.
I'd suggest to use a dedicated function to read the integer which repeats the query until it got a valid input:
def input_int_digits(prompt, digits=4):
while True:
s = input(prompt).strip()
if len(s) == digits and s.isdigit():
return int(s)
print("Invalid input -- {}-digit integer expected.".format(digits))
Note that I used str.strip() to remove leading or trailing whitepsace and that str.isdigit() checks whether all characters of the string are digits -- you don't need to loop over the string.
Let's focus on this code:
for c in s:
if len(s)!= 4:
valid = False
if not c.isdigit():
print (c, 'is not a valid input')
number = int(s)
The first thing to say is that the len() check should be moved outside the character loop.
if len(s)!= 4:
valid = False
for c in s:
...
The next comment to make is that whilst you are detecting non-digits, you continue executing code as if nothing is wrong. You presumably intend to set valid to False.
if not c.isdigit():
print (c, 'is not a valid input')
valid = False
Now, the main part of the problem. You need to skip the conversion to int when invalid input is detected.
if valid:
number = int(s)
...
If you want to continue with such an approach your code would look like this:
valid = True
s = input('please type a 4-digit integer \n')
if len(s)!= 4:
valid = False
print(len(s), 'is an invalid amount of digits')
if valid:
for c in s:
if not c.isdigit():
valid = False
print (c, 'is not a valid input')
if valid:
number = int(s)
firstOne = number // 100
secondOne = number % 100
sum = firstOne + secondOne
x = '/'
print('your integer is ' + str(number), x, 'first two digits are ' + str(firstOne), x, 'second two digits are ' + str(secondOne), x, 'sum of two new numbers is ' + str(sum))
Having said all of that, I'd probably reorganise the code quite a bit to deal with the errors as soon as they are detected. Code is much easier to understand if you can organise your error handling that way.
s = input('please type a 4-digit integer \n')
if len(s)!= 4:
sys.exit(str(len(s)) + ' is an invalid amount of digits')
for c in s:
if not c.isdigit():
sys.exit(c + ' is not a valid input')
number = int(s)
firstOne = number // 100
secondOne = number % 100
sum = firstOne + secondOne
x = '/'
print('your integer is ' + str(number), x, 'first two digits are ' + str(firstOne), x, 'second two digits are ' + str(secondOne), x, 'sum of two new numbers is ' + str(sum))
Now, that's a start in the right direction, but you can continue in this vein making the code better and better. Sven's answer gives you an excellent illustration of where such a process would ultimately lead.
What about
...
valid = len(s) == 4 and all(c.isdigit() for c in s)
if not valid:
print (c, 'is not a valid input')
...
or even better (thanks, Sven!)
...
valid = len(s) == 4 and s.isdigit()
...
In the for that checks for isdigit , you print an error message if the string contains non-digits but still call for int() on all s
you need to exit the program after "is not a valid input" message
you can change the print to
sys.exit("is not a valid input")