I'm not getting expected result , I want to know what's wrong with the code - python-3.5

I want to know whether I can use Input function under for loops and Lists?
I'm using the latest version of python 3.7.4.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
if (K in List):
print("yes it's in the list")
else:
print("It's not in the list")
If I entered apple I'm getting the result as it's not on the list. I want to know whether we can use Input function under for loops and lists with if-else conditions.

Your issue is with the line
K=print(input('Enter the Value:'))
You do not need print here. Print is a function that takes a value, prints it to your screen and returns None. You passed the input to print, but you want to store the value in K, not print it to the screen (the user is entering the value so they probably do not need to see it again). So change this to:
K=input('Enter the Value:')

Here you can check your error with print function.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
print(K)
.....
K is None in this case.

Related

Range function not iterating whole list, help me pls

def count4(lst):
count = 0
for i in range(lst[0],lst[-1]+1):
print(i)
print(count4([1,2,3,4,5,6,4,5,4,4]))
Here the output is showing just "1234" and not the whole list pls tell me how to iterate this list using range function.
The reason you are getting output as "1234"
The below statement
for i in range(last[0], last[-1]+1):
is interpreted as
for i in range(1, 4 + 1):
i.e
for i in range(1,5):
Solution: Use this
for i in lst:
You were trying to iterate in the range of values stored in the list at starting and end position that was passed, which is logically incorrect.
The other suggested methods are also correct since you specifically said to use the range function so think this might be the answer you were looking for
def count4(lst):
for i in range(len(lst)):
print(lst[i])
print(count4([1,2,3,4,5,6,4,5,4,4]))

Defining a function to find the unique palindromes in a given string

I'm kinda new to python.I'm trying to define a function when asked would give an output of only unique words which are palindromes in a string.
I used casefold() to make it case-insensitive and set() to print only uniques.
Here's my code:
def uniquePalindromes(string):
x=string.split()
for i in x:
k=[]
rev= ''.join(reversed(i))
if i.casefold() == rev.casefold():
k.append(i.casefold())
print(set(k))
else:
return
I've tried to run this line
print( uniquePalindromes('Hanah asked Sarah but Sarah refused') )
The expected output should be ['hanah','sarah'] but its returning only {'hanah'} as the output. Please help.
Your logic is sound, and your function is mostly doing what you want it to. Part of the issue is how you're returning things - all you're doing is printing the set of each individual word. For example, when I take your existing code and do this:
>>> print(uniquePalindromes('Hannah Hannah Alomomola Girafarig Yes Nah, Chansey Goldeen Need log'))
{'hannah'}
{'alomomola'}
{'girafarig'}
None
hannah, alomomola, and girafarig are the palindromes I would expect to see, but they're not given in the format I expect. For one, they're being printed, instead of returned, and for two, that's happening one-by-one.
And the function is returning None, and you're trying to print that. This is not what we want.
Here's a fixed version of your function:
def uniquePalindromes(string):
x=string.split()
k = [] # note how we put it *outside* the loop, so it persists across each iteration without being reset
for i in x:
rev= ''.join(reversed(i))
if i.casefold() == rev.casefold():
k.append(i.casefold())
# the print statement isn't what we want
# no need for an else statement - the loop will continue anyway
# now, once all elements have been visited, return the set of unique elements from k
return set(k)
now it returns roughly what you'd expect - a single set with multiple words, instead of printing multiple sets with one word each. Then, we can print that set.
>>> print(uniquePalindromes("Hannah asked Sarah but Sarah refused"))
{'hannah'}
>>> print(uniquePalindromes("Hannah and her friend Anna caught a Girafarig and named it hannaH"))
{'anna', 'hannah', 'girafarig', 'a'}
they are not gonna like me on here if I give you some tips. But try to divide the amount of characters (that aren't whitespace) into 2. If the amount on each side is not equivalent then you must be dealing with an odd amount of letters. That means that you should be able to traverse the palindrome going downwards from the middle and upwards from the middle, comparing those letters together and using the middle point as a "jump off" point. Hope this helps

how to convert an int array to string in python

I have a problem in converting an int array into string. Here is my part of code
response_list=[]
for key in json_response['response_code']:
if json_response['response_code'][key] ['0'] is True:
print('No such exist')
response_list.append('Check')
sys.exit()
What happens is this 'response_code' that is part of the output result of my entire code consist of either 0 and 1. So what I want to do is if 'response_code' is 0 in the output result print the needy and exit the whole operation.
I used for but it says 'int is not iterable with for loop. I tried using the dictionary:
response_list=[]
keydict=str(json_response['response_code'])
for key in keydict:
if keydict == ['0'] is True:
print('No such exist')
response_list.append('Check')
sys.exit()
I still get the int is not iterable
TypeError: 'int' object is not iterable
Can someone please explain how to solve the issue
p.s response_list stores the values so I can use later in my code.
What happens in my full code:
I have a list of urls where I want to get it scanned from VirusTotal API. So the API scans the list of urls one by one and if response code = 1 that means API outputs results. If the response code for another url becomes 0 it means API does not show result
You can only use a list for the iteration in For loop as you are using a dict and string doesn't work in you case
Trying to Iterate JSON
for key in json_response['response_code']
Trying to Iterate String
for key in str(json_response['response_code'])
Make sure you are using a valid list for the iteration.
Post your json_response['response_code'] structure if you need any help with the iteration of a specific value in the JSON.
if keydict == ['0'] is True:
This will not work,
If you want to check a variable
if keydict == ['0']: If you want to check for a specific value
if keydict: if you want to check if the keydict has a value

How this happens in Python?

I created a function showed below, and if called print(sum_num(1,2)) it will show up 2 output which are 3 and None. As long as I removed print, it would go right. Can anyone explain why it will work like this? Thank you so much!
enter image description here
Add return statement to your function.
You are only printing the value in function so it will first print 3 which is 1+2
but it returns None That's where your 2nd output comes from.
Use below code:
def sum_num(a,b):
# print(a+b)
return a+b
print(sum_num(1,2))

Program ignores all the numbers after the 1st one

Why the program takes just the first number in the list and ignores others, making an empty list.
This happens in every function with for loop.
cars=[23.11,1531,'volvo','BMW']
def price(CAR):
num=[]
strings=[]
for i in CAR:
if isinstance(i,float)or isinstance(i,int):
num.append(i)
elif isinstance(i,str):
strings.append(i)
else:
pass
return num,strings
print(price(cars))
([23.11], [])
The only reason I can think of is, your return statement is aligned with your for loop, so it exists after the first iteration. (Though it looks aligned correctly right now, maybe the editor corrected it instinctively.)

Resources