473,387 Members | 1,495 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Loops (and the in operator) [solved]

Hi,
I'm new to Python and OO in general. I am trying to set up a simple loop based around an inputed answer to a question, so that if you input a wrong answer, you are asked the question again, but if correct, the program moves on.

For example:
What is the capital of France?

Correct answer - move on to next question. Wrong answer. Repeat the question

I used to write in basic years ago in which programs had line numbers and would have went something like this. It was easy to direct the program back again to ask the question again.


10 print "what is the capital of France?"
20 get a$ #user inputs answer
30 If A$ = "Paris" then goto 60
40 print "That is the wrong answer!. Try again"
50goto 10
60 The next question........

I'm really finding it hard to get my head round loops without line numbers.
thanks,
tim
Oct 22 '06 #1
16 1939
bvdet
2,851 Expert Mod 2GB
Hi,
I'm new to Python and OO in general. I am trying to set up a simple loop based around an inputed answer to a question, so that if you input a wrong answer, you are asked the question again, but if correct, the program moves on.

For example:
What is the capital of France?

Correct answer - move on to next question. Wrong answer. Repeat the question

I used to write in basic years ago in which programs had line numbers and would have went something like this. It was easy to direct the program back again to ask the question again.


10 print "what is the capital of France?"
20 get a$ #user inputs answer
30 If A$ = "Paris" then goto 60
40 print "That is the wrong answer!. Try again"
50goto 10
60 The next question........

I'm really finding it hard to get my head round loops without line numbers.
thanks,
tim
Try this:
Expand|Select|Wrap|Line Numbers
  1. z=1
  2. while z:
  3.     answer = ....ask for input...
  4.     if answer in [...list of possible correct answers...]:
  5.         break
  6.     else:
  7.         print "You have entered an incorrect answer. Try again."
  8.  
Oct 22 '06 #2
bartonc
6,596 Expert 4TB
Read yesterday's post "need help with code structure" for pythonic structure on how to do this.
Oct 22 '06 #3
Thanks for the replies. I've solved most of the problem. Can someone tell me why this dooes not work

namestring = input("WHAT IS YOUR NAME?" )
while namestring == 'Jack':
age = 9
while namestring == 'Rachel':
age = 7

I'm trying to set a value for age depending on what name was entered.
Also, is there a way to make Python ignore upper,lower case or a command along th same lines as
while namestring = 'Jack' or 'JACK' or 'jack':
age=9

thanks
Oct 22 '06 #4
the age is indented by the way. It just did not show on the message

tim
Oct 22 '06 #5
bartonc
6,596 Expert 4TB
the age is indented by the way. It just did not show on the message

tim
That's because you didn't USE CODE TAGS! The background of the post screen has it, the panel on the right of the post screen has it, the sticky at the top of this forum has it. Read them. Use them. It helps us a lot.

Thanks for posting, keep it up. Use code tags. Thanks,
Barton
Oct 22 '06 #6
bartonc
6,596 Expert 4TB
Thanks for the replies. I've solved most of the problem. Can someone tell me why this dooes not work

namestring = input("WHAT IS YOUR NAME?" )
while namestring == 'Jack':
age = 9
while namestring == 'Rachel':
age = 7

I'm trying to set a value for age depending on what name was entered.
Also, is there a way to make Python ignore upper,lower case or a command along th same lines as
while namestring = 'Jack' or 'JACK' or 'jack':
age=9

thanks
while creates a loop which needs a condition that changes (to "no longer true") or a break statement in order to break out of the loop.
Expand|Select|Wrap|Line Numbers
  1. namestring = raw_input("WHAT IS YOUR NAME? " )
  2. namestring = namestring.captalize() # use str type method to get a capitalized copy of namestring
  3. if namestring == 'Jack':
  4.     age = 9
  5. if namestring == 'Rachel':
  6.     age = 7
  7.  
type
help(str)
to see all the things that strings know how to do.
Oct 22 '06 #7
Thanks for all the help, but one last question!!!
Now, even if the name is entered correctly and assigned to namestring, the age value is not altered.
Any ideas?

Thanks,
Tim
Oct 23 '06 #8
I had given age an initial value age = 0 at the start of the program, but this isn't in the loop by the way

tim
Oct 23 '06 #9
bartonc
6,596 Expert 4TB
I had given age an initial value age = 0 at the start of the program, but this isn't in the loop by the way

tim

Post you program. Be sure to use code tags. It's probably a matter of scope. The scope of a variable (global or local) depends on where/how you declare/assign it.

Expand|Select|Wrap|Line Numbers
  1. aGlobal = 100
  2. def func():
  3.     aLocal = 100
  4. func()
  5. print aLocal
  6. Traceback (most recent call last):
  7. File "<pyshell#0>", line 1, in -toplevel-
  8.     print aLocal
  9. NameError: name 'aLocal' is not defined
  10.  
See what I mean?
Oct 23 '06 #10
Hi,
This is the code. I was just playing around with a simple program that would amuse kids and would teach me about using
simple loops.
the age value always seems to be 0. I would also like a bit of code to ask the name again if the wrong name was input.

thanks!!!

Expand|Select|Wrap|Line Numbers
  1. from time import sleep
  2. age = 0
  3. print 'hello'
  4. sleep(5)
  5. print 'I bet I can tell whether you are telling the truth about how old you are ?'
  6. sleep(5)
  7. print 'I CAN prove it to you'
  8. sleep(5)
  9. print 'You still dont believe me, do you?'
  10. namestring = raw_input("WHAT IS YOUR NAME?" )
  11. namestring = namestring.capitalize()
  12. if namestring == 'Jack':
  13.     age = 9
  14. if namestring == 'Rachel':
  15.     age = 7
  16. answer = 0
  17. while answer != age:
  18.     answer=input ("What is your age? ")
  19.     if answer != age:
  20.         print "YOU ARE FIBBING"
  21. print 'NOW YOU ARE TELLING THE TRUTH'
  22.  
