outputting strings and function outputs in Python - python

I am coding a simple program to add all positive integers not greater than a given integer n. My code:
print("Enter an integer:")
n=input()
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
#print("1+2+3+...+"+str(n)+"="+str(add(n)))
print(add(100))
The function works.
Why does the line in the one line comment not work, if I remove the hash tag? It should - there is a concatenation of four strings. Thank you.
EDIT: the whole output:
Enter an integer:
12
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "<string>", line 6, in add
TypeError: can only concatenate str (not "int") to str
>

input() returns a string. You are passing n=input() which is a string so it is not working as expected.
change it to n=int(input())
Also sum is a reserved keyword and it will be best to change that to a different name

input returns a string, so add(n) will look something like add("1234"). Then, range(k+1) inside the function will be range("1234" + 1), but "1234" + 1 is an error since it's not possible to add a string and a number.

The problem exists in your input, it's current data type is str, and must be converted into int.
Also, it's best if you use .format() when printing strings.
print("Enter an integer:")
n = int(input())
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
print("1 + 2 + 3 + ... + {} = {}".format(n, add(n)))

Related

print all the list elements with an even index number, error statement

for my task, which I think I have already right, but on Snakify it shows me this error statement: Traceback (most recent call last): ValueError: invalid literal for int() with base 10: '1 2 3 4 5'
On google colab this error doesn't show up, on snakify it does, but I need this error to go so I can check my solutions. Any suggestions?
Task is: a list of numbers, find and print all the list elements with an even index number.
a = []
b = []
numbers = input()
for n in numbers.split():
a.append(int(n))
if int(n) % 2 == 0:
b.append(a[int(n)])
print(b)
int() can convert only numbers and raise error if argument contain a non-digit char, for example space ' '. You can use:
nums = input().split() # split() method splited string by spaces
a = []
for i in range(len(nums)): # len() function return count of list elements
if (i % 2) == 0:
a.append(nums[i])
print(a)
Also you can get
IndexError: list index out of range
Please comment if interesting why
int(input()) will only work on a single number. If you want to enter many numbers at once, you'll have to call input() first, split it into separate numbers, and call int() on each one:
numbers = input()
for n in numbers.split():
a.append(int(n))
Or using a list comprehension:
numbers = input()
a = [int(n) for n in numbers.split()]

Strings to list and loop checking

Given a list, containing N user-provided strings, the task is to print whether each string is a palindrome or not. (PYTHON)
i have this code already. and keeps telling me errors that "Traceback (most recent call last):
File "C:\Users\jpsam\Desktop\fuckmylife.py", line 20, in <module>
palindrome_checker(q)
File "C:\Users\jpsam\Desktop\fuckmylife.py", line 4, in palindrome_checker
while y <len(inputlist()):
TypeError: 'list' object is not callable"
def palindrome_checker(q):
y = 0
while y <len(inputlist()):
if inputlist == inputlist[::-1]:
print(q, " is a panlindrome")
len(inputlist()-1)
else:
print (q, "not a palindrome")
len(inputlist()-1)
return (q)
x = 1
inputlist = []
while x == 1:
q = input("Input string: ")
inputlist.append(q)
x = int(input("Do you want to add more? [1]YES [0]NO ====>"))
palindrome_checker(q)
First, your indentation is incorrect.
Secondly, the statement len(inputlist()-1) is giving the exception because you have followed a list, inputlist, with (), which asks the interpreter to call inputlist as a function. Unfortunately I have no idea what this statement is supposed to achieve (not the other one in the if branch - your code could be refactored too).
A simpler palindrome function might read as follows:
def palindrome(s):
return s == s[::-1]
You might use it as follows:
if palindrome("able I was ere I saw elba"):
print("The phrase is palindromic")

Stranger error with the .join function

