Hi there,
I'm writing my first Python script for a(n imperative) programming class at university, and I want to make it a little better. It's meant to be fairly short, 50 lines. I've written the basic 'mechanism' to look at the user input.
Instead of simply printing every property of the input (it analyses an integer input and tells you if they are such and such, WOW!), I want to make a dictionary containing the 'name' of each property and whether it's true or not, or it's value. for instance, {'Even':True}. Fair enough. I also want the program to repeatedly ask the user for input (to type in one of the keys from the dictionary), so each time there is an input, it prints the value and then asks the same question. This is my main issue. I've only seen the Python tutorial, and I haven't found anything relevant.

In short: How do I keep doing the same thing over and over?

Also, how do I get a program not to close when it's done?

Use while loops, if you've got the Zelle book read that, if not I suggest you get it.
Click here

While loops, if set to "True" basically means they will continuously cycle through the loop forever, unless you enter a "break" function within the loop's body if a certain condition has been met. (e.g. if what the user has entered something you deem as correct or if a certain variable with a value has reached a certain number)

Example:

while True:
         word = input("Please enter a word, and not a number: ")
            if word.isalpha() == True:
                 break
            else:
                 print("You did not enter a word")

Until the user has entered a word, and not a number, the while loop will continuously run around the body (i.e. keep asking until a word has been entered, and the body of the if statement orders the loop to break. Causing the question to stop being asked)

Note: you can enter conditions in the while loop rather than just True, but like I say, get the Zelle book and read it - I'm a student and it's helped me out a massive amount.

I'm not quite sure I follow you, sorry. I've only used 'while' once, and it was to decide whether or not to ask the user for input a second time. The loop you gave seems to be concerned whether the input is a word. I don't understand your loop entirely or how I could integrate it into my script, sorry.
Maybe I should post parts of my code so far(end of post)? My question is badly worded, I'll admit. English isn't my first language, and my mastery of Python or the basic tenets of programming are inexistent.

Basically, my program will make a dictionary containing names of properties and their values(determined by the main body of the script below). Now, once this dictionary is complete, I want the program to ask the user to give another input. This input is meant to be a key from the dictionary. It will then print the corresponding value out of the dictionary, and then ask the same question again. It's just meant to keep asking the same question,regardless of what it prints or what input is given. If the input is not a key in the dictionary, it is also meant to repeat the question.

Here is my very bad little script in progress. It's undergoing the transformation from printing to dictionary entries, so instead of printing strings that tell you whether it is prime, even etc, it will add them as values to some dictionary key. I hope the inclusion of my incomplete source code helps you to understand my inane ramblings.
Sorry for long reply.

EDIT: I have gotten it to ask for keys (UI=str(raw_input('What are you looking for?'))
;print Properties[UI]). It works. Now for the repeating of the question...

import math

n=int(raw_input('Enter a positive integer:'))
m=[1]
p=range(2,n)
Properties={'Proper divisors':m ,'Perfect':'Start', 'Prime':'A string', 'Square root':'Nothing yet', 'Even or odd':'Will be added by the program itself by replacing it with another string later', 'Triangular':'same', 'Square':'ditto'}


for x in p:
    if n%x==0:
        m.append(x)
        p.remove(x)
    else:
        pass
    
if len(m)>1:
    Properties['Proper divisors']= str(m)
else:
    pass

a=reduce(lambda y,x: x+y, m)

if a==n:
    Properties['Perfect']= str(n)+' is a perfect number'
else:
    Properties['Perfect']= str(n)+' is an imperfect number'

if len(m)==1:
    Properties['Prime'] 'Yes'
else:
    Properties['Prime'] 'No'

squareroot=math.sqrt(n)
Properties['Square root'](str(n)+' has square root '+str(squareroot))

r=tuple(m)
if 2 in r:
    Properties['Even or odd']='Even'
elif len(m)!=1:
    Properties['Even or odd']='Odd'
elif len(m)==1:
    pass

if n==2:
    print('This number is even')

for g in range(2,n):
    if reduce(lambda y,x: x+y, range(1,g))==n:
            print(str(n)+' is a triangular number')
            break
else:
    pass
            
for g in range(2,n):
    if g**2==n:
        print (str(n)+' is a square number')
        break
    else:
        pass

For a program to have repetitive request input, you need to understand while loops, if statements and decision structures

Run what I wrote in shell and see if you can understand it.

Nevermind, I think I fixed it. Thanks for your help, a loop did the trick.

while n>0:
    UI=str(raw_input('What are you looking for?'))
    if UI=='Everything' or UI=='All':
        print Properties
    else:
        print Properties[UI]

