Not getting the desired output in python - python

enter image description hereI want to reverse a number. If 92 is typed the result should be 29. The code is given below
def intreverse(n) :
a=str(n)
b=a[::-1]
c=int(b)
print (c)
But i am getting the result as actual output as
29/n
none/n
Why?

The course you use probably wants you to write functions with returns. As your function has no return, you get None in the end. And for the newline character \n: As you print your answer, print puts a newline character after what you print. If you delete the print statement and put a return statement instead as suggested, both problems will be solved.

It looks like you are getting newlines in your text input (possibly two?). I would fix this with
a=str(n).strip()
also, you are printing the result, I think you want to return it. Since the function does not return anything, a = intreverse('29') will assign None to a. So you want:
def intreverse(n) :
a=str(n).strip()
b=a[::-1]
c=int(b)
return c
Or just for the obligatory one-liner:
def intreverse(n):
return int(str(n).strip()[::-1])

Related

How to make a bool return true/false using the return function inside def in Python?

I was given a task to make a code which takes a word, checks if there are any vowels in it, then returns true if there are vowels inside the word, and false if no vowels are there inside the given word. This is what I wrote-
def search4vowels(word):
vowels = set('aeiou')
found = vowels.intersection(set(word))
return(bool(found))
search4vowels('test')
Here, I was expecting found to contain either none (Or 0 vowels) or the value of the vowels. Then use the return function with bool
to get true or false depending on the value of the variable found However, when I ran the code, nothing was printed. I also changed the last line under def return(bool(found)) to return bool(found) but that did not print anything either. This might be a really dumb/stupid question but I am really a beginner and actually don't know why nothing is getting printed despite the use of the return function. I checked on various websites also but did not understand why this was happening. Thanking you in advance, Have a great day ahead!
Try adding a print statement to show the output:
print('Result:', search4vowels('test'))

print() prints only every second input

I'm new to python and I've been trying to make a little function to call upon when I need to filter an input from everything except regular letters.
I've used SO for parts of the code, but I can't seem to understand why does it only print on every second try.
Here's my code:
import re
i=1
def inputFilterText():
inputRaw = input('input: ')
inputFiltered = re.sub('[^a-zA-Z]+', '', inputRaw)
return inputFiltered
while i > 0:
inputFilterText()
print(inputFilterText())
And here's my output:
I'm not really sure what's going on, but I presume it's a logical error. I've only just started using Python so any help is appreciated.
PSThe 'while' is only there so it's easier to test, it can be omitted.
You are calling inputFilterText twice. Once within the print() and once before. This is causing the code to prompt for input twice before printing the second response.
The problem is that you make a call to the inputFilterText function twice. The first time the output is discarded. Causing input to be taken twice, but only showing a result once.
To fix it, remove the inputFilterText() line. An example of working code.
import re
i=1
def inputFilterText():
inputRaw = input("input: ")
inputFiltered = re.sub(""[^a-zA-Z]+, "", inputRaw)
return inputFiltered
while i > 0:
print(inputFilterText())
Also, in future please send code as raw text, rather than screenshots.
Might I suggest using a variable here, you're not doing anything with the first filter call (this is why it's asking the first time) and the second one you're only printing.
while True:
txt = inputFilterText()
#do some stuff if needed
print(txt)

Strange behaviour with String reversal function

