for loop find in list with if statement [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have the following question:
considering the given list :
list = ['12','8','3']
why does print('8' in list) returns True
whereas
for i in range(5):
if '8' in list == True:
(code)
doesn't execute my code inside the if loop ?
Could someone explain me why, and how could I make this work ?
Maybe this question has already been asked but I don't see with which keywords I should search for it.
Thanks for the help :-)

You seem to have some logical errors in your code, so I'll try to outline what you should be doing.
You shouldn't name variables str or list or int because they might conflict with Python's built in keywords.
Your check did if '8' in list, but that will test if the string 8 is in the list, not the number. Drop the apostrophes.
You don't have to put if 8 in list in a loop, it'll do the looping and testing for you.
Solution
To check if a number is in a list, you can use python's built in in keyword, your write your own code to do the checking.
Remember not to use keywords like list, so I've changed the name to myList in these examples.
Using in
if 8 in myList: # Note that you don't have to say == True
print('8 is in the list!')
Or using for i in myList)
for i in myList:
if i == 8:
print('8 is in the list!')**
Or using for i in range(len(myList))
for i in range(len(myList)):
if myList[i] == 8:
print('8 is in the list!')

Related

Reverse a string with users input [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I decided to take on some programming projects and decided to follow this guide:
https://www.dreamincode.net/forums/topic/78802-martyr2s-mega-project-ideas-list/
I started with the first project, which is to reverse a string, pretty simple stuff as you can find out how to do that in the documentation. IE.
txt = "Hello World"[::-1]
print(txt)
dlroW olleH
s = "health" [::-1]
print(s)
htlaeh
And So on... There's two questions really. In this guide i'm not to sure if they just wanted you to reverse the string. It seems like they want Input? For the user to Enter the String.
In this case i thought it might be something like this:
string = Input("Enter a string")
print(s [::-1])
How ever this did not work, Not to sure how to implement this in Python 3.8.2. Could someone let me know and how they did it that would be great.
Thank you.
Your code has a space between s and the indices you want. You also have two variable names, s and string. Choose one. Finally, Input must be lowercase. Change it to this:
string = input("Enter a string")
print(string[::-1])
Your print statement needs some modifications.
Here it goes-
print(string[: :-1])

How to use the value of variable as a key in a dictionary in Python? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm continuing learning python and I want to use the value of a variable as a key in a dictionary, and the input of the user as the value of that key, but what I'm doing is doing the opposite.
def scan_option(option_type):
option_dict={}
elected_type = option_type + '_option'
option_dict.update(elected_type= raw_input("Enter the {} Option: ".format(option_type)))
return option_dict
print scan_option("Hardrive")
In case user answered 8:
The output is: {'elected_type': '8'}
and I want it to be: {'Hardrive_option': '8'}
What do I need to change in the code to do that?
update takes a dictionary as its argument. The stuff you fed it was a symbol and a string; it converts that to a dictionary and then does the update.
The syntax you need here is a simple dictionary assignment:
option_dict[elected_type] = raw_input(...)
You might try simpler commands when you first write your code. Once those work properly, then you can go for the one-line, compound commands.

re.findall working in console but not in script? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm probably missing something very basic here, but here goes:
I'm using Python 2.7 and regex to identify digits within a string.
In the console, I type in:
>>> newstr = 'NukeNews/File_132.txt'
>>> int(re.findall(r'\d+',newstr)[0])
132
Which is what I expect.
However, in the script I'm running, I have the strings stored in a dictionary, linedict. I'm running this script:
news_id=[]
for line in line_vec:
print linedict[line]
newstr= linedict[line]
id_int = re.findall('r\d+',newstr)
print id_int
news_id.append(id_int)
It's a long list, but the output looks like:
NukeNews/File_132.txt
[]
So - the correct string is registered, but it's not matching on anything.
I was calling the first item in the list earlier (to match the console input of int(re.findall(r'\d+',newstr)[0]), but the script is telling me that the regex didn't find any instances of the digits in the string. I would expect this to return:
NukeNews/File_132.txt
['132']
Any idea why it's not working as expected? When I try running re.match(r'/d+',newstr) I also get an empty group (following the groups example on https://docs.python.org/2/library/re.html).
Edit: As pointed out, this is a case of not being careful with 'r' and r'*'. I'm just going to leave this up in case anyone else googling "why does my regex work in console but not in script" forgets to check this typo, like I did.
You've got your r inside the quotes so instead of getting a "raw string" you're getting a string with an 'r' in it ...
id_int = re.findall('r\d+',newstr)
# ^
# should be:
id_int = re.findall(r'\d+',newstr)
your "console" version also only takes the first of the found matches compared to your "script" version which appends the entire list.

most efficient code for printing odd numbers from 1-99 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
The task is to print the odd numbers from 1-99 on separate lines.
Codeeval deemed this code partially correct (98 out of 100): (edited)
liszt = (i for i in range(1,100) if i%2!=0)
for i in liszt:
print i
Codeeval deemed the below code completely correct:
liszt = range(1,100)
for i in liszt:
if i%2!=0:
print i
New to Python, so just looking to understand why one method might be considered better than the other. Is the second method more efficient?
Thanks for the help!
In the first code you are iterating over two generators first range(1, 100) and then over liszt whereas in the second case the iteration is only over liszt. Other than that the operation is same in both the cases, so the second method is more efficient.
Since every second number after 1 would be odd, a better solution could be:
for i in range(1, 100, 2):
print(i)
print("\n".join(str(i) for i in range(1,100,2)))

INVALID SYNTAX ERROR for 'else' statement in python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to write a quicksort program in python, however I'm getting an invalid syntax error at else statement in the second last line below:
import random
n=int(raw_input("Enter the size of the list: ")) # size of the list
intlist = [0]*n
for num in range(n):
intlist[num]=random.randint(0,10*n)
pivot=random.choice(intlist)
list_1=[] # list of elements smaller than pivot
list_2=[] # list of elements greater than pivot
for num in range(n):
if num<=pivot:
list_1.append(num)
else
list_2.append(num)
This is not a complete program as I am still writing.
add a colon after the else so that it looks like else:. and pick up a good tutorial ;)
Looks like you need a ':' after "else".

Categories

Resources