'n' is the raw input at the beginning of the program.

I am doing some 'debugging' now. Not all inputs appear to work.

For a program to have repetitive request input, you need to understand while loops, if statements and decision structures

Run what I wrote in shell and see if you can understand it.

I think I understand 'while' loops a bit better now. Thanks for your help.

I'll take a look at your code in Shell, but I think I understand it. If the input is a word, it stops the loop, if it is not a word, it tells you so. I don't understand the first line, though. while True. What is true?Maybe running it in Shell will help, as you say

For me it would be lot cleaner style to use normal binary arithmetic for even/odd:

>>> def odd(n):
	return bool(n & 1)

>>> def even(n):
	return not odd(n)

>>> even(123123)
False
>>> odd(123123)
True
>>>

If you want you could have class and have the things you like to establish as properties:

>>> class NumberWithProperties(int):
	@property
	def odd(n):
		return bool(n & 1)
	@property
	def even(n):
		return not odd(n)

	
>>> n = NumberWithProperties(123123)
>>> n.odd
True
>>> n.even
False
>>> n+4
123127
>>> (n+4).odd

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    (n+4).odd
AttributeError: 'int' object has no attribute 'odd'
>>> k = NumberWithProperties(1.232)
>>> k
1
>>>

You could say it also

while 'Hell is not frozen':
        #do your stuff

if you understand it better as anything not 0-like value is True.

If and when you decide to get the Zelle book, maybe look up boolean expressions as well.

But doing:

while True:

Enables the loop to get started and start producing whatevers within the loop. However, if it was:

while False:

It would never start. That's why in my first post I said you can make different conditions to make the while loop begin. E.g. if you writ something like this:

number = 1

while number == 1:
         word = input("Please enter a word, and not a number: ")
            if word.isalpha() == True:
                 break
            else:
                 print("You did not enter a word")

That means the loop will always keep on running through it's content, as long as the "number" variable has the value "1". Basically the same principle as having the condition set to "True" (which is what we originally had anyway). But if you were to change the code to this:

number = 1

while number == 1:
         word = input("Please enter a word, and not a number: ")
            if word.isalpha() == True:
                 break
            else:
                 print("You did not enter a word")
                 number = number + 1

Then after the loop going through once, and only once, it would stop running through it's content. Because the value of the variable "number" has changed and is no longer equal to "1", which is the while loop's condition (number == 1).

So the above code is basically say in english:

while the variable "number" is equal to the number "1":
        Ask the user to a [I]word[/I]:
            Check to see if what the user has entered is actually a word or not:
                If it is, then break out of the loop
            If what the user has entered isn't a word:
                Tell the user it isn't a word
                Increase the value of the variable "number" by 1, causing the loop to stop.

This code can be changed in so many ways if you understand it properly. Seriously though, get the Zelle book lol.

You could say it also

while 'Hell is not frozen':
        #do your stuff

if you understand it better as anything not 0-like value is True.

I agree that your way of determining whether a number is odd or even is cleaner.
As for classes, I'm not doing object-oriented programming and I don't know what classes are. Maybe if I take CS as option next semester...it's OO time then. For now, I had the program make a list of proper divisors, so it seemed straightforward enough to check whether it is even or odd by seeing whether or not 2 is a proper divisor.

As for the 'while' loops, could it be that there is a misunderstanding?
I understand the structure for 'while' insofar as it basically means:
while statement true,
perform some action.
The 'while' loop I wrote up earlier works fine. I don't quite understand AdampskiB's use of 'True' as a condition in his first reply, is all. Not used to seeing Python explained other than in the Documentation.


And to AdampskiB's latest reply (can't quote properly, sorry):
I understand this loop. I used a loop to make it repeat the question. I'm going to add another while loop for n==1 and for n<0 in a minute, but I just got home from the library. What's this book by Zelle? haven't heard of it, and it's not on amazon.

Here's the improved script:

import math

n=int(raw_input('Enter a positive integer:'))
m=[1]
p=range(2,n)
Properties={'Proper divisors':m ,'Perfect':'Start', 'Prime':'A string', 'Square root':'Nothing yet', 'Even or odd':'Odd', 'Triangular':'No', 'Square':'No'}

for x in p:
    if n%x==0:
        m.append(x)
        p.remove(x)
    else:
        pass
    
if len(m)>1:
    Properties['Proper divisors']= str(m)
else:
    pass

a=reduce(lambda y,x: x+y, m)

if a==n:
    Properties['Perfect']= str(n)+' is a perfect number'
else:
    Properties['Perfect']= str(n)+' is an imperfect number'