I am using recursion to reverse a string. I am able to reverse a string successfully using following code.
def rev(string):
if len(string)==0:
return string
if len(string)==1:
return string
else:
s=string
string = s[-1]+rev(s[:-1])
return string
But when i am replacing return with print it is printing only the first two characters of answer and then throwing an error saying
"TypeError: cannot concatenate 'str' and 'NoneType' objects"
Example. when give 'StackOverflow' to function and returned a value it returns 'wolfrevOkcatS' corrrectly
but when I am trying to print the answer in the function itself, it is only printing "tS" giving the error above.
I suspect that you did something like this:
def rev(string):
if len(string)==0:
print string
if len(string)==1:
print string
else:
s=string
string = s[-1]+rev(s[:-1])
print string
Let's get right to the problem. Supposed the string you are trying to reverse is abc. In the first call, you will hit the else clause and try to evaluate:
'c' + rev('ab')
The problem is now that your function has no return statements, rev('ab') returns None. And python raises an error when you try to concatenate a string with None.
With the return statements. rev('ab') returns 'ba' and the plus sign can be used to concatenate 'c' with 'ba'.
As an aside, if you are ever trying to solve this problem in production code, you should be using the built in tools.
reversed_str = myStr[::-1]
reversed_str_iterator = reversed(myStr)
If you're replacing return with print, your function will not return anything. In Python, that is the same as returning None. This breaks your recursive step where you concatenate the last letter of the string with the return value of the recursive call. Instead, you should just let the recursive call do its own printing (just call it), after print the last letter in a separate statement:
else:
print(s[-1], end="") # or print s[-1], (with the comma!) if you're on Python 2
rev(s[:-1])
Note that you probably want your base cases to print a newline in this situation, since otherwise you won't get one at all.
If you don't return from a function, then the function implicitly returns None. By replacing return with print, you break the recursive functionality; it recurses, but the values computed in the recursive calls are not returned and used. If you want to print intermediate results for your own edification, do so, but do so just before each return statement, not in place of the return statements.
To reverse a string/list in Python use list[::-1]
Demo
>>> my_str = 'StackOverflow'
>>> my_str[::-1]
'wolfrevOkcatS'

Python pass print statement including non strings to function

I'm trying to generate a log class which has a function that takes input and prints it to a log file. When printing to the console an example can be:
print("hi",[1,2,3])
which results in
hi [1,2,3]
However I have a function:
def printLog(input):
self.file.write('%s\n' % input)
However, passing this combination wouldn't work right. Is there someway I can pass "hi, [1,2,3]" as a string. This would have to convert the list to be printed exactly as it is printed in the console screen? This should deal with all data types, not just lists.
Use the file argument of print() function:
def printLog(*inp):
print(*inp, file=self.file)
You need to build the string yourself. The print statement (and function, when available) automatically calls str on each of its arguments, then prints them separated (by default) by a space.
def printLog(*input):
self.file.write('%s\n' % (" ".join(str(x) for x in input),))
how bout
print("A",[1,2,3],file=self.file)
Well, if I'm not mistaken, couldn't you just typecast the input into a string using str() right after you define printLog?
def printLog(input):
input = str(input)
self.file.write('%s\n' % input)

String Delimiter in Python

I want to do split a string using "},{" as the delimiter. I have tried various things but none of them work.
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
Split it into something like this:
2,1,6,4,5,1
8,1,4,9,6,6,7,0
6,1,2,3,9
2,3,5,4,3
string.split("},{") works at the Python console but if I write a Python script in which do this operation it does not work.
You need to assign the result of string.split("},{") to a new string. For example:
string2 = string.split("},{")
I think that is the reason you think it works at the console but not in scripts. In the console it just prints out the return value, but in the script you want to make sure you use the returned value.
You need to return the string back to the caller. Assigning to the string parameter doesn't change the caller's variable, so those changes are lost.
def convert2list(string):
string = string.strip()
string = string[2:len(string)-2].split("},{")
# Return to caller.
return string
# Grab return value.
converted = convert2list("{1,2},{3,4}")
You could do it in steps:
Split at commas to get "{...}" strings.
Remove leading and trailing curly braces.
It might not be the most Pythonic or efficient, but it's general and doable.
I was taking the input from the console in the form of arguments to the script....
So when I was taking the input as {{2,4,5},{1,9,4,8,6,6,7},{1,2,3},{2,3}} it was not coming properly in the arg[1] .. so the split was basically splitting on an empty string ...
If I run the below code from a script file (in Python 2.7):
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
print string.split("},{")
Then the output I got is:
['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3 ']
And the below code also works fine:
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
def convert2list(string):
string=string.strip()
string=string[:len(string)].split("},{")
print string
convert2list(string)
Use This:
This will split the string considering },{ as a delimiter and print the list with line breaks.
string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3"
for each in string.split('},{'):
print each
Output:
2,1,6,4,5,1
8,1,4,9,6,6,7,0
6,1,2,3,9
2,3,5,4,3
If you want to print the split items in the list only you can use this simple print option.
string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3"
print string.split('},{')
Output:
['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3']
Quite simply ,you have to use split() method ,and "},{" as a delimeter, then print according to arguments (because string will be a list ) ,
like the following :
string.split("},{")
for i in range(0,len(string)):
print(string[i])

Categories

Resources