Stuck with a list in a loop - python

So for a while now i've been trying to complete this exercise. The idea is to store inputs of numbers in a list, until the word 'done' is entered. Then print the minimal and maximal values of integers. And it seems i can't get it to work however many solutions i've tried, and it raised some stupid questions i would love to get answers for. So here's my best try i guess:
while True:
mylist=[]
mylist=[mylist.append(input('Please enter a number'))]
if 'done' in mylist:
print(min(mylist[:len(mylist)-4]))
print(max(mylist[:len(mylist)-4]))
break
And unsurprisingly it doesn't work, and i've no idea why, and i've exhausted all of my ideas to get it to work. But i have i stupid question. If i declare a list in a loop like i did it here, will the declaration make it empty again while it loops a second time? If it does, then how do i declare list and use it in a loop when Python doesn't want me to use global variables? Also i might have used 'break' here incorrectly, but it doesn't really matter, since the code doesn't go that far, it's just reading inputs.

store inputs of numbers in a list, until the word 'done' is entered.
1) Create an empty list before the loop. Otherwise, you are clearing the list every iteration.
2) Stop the loop when you see "done" (use break). Don't append to the list unless you have some other input. It would also help to add try-except around the int(x)
numbers = []
while True:
x = input("Enter a number: ")
if x == "done":
break
numbers.append(int(x))
Then print the minimal and maximal values of integers
Outside the loop (or before the break), you can print the values. You don't need any list slicing to check mins and maxes
print("Min", min(numbers))
print("Max", max(numbers))

If i declare a list in a loop like i did it here, will the declaration make it empty again while it loops a second time?
Yes. The line mylist=[] creates a new empty list, and makes mylist into a name for that new empty list (forgetting whatever it used to be a name for), every time it gets executed.
If it does, then how do i declare list and use it in a loop…
Just do it outside the loop:
mylist=[]
while True:
… when Python doesn't want me to use global variables?
The distinction is between local variables, defined inside a function body, and global variables, defined outside of any function body. Since you haven't written any function definitions at all, all of your variables are global variables anyway.
And, if you moved all of this inside a function, all of your variables would be local variables, whether they're inside the loop or not.
Anyway, this still isn't going to fix your code, because of a number of other problems:
mylist.append(…) modifies the list in-place, and returns None.
mylist=[mylist.append(…)] throws away the existing list and replaces it with the useless list [None].
mylist is (supposed to be) a list of strings, not a string, so mylist[:len(mylist)-4] isn't throwing away the final 4-character string, it's throwing away the last 4 strings, whatever they are.
min on a list of strings will compare them as strings, in dictionary order, not as numbers. You have to convert them to numbers if you want to compare them as numbers. But you can do this on the fly, using key=float. (See the Sorting HOWTO for more.)
While we're at it, you can simplify a few things:
x[:len(x)-4] does the same thing as x[:-4].
But, instead of adding the new string to the list and then checking whether 'done' is anywhere in the list, and then looping over the whole list except for the done, why not just check the new string?
So, here's some code that does what you want:
mylist = []
while True:
number = input('Please enter a number')
if number == 'done':
print(min(mylist, key=float))
print(max(mylist, key=float))
break
else:
mylist.append(number)

Related

Why I can't use pass in python if else statement when use condition in a single line [duplicate]