if len(m)==1:
    Properties['Prime']='Yes'
else:
    Properties['Prime']='No'

squareroot=math.sqrt(n)
Properties['Square root']=str(squareroot)

r=tuple(m)
if 2 in r:
    Properties['Even or odd']='Even'
elif len(m)!=1:
    Properties['Even or odd']='Odd'
elif len(m)==1:
    pass

if n==2:
    Properties['Even or odd']='Even'

for g in range(2,n):
    if reduce(lambda y,x: x+y, range(1,g))==n:
            Properties['Triangular']='Yes'
            break
else:
    pass
            
for g in range(2,n):
    if g**2==n:
        Properties['Square']='Yes'
        break
    else:
        pass

while n>0:
    UI=str(raw_input('What are you looking for?'))
    if UI=='Everything' or UI=='All':
        print Properties
    elif UI=='Properties' or UI=='List':
        print Properties.keys()
    elif UI not in Properties:
        pass
    else:
        print Properties[UI]

If you were to set a while loop with a condition of "True", with no break function within it's body to cause it to stop, then the loop will execute the body forever, never ending. You would often use "True" if you do not know the exact number of how many times you want to execute the body.

Click here to look at the John Zelle book from Amazon (UK)

If you were to set a while loop with a condition of "True", with no break function within it's body to cause it to stop, then the loop will execute the body forever, never ending. You would often use "True" if you do not know the exact number of how many times you want to execute the body.

Click here to look at the John Zelle book from Amazon (UK)

I think I understand now. You used True as a kind of generic condition, which is always true, so it will continue on forever. I didn't know this was a syntactic possibility. Sort of like my condition of n>0 is always the same because 'n' is in a sense immutable within the program after its initial input. Hadn't looked at it this way.
The book by Zelle looks to be quite good. I hadn't found it on Amazon Germany, where I buy some of my things. Is it more dense/terse or more conversational?
I think I'm starting to understand Python much better, but certain grammatical and syntactical subtleties elude me due to my lack of experience, which makes programming harder.
I'm not sure how much more programming I will do after this course, but learning some more of it seems interesting. Especially if the program can interact with the system, for example changing files or generating them. I had another idea for my assignment, but it was too complex for my weak skills.

All of the else: pass statements do nothing and can be eliminated

if len(m)>1:
    Properties['Proper divisors']= str(m)
else:                 ## does nothing
    pass
#
#
while n>0:             ## you don't change "n" so this is an infinite loop
    UI=str(raw_input('What are you looking for?'))
    if UI=='Everything' or UI=='All':
        print Properties
    elif UI=='Properties' or UI=='List':
        print Properties.keys()
    elif UI in Properties:     ## print all other properties for UI
#    elif UI not in Properties:
#        pass
#    else:
        print Properties[UI]

All of the else: pass statements do nothing and can be eliminated

if len(m)>1:
    Properties['Proper divisors']= str(m)
else:                 ## does nothing
    pass

You are right. I took one out and the program works the same. I put them in there because I thought the syntax might require them: 'The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action' (From the Python documentation). Looks like I was wrong again. Thank you

Your right with the n>0. Now from knowing that you could possibly understand my use of the "number" variable as a condition in the while loop in my previous posts. I think Python definitley is an exciting code to use, but I'm almost finished with my copy of Zelle as we only have few weeks left of Unit so I'll send you a quick PM.

Your right with the n>0. Now from knowing that you could possibly understand my use of the "number" variable as a condition in the while loop in my previous posts. I think Python definitley is an exciting code to use, but I'm almost finished with my copy of Zelle as we only have few weeks left of Unit so I'll send you a quick PM.

I understand both your loops now. I didn't anticipate that 'True' could be used, but ' while number==1' is something I've used before. That being said, I'm very happy that we got to choose a language for ourselves in this course. C++ is not something I'd want to be work with, even though it's the standard for non-CS students at many universities in programming courses.

I would myself recommend 'Dive into Python' or 'Dive into Python3' for learning thoroughly and practically (no strange non-standard graphics modules).

http://diveintopython.net
http://diveintopython3.net

In that case then I'd go with what tony recommended. He seems to be the python dude around here.

I would myself recommend 'Dive into Python' or 'Dive into Python3' for learning thoroughly and practically (no strange non-standard graphics modules) Python.

I haven't looked at the newest Python version at all, I downloaded Python 2.7. Seems like both 'Dive into Python' and Zelle's book have very good reviews on Amazon. What's the style like in this book?

EDIT: Didn't realise the entire book was available online. Looks good. Already learned something new

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.