Sunday 3 April 2016

continuous number increment until user input == 'specific input' Python




First to say I am new to 'asking questions' in stackoverflow so I apologize if my question is not in the right category or another similar question has been asked already. I tried to find a relevant question but I couldn't. Mine is a little specific which will serve me as an example for future programming.



The flow of the simple program I am trying to create is:





  • Having a start number of for example 0




    1. the number gets incremented by 1 until the number has incremented with 100 numbers at which point..

    2. Program asks "Y/N" if Yes then steps 1 and 2 repeat (Every time this process repeats the number should add another 100 on it self. So for example the second repetition will start from 100 and not from 0) if no the step 3

    3. The program prints the largest number that was reached





This is my code:



def creeper (number, growth):
while number <= growth:
print (number)
number += 1
return (number)

diff = 100 #represents the limit of each incrementation

print('lets start')
old_num = creeper(0, diff)
while True:
inp = str(input('Yy/Nn: '))
print(inp)
if inp == 'Y' or 'y':
new_num = creeper(old_num, diff)
old_num = new_num
else:
print(new_num)

break
input("Did we get to here? Press enter to exit then: ")


In particular I am asking about this section:



if inp == 'Y' or 'y':
new_num = creeper(old_num, diff)
old_num = new_num
else:

print(new_num)
break


It seems that python reads correctly what is the input but it doesn't go back to step 1. Actually it doesn't even get to step 3. I can't understand how this particular chunk of code works:



if inp == 'Y' or 'y':


I appreciate any response to my question.

Thanks!


Answer



I see at least two problems:



A. As many people have said in the comments, in order to work properly, the if statement must be written differently, e.g.:



if inp == 'y' or inp == 'Y'


or this way:




if inp in ('y', 'Y')


Check those links from the comments, for example: this post



The boolean value for 'y' is always True, thus the else statement will never be executed.







B. Second problem is in your else statement. You have to check against the old_num because the new_num might not be created yet (in case it is the first iteration).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...