I've been trying to write a program which finds the roots of an inputted mathematical function. I've only just started, so what I show here is only the start, and there are unused variables.
Here I wrote a function which is supposed to replace the term 'x' in a function with a value you input, say, 100. Here is the code:
code = list(input("Enter mathematical function: "))
lowBound = int(input("Enter lower bound: "))
upBound = int(input("Enter upper bound: "))
def plugin(myList, value):
for i in range(len(myList)):
if myList[i] == 'x':
myList[i] = value #replaces x with the inputted value
return ''.join(myList) #supposed to turn the list of characters back into a string
print(plugin(code,upBound))
But when I run the program, I get the error:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 9, in plugin
TypeError: sequence item 0: expected str instance, int found
(I'm using an online programming platform, so the file is just called 'python')
This doesn't make any sense to me. myList should not be an int, and even if it was the right data type (str), it should be a list. Can someone explain what's going on here?
You are replacing a str type (or character) with an int type.
Try this instead:
myList[i] = str(value)
You can only join an iterable of strings
return ''.join(str(x) for x in myList)
Or, more succinctly. Remove the function
print(''.join(str(upBound if x =='x' else x) for x in code)

Can't convert 'int' object to str implicitly: Python 3+

My code is supposed to determine and display the number of binary trees after an input.
I keep getting the can't convert int object to str implicitly error and I have no idea how to fix it. It easily works in versions of Python under 3.0, so please help, as I'm still a beginner in Python and I would like to understand what I'm doing wrong.
import sys
print ("Welcome to Binary Tree Enumeration!")
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
def distinct(x):
leafnode = '.'
dp = []
newset = set()
newset.add(leafnode)
dp.append(newset)
for i in range(1,x):
newset = set()
for j in range(i):
for leftchild in dp[j]:
for rightchild in dp[i-j-1]:
newset.add(("(") + leftchild + rightchild + (")"))
dp.append(newset)
return dp[-1]
alltrees = distinct(x+1)
for tree in alltrees:
print (tree)
print ("Thank you for trying this out!")
I forgot to add...this is the error I'm getting.
Traceback (most recent call last):
File "main.py", line 29, in
alltrees = distinct(x+1)
TypeError: Can't convert 'int' object to str implicitly
As others have suggested, this comes from your call to input. In Python27:
>>> input() + 1
3 # I entered that
4
But using raw_input() (which has the same behaviour as input in Python3+):
>>> raw_input() + 1
3 # I entered that
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
And indeed, we have:
>>> x = raw_input()
3
>>> type(x)
<type 'str'>
In your code, your user-input x is a string, and the code complains on the line distinct(x+1) when you try to add a string and an int. Convert it first like this:
>>> x = int(input())
...
In order to concatenate strings and string representations of various types, you have to cast the latter to strings explicitly, e. g.
"(" + str(leftchild) + ", " + str(rightchild) + ")"
or, more readably,
"(%i, %i)" % (leftchild, rightchild)
By default when you use input its always a string input
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
So there's no need to convert it again !
and here use .format()
newset.add("{0} {1} {2} {3}".format(r"(", leftchild, rightchild, r")"))
But the above one will not maintain the datastructure !!
If you would like to preserve the datastructure, use,
newset.add(tuple(leftchild, rightchild))

number/numbers to list by using input() [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers's answer in stackoverflow but couldn't make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
In your function, you can directly convert num into a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:
In [1]: num = '1'
In [2]: num.split(',')
Out[2]: ['1']
In [3]: num = '1,2,3,4'
In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']
You can then use your function as you have it:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
number = map(int,num)
return number
x = inputnumber()
print x
However you can take it a step further if you want - map here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number and return the result of the comprehension (same would work for map as well, if you want to keep that):
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num]
x = inputnumber()
print x
If you want to handle other types of input without error, you can use a try/except block (and handle the ValueError exception), or use one of the fun methods on strings to check if the number is a digit:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num if n.isdigit()]
x = inputnumber()
print x
This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit() part).
And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):
print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:
def inputnumber():
num = raw_input()
for i, j in enumerate(num):
if j not in ', ':
try:
int(num[i])
except ValueError:
#error handling goes here
return num
def main():
x = inputnumber()
print x
I guess all it is is a long-winded version of RocketDonkey's answer.

Categories