Oct 24 '06 #11
By the way, I think the names should be capitalized, but there is no difference when i do this.
t
Oct 24 '06 #12
bartonc
6,596 Expert 4TB
By the way, I think the names should be capitalized, but there is no difference when i do this.
t
The code ran for me. It looks good too. Try this:
Expand|Select|Wrap|Line Numbers
  1. from time import sleep
  2. age = 0
  3. print 'hello'
  4. sleep(5)
  5. print 'I bet I can tell whether you are telling the truth about how old you are ?'
  6. sleep(5)
  7. print 'I CAN prove it to you'
  8. sleep(5)
  9. print 'You still dont believe me, do you?'
  10. namestring = raw_input("WHAT IS YOUR NAME?" ) 
  11. ### debug using print
  12. print namestring 
  13. ### debug using print
  14. namestring = namestring.capitalize() 
  15. ### debug using print
  16. print namestring 
  17. ### debug using print
  18. if namestring == 'Jack':
  19.     age = 9
  20. if namestring == 'Rachel':
  21.     age = 7 
  22. ### debug using print
  23. print namestring, age 
  24. ### debug using print
  25. answer = 0
  26. while answer != age:
  27.     answer=input ("What is your age? ")
  28.     if answer != age:
  29.         print "YOU ARE FIBBING"
  30. print 'NOW YOU ARE TELLING THE TRUTH'
  31.  
Using print statements is a really good way to debug your code.
Oct 24 '06 #13
Thanks for all the help. You've been patient!!!

Heres something funny. I copied your code with debug points into a new window, saved it as a new file and ran it. It worked fine. Then I took all of your debug points out and ran it again. It worked perfectly.
Then I loaded my original code and it wouldn't run, yet line by line it looks exactly the same. I can't explain that I'm afraid :-)

Thanks again

p.s. I'm only getting back into programming after a LOT of years away. Back then the Commodore Vic-20 was king and programmers could manage to write games like frogger with its 'huge' 5K (3.5K useable) of free memory :-) I could actually churn out a reasonable program myself believe it or not!!!!
Oct 24 '06 #14
If you do't mind being patient once more, can this be simplified :-

if namestring != 'Rachel' and namestring != 'Jack' and namestring != '':
Oct 24 '06 #15
bartonc
6,596 Expert 4TB
If you do't mind being patient once more, can this be simplified :-

if namestring != 'Rachel' and namestring != 'Jack' and namestring != '':
I don't mind at all. That's what we're here for.
This can be simplified in a very cool and extensible way using a list:
Expand|Select|Wrap|Line Numbers
  1. people = ['Jack', 'Rachel']
  2. if namestring not in people:
  3.     # do stuff for unknown people
  4.  
The in operator is the same a writing a function like this:
Expand|Select|Wrap|Line Numbers
  1. def IsInList(key, list):    # Return True if key is in list
  2.     for item in list:
  3.         if key == item:
  4.             return True
  5.  
in works on most iterators (lists, dictionaries, file objects, etc) in all sorts of cool ways.
I guess that you know what not does.
Oct 24 '06 #16
bartonc
6,596 Expert 4TB
I don't mind at all. That's what we're here for.
This can be simplified in a very cool and extensible way using a list:
Expand|Select|Wrap|Line Numbers
  1. people = ['Jack', 'Rachel']
  2. if namestring not in people:
  3.     # do stuff for unknown people
  4.  
The in operator is the same a writing a function like this:
Expand|Select|Wrap|Line Numbers
  1. def IsInList(key, list):    # Return True if key is in list
  2.     for item in list:
  3.         if key == item:
  4.             return True
  5.  
in works on most iterators (lists, dictionaries, file objects, etc) in all sorts of cool ways.
I guess that you know what not does.
The equivalent function above uses the in operator (I do it without thinking) as a generator so that we don't write functions like this:
Expand|Select|Wrap|Line Numbers
  1. for i in range(len(aList)):    # There's in again, can't get away from it!
  2.     yeild aList[i]
  3.  
Oct 25 '06 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: JustSomeGuy | last post by:
I have a need to make an applicaiton that uses a variable number of nested for loops. for now I'm using a fixed number: for (z=0; z < Z; ++z) for (y=0; y < Y; ++y) for (x=0; x < X; ++x)
17
by: newtothis | last post by:
I have been reading various texts in C/ C++ and Java. The for lops all run along the lines of : int i ; for(i = 0 ; i < 4 ; i++) {
4
by: Gonzalo Aguirre | last post by:
i have three classes like this class foo{ attrib_1; .. .. public: ..
0
by: cppsks | last post by:
Hello. I posted a question regarding this yesterday. I came up with the following solution but I am a little hesistant as to this solution having any side-effects that I am not aware of. The...
46
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are...
17
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html Why is C# 500% slower than C++ on Nested Loops ??? Will this problem be solved in...
20
by: Crirus | last post by:
I have this situation 25 26 ........ 9 10 11 12 13 24 1 2 3 15 23 8 x 4 15 22 7 6 5 16 21 20 19 18 17
24
by: Kunal | last post by:
Hello, I need help in removing if ..else conditions inside for loops. I have used the following method but I am not sure whether it has actually helped. Below is an example to illustrate what I...
5
by: ertis6 | last post by:
Hi all, I need to calculate a value inside 8 nested for loops. 2 additional for loops are used during calculation. It was working fine with 4 loops. My code is like this: ... for(int i1=0;...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.