Loop and validation in number guessing game - python

I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!

To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)

Related

How can I stop a program when the user wants to?

So I made a program which asks the user the amount of numbers he wants, which numbers he wants and creates a list. I now want to make it so that if the user puts in the number 0 the program will stop there and print the previous numbers he has put if it's possible (note: I want the 0 to not be printed only the previous numbers he entered). Because this is my first time posting I'm not sure what else information is needed other than what version of Python I'm using (which is 2.7). If there's more information that's needed just ask. Also if it's needed I'll write the code I have written down.
lst = []
x = int(input("Enter number of elements : "))
for i in range(0, x):
num = int(input())
lst.append(num)
print(lst)
Before lst.append(num)
if num == 0:
break
Add a if-else statement:
if num != 0:
lst.append(num)
else:
break

how can I reduce my code? A lot of it is repetitive

The code creates a random addition problem and spits out "Congratulations" if correct and "sorry...." if the inputted value is wrong. The while loop repeats this process until the user inserts "N" for the question "continue (Y/N):, at the same time it keeps track of how many questions have been answered, and which ones are correct. The code works fine, my problem is it has repetitive code. I was wondering if there is a way to shrink it.
**I appreciate everyone one's help and advice. I"m a noob that's just learning python **
import random
correct=0
count=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
A first start, would be eliminating the code before the while, by initializing the count variable (which keeps track of the turns), in zero, and allowing the while loop to run the first turn, we just need to have a variable like want_to_play and by default it's True, so the first time we'll be playing, and at the end of the game If I don't input Y or y it will asume I don't want to play any more and set the variable to false, that way I can have all the turns ran by the while loop.
and you'll be getting something like this.:
from random import sample
correct = 0
count = 0 # STartint in turn zero
want_to_play = True # Control Variable
while want_to_play:
count += 1
# First turn this is zero, and adds one.
[num1, num2] = sample(range(0, 101), 2)
# Just another way of getting two random numbers from 1 up to (including) 100.
# Printing could be done in one line.
print(format(num1, '5d') + '\n+' + format(num2, '4d'))
answer = int(input('= '))
# The comparison really doesn't really hurt if you do it this way.
if answer == num1 + num2:
print('Congraulations!')
correct += 1
else:
print('Sorry the correct answer is', sum)
# HERE you ask if you want to play again or not, using a one line if
# you decide.
want_to_play = (True if 'y' == input('Continue (Y/N).lower():')
else False)
else:
print('Your final score is',correct,'/',count)
By initializing the variable c as "Y", the condition is met and the loop can be executed:
import random
correct=0
count=1
c = "Y"
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
c = c.upper()
else:
print('Your final score is',correct,'/',count)
I also added the method upper() to the Y/N input so the user can also type it in lowercase
Try to move as much of the processing as possible into the loop. The first "paragraph" of your code was basically a duplicate of the main-loop. By creating the continuation variable c so that it drops straight into the loop, most of that first block could be removed.
import random
correct=0
count=0
c = 'Y'
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congratulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
The two formula printing statements can also be reduced to a single one:
print(format(num1,'4d'))
print('+',num2)
could be
print( format(num1,'4d') + '+', num2 )
The variable sum could be removed, but it does make the code self-documenting, which is a good thing.

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

breaking out of the loop?

I'm having some trouble with breaking out of these loops:
done = False
while not done:
while True:
print("Hello driver. You are travelling at 100km/h. Please enter the current time:")
starttime = input("")
try:
stime = int(starttime)
break
except ValueError:
print("Please enter a number!")
x = len(starttime)
while True:
if x < 4:
print("Your input time is smaller than 4-digits. Please enter a proper time.")
break
if x > 4:
print("Your input time is greater than 4-digits. Please enter a proper time.")
break
else:
break
It recognizes whether the number is < 4 or > 4 but even when the number inputted is 4-digits long it returns to the start of the program rather than continues to the next segment of code, which isn't here.
You obviously want to use the variable done as a flag. So you have to set it just before your last break (when you are done).
...
else:
done = 1
break
The reason it "returns to the beginning of the program" is because you've nested while loops inside a while loop. The break statement is very simple: it ends the (for or while) loop the program is currently executing. This has no bearing on anything outside the scope of that specific loop. Calling break inside your nested loop will inevitably end up at the same point.
If what you want is to end all execution within any particular block of code, regardless of how deeply you're nested (and what you're encountering is a symptom of the issues with deeply-nested code), you should move that code into a separate function. At that point you can use return to end the entire method.
Here's an example:
def breakNestedWhile():
while (True):
while (True):
print("This only prints once.")
return
All of this is secondary to the fact that there's no real reason for you to be doing things the way you are above - it's almost never a good idea to nest while loops, you have two while loops with the same condition, which seems pointless, and you've got a boolean flag, done, which you never bother to use. If you'd actually set done to True in your nested whiles, the parent while loop won't execute after you break.
input() can take an optional prompt string. I've tried to clean up the flow a bit here, I hope it's helpful as a reference.
x = 0
print("Hello driver. You are travelling at 100km/h.")
while x != 4:
starttime = input("Please enter the current time: ")
try:
stime = int(starttime)
x = len(starttime)
if x != 4:
print("You input ({}) digits, 4-digits are required. Please enter a proper time.".format(x))
except ValueError:
print("Please enter a number!")

Categories