This question already has answers here:
Skip elements on a condition based in a list comprehension in python
(3 answers)
Closed last month.
I want to check if an item is in a list and if not, I want to append it to the list.
Usually I would write it:
if item not in list:
list.append(item)
else:
pass
However, I got to the point where I try to keep my code shorter and got to this:
list.append(item) if item not in list else list
To be fair, only list.append(item) if item not in list is my own creation. The else statement is due to insistence of PyCharm.
Now to my question: Why can't I follow up the else statement with pass but must write list instead. I can't wrap my head around it, nor did Google help too.
Thanks for your clarifications.
There is a difference between an if statement and a conditional expression.
When you write
if condition:
this()
else:
that()
you are writing a statement. It is an imperative construct — it does something. And the else bit is optional; if it is omitted, the statement will do nothing if the condition is not fulfilled.
The this if condition else that construct is an expression. It computes a value. It always has to compute a value, so the else bit has to be there. Using it for its side effects, for example by calling `list.append(), which doesn't return anything useful, is... not exactly wrong, but... well, it is wrong. Not technically, but philosophically.
So, when you want to compute a value, in one of two possible ways, and the whole thing fits in a line or so, use a conditional expression. If you want to do either of two things, one of which may be nothing, use an if statement.
Notice that you write
if temperature < 0:
coat = thick
else:
coat = thin
but
coat = thick if temperature < 0 else thin
In the first case, you have an if statement that selects which of two assignment statements to execute. In the second case, you have a single assignment statement, which uses a conditional expression to decide which value to assign.
Expressions can be used as statements (in which case their value is simply ignored), but statements have no value, and thus cannot be used as expressions.
In your first snippet, the else statement is redundant, i.e.
if item not in a_list:
list.append(item)
is enough and is as short and idiomatic as it can get (you might want to try sets for performance though).
In the second snippet, you're using a conditional expression to append to a list, which is not what those expressions are for. A conditional expression must have a value regardless of the condition, and pass is not a value. Use the conditional statements like above unless you need to compute a value based on the condition.
From docs(also provided by Pycharm):
pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet)
In python it's not allowed if you are using ternary operator interpretation, so in else you need to do something
so your solution is:
if item not in list:
list.append(item)
Or use set()
set.add(item)
You can shorten your code even more by using the and operator
item not in list and list.append(item)
It will only execute list.append(item) if item not in list returns True

How can i use the "list" function and get all items in a single index on python?

So i'm working on this really long program, and i want it to save an input inside of a new list, for that i have tried doing:
thing=list(input("say something")) #hello
print(thing)
#[h,e,l,l,o]
how can i arrange it to get [hello] instead?
Offhand, I'd say the easiest would be to initialize thing with an empty list and then append the user's input to it:
thing = []
thing.append(input("say something: "))
Use:
thing = [input("say something")]
In your version "hello" is treated as an iterable, which all Python strings are. A list then gets created with individual characters as items from that iterable (see docs on list()). If you want a list with the whole string as the only item, you have to do it using the square bracket syntax.

How to print a word in a list which has been assigned a random number?

I was wondering if anyone could help me with this problem.
In my piece of code that I am working on, I am creating a game upon which the user guesses a word from the list imported from a text file in python 3.3. I choose a random word from the list e.g
words = random.randint(0,len(wordlist))
I have successfully, got the program working, however when the user gets the word wrong, it prints the random number its assigned to not the word from the list. for example
else:
print("No, the answer was",words)
I was wondering how to get to print the word from the list not the random number?
Don't use a random number at all. Use the random.choice() function instead:
words = random.choice(wordlist)
random.choice() picks a random item from the list.
Your use of random.randint() has two problems:
You now need to always use wordlist[words] each time you want the word; you are never really interested in random integer, so there is no point in storing that. But
words = wordlist[random.randint(0, len(wordlist))]
is rather more verbose than the random.choice() alternative.
random.randint() picks a number between the start and stop values, inclusive. That means you can end up picking exactly len(wordlist), but there is no such index in your wordlist list; you'd get an IndexError. You need to use random.randint(0, len(wordlist)) - 1, really, or perhaps random.randrange(len(wordlist)) instead.
But again, random.choice() is just easier.

Python 3.x dictionary-based keygen help?

I'm studing Python for one month and I'm trying to make a keygen application by using the dictionary. The idea was to compare each letter in name = input('Name: ') to dict.keys() and print as result dict.values() for each letter of name equal to dict.keys(). That's what I wrote:
name = input('Name: ')
kalg = dict()
kalg['a'] = '50075'
kalg['b'] = '18099'
kalg['c'] = '89885'
etc...
I tryed writing this...
for x in kalg.keys():
print(x)[/code]
...but i need to keep print(x) result but i don't know how to do it! If i do this:
for x in kalg.keys():
a = x
'a' keeps only the last key of the dictionary :(. I thought it was because print(x) prints each key of dict.keys() on a new line but i don't know how to solve it (I tryed by converting type etc... but it didn't work).
Please can you help me solve this? I also don't know how to compare each letter of a string with another string and print dict.values() as result and in the right position.
Sorry for this stupid question but i'm too excited in writing python apps :)
# Karl
I'm studing Python over two differt books: 'Learning Python' by Mark Luts which covers Python
2 and a pocket which covers Python 3. I examined the list comprehension ón the pocket one and Imanaged to write three other variants of this keygen. Now i want to ask you how can I implementthe source code of this keygen in a real application with a GUI which verify if name_textbox andkey_textbox captions match (i come from basic so that was what i used to write, just to give youan idea) as the keygen output result. I know i can try to do this by my own (I did but with nosuccess) but I would like to first complete the book (the pocket one) and understand all the mainaspects of Python. Thank you for the patience.
Calling print can't "keep" anything (since there is no variable to store it in), and repeatedly assigning to a variable replaces the previous assignments. (I don't understand your reasoning about the problem; how print(x) behaves has nothing to do with how a = x behaves, as they're completely different things to be doing.)
Your question boils down to "how do I keep a bunch of results from several similar operations?" and on a conceptual level, the answer is "put them into a container". But explicitly putting things into the container is more tedious than is really necessary. You have an English description of the data you want: "dict.values() for each letter of name equal to dict.keys()". And in fact the equivalent Python is shockingly similar.
Of course, we don't actually want a separate copy of dict.values() for each matching letter; and we don't actually want to compare the letter to the entire set of dict.keys(). As programmers, we must be more precise: we are checking whether the letter is a key of the dict, i.e. if it is in the set of dict.keys(). Fortunately, that test is trivial to write: for a given letter, we check letter in dict. When the letter is found, we want the corresponding value; we get that by looking it up normally, thus dict[letter].
Then we wrap that all up with our special syntax that gives us what we want: the list comprehension. We put the brackets for a list, and then inside we write (some expression that calculates a result from the input element) for (a variable name for the input elements, so we can use it in that first expression) in (the source of input elements); and we can additionally filter the input elements at the same time, by adding if (some condition upon the input element).
So that's simple enough: [kalg[letter] for letter in name if letter in kalg]. Notice that I have name as the "source of elements", because that's what it should be. You explained that perfectly clearly in your description of the problem - why are you iterating over dict.keys() in your existing for-loops? :)
Now, this expression will give us a list of the results, so e.g. ['foo', 'bar', 'baz']. If we want one continuous string (I assume all the values in your dict are strings), then we'll need to join them up. Fortunately, that's easy as well. In fact, since we're going to pass the results to a function taking one argument, there is a special syntax rule that will let us drop the square brackets, making things look quite a bit neater.
It's also easier than you're making it to initialize the dict in the first place; idiomatic Python code rarely actually needs the word dict.
Putting it all together:
kalg = {'a': '50075', 'b': '18099', 'c': '89885'} # etc.
name = input('Name: ')
print(''.join(kalg[letter] for letter in name if name in kalg))
I can only guess, but this could be what you want:
name = input('Name: ')
kalg = {'a':'50075', 'b': '18099', 'c': '89885'}
keylist = [kalg[letter] for letter in name]
print(" ".join(keylist))

print statement in for loop only executes once

I am teaching myself python. I was thinking of small programs, and came up with an idea to do a keno number generator. For any who don't know, you can pick 4-12 numbers, ranged 1-80, to match. So the first is part asks how many numbers, the second generates them. I came up with
x = raw_input('How many numbers do you want to play?')
for i in x:
random.randrange(1,81)
print i
Which doesn't work, it prints x. So I am wondering the best way to do this. Make a random.randrange function? And how do i call it x times based on user input.
As always, thank you in advance for the help
This should do what you want:
x = raw_input('How many numbers do you want to play?')
for i in xrange(int(x)):
print random.randrange(1,81)
In Python indentation matters. It is the way it knows when you're in a specific block of code. So basically we use the xrange function to create a range to loop through (we call int on x because it expects an integer while raw_input returns a string). We then print the randrange return value inside the for block.

Categories