Python while loop keeps repeating itself - python-3.x

Simple question but it is driving me nuts. why when I run this code does it just keep repeating itself? And my indentations are correct just had to space 4 times to post this for whatever reason.
High Scores
0 - Exit
1 - Show Scores
Source code:
scores = []
choice = None
while choice != "0":
print(
"""
High Scores
0 - Exit
1 - Show Scores
"""
)
choice = input("choice: ")
print()
if choice == "0":
print ("exiting")
elif choice == "1":
score = int(input("what score did you get?: "))
scores.append(score)
else:
print ("no")
input ("\n\nPress enter to exit")

This is because you are not using proper indentation. Please indent the code under the while loop that you want to execute while choice != 0
Further there is no mistake with comparison as #wookie919 wrongly indicated because you're taking a String as input and not an Int. You can however typecast your input as a string by wrapping it around an int() like int(input("Choice .. "))
Hope it helped.

It's because you are comparing an Integer to a String. Try entering "0" instead of just 0. Or modify your program to compare with 0 instead of "0".

Related

Adding sums in a loop while also using the def function

I am working on a function that sums up the amount of positive and negative numbers a user inputs. It has to be in a loop and has to have two functions(on for pos, one for neg) to return True or False. I have tried everything and am so lost and don't even know where to start anymore. This is what I have so far:
pos = 0
neg = 0
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
while num > -100 or num < 100:
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
if num > 100 or num < -100:
print("Please only enter integers between -100 to 100")
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
elif num == 0:
print("Here is your summary: ")
print("You entered: ", pos, "positives number(s) and", neg, "negative number(s)")
def if_positive(pos):
if num > 0:
pos = pos + 1
def if_negative(neg):
if num < 0:
neg = neg + 1
if_positive(pos)
if_negative(neg)
Every time I try something, I get one part correct and then the other wrong. Python for Everybody hasn't helped at all and I've done hours of research and nothing helps. Please help me. Every time I post a question on here it gets removed! I have no idea what I'm doing wrong, I am just trying to ask a simple question :( So I will try for the third time!
Lets do it as follow
Lets have while loop then if the num is zero just break it otherwise check the conditions
I have added two lists but if you just count how many numbers positive and negative then you don't need lists you can use integer count variables
postive_numbers =[]
negative_numbers =[]
while True:
num = int(input("Please enter a positive or negative number. Or 0 to quit\n Enter the number: "))
if num>100 or num < -100:
print("Please only enter integers between -100 to 100")
continue
if num == 0:
print("Here is your summary:\n ")
print("You entered: \npositives number(s) {} \nnegative number(s){} ".format(len(postive_numbers),len(negative_numbers)))
break
elif num< 0:
negative_numbers.append(num)
else:
postive_numbers.append(num)
If I had to guess, I'd say your questions are being removed because they sound like school assignments, and people tend to sour a little at the idea of people going to StackOverflow to have others do their homework for them. That said, it seems to me like you've put in a good-faith effort based on what you've already written, and there's nothing wrong with asking for help when you don't understand something after trying to figure it out yourself.
Try this:
def is_positive(number):
"""
This could be shortened to simply:
`return number > 0`
"""
if number > 0:
return True
else:
return False
def is_negative(number):
"""
Similarly, this could be shortened to:
`return number < 0`
"""
if number < 0:
return True
else:
return False
n_positive = 0
n_negative = 0
while True:
num_entered = int(input("Please enter a positive or negative number. Or 0 to quit"))
if not -100 < num_entered < 100:
print("Please only enter integers between -100 to 100")
elif is_positive(num_entered):
# this is a shortcut for `n_positive = n_positive + 1`
n_positive += 1
elif is_negative(num_entered):
n_negative += 1
else:
break
print("Here is your summary:")
# this is equivalent to what you had in your question, but uses "f-strings",
# which were implemented in Python 3.6 and are super convenient
print(f"You entered {n_positive} positive number(s) and {n_negative} negative number(s)")
A few extra notes you might find helpful:
if not -100 < num_entered < 100: is equivalent to if num > 100 or num < -100:, but just a cleaner way of writing it
while True is an idiom in Python that essentially means "keep looping forever until I break out of it or exit the program." From the code you had written, it seems like you want to keep allowing the user to input numbers until they enter "0 to quit". That's the condition upon which you want to break out of the loop.
"def" itself isn't a function -- def is a keyword that defines a function, which is a snippet of code that performs a single task that can be re-used later. You said your two functions needed to return True or False. In Python, the return keyword causes a function to exit and "return" the value specified.
This is why you're able to use those pre-defined functions directly in the the if and elif statements later. You can think of the way "if" works as taking the code between if and : and evaluating it. If it evaluates to True, then the block of code inside (i.e., indented under) the if statement is executed and any elif or else statements you may or may not have after that are skipped. Or, if it evaluates to False, then Python "moves on," and if you have an elif statement after the if, it repeats the same process there. Finally, if neither or if or elif blocks evaluate to True and you have an else block, that code is run.
This is a very long way of saying that in your case, the logical flow is: "if the number isn't between -100 and 100, remind the user of the acceptable range of values. Otherwise, if the number is_positive, add 1 to the running count of positive numbers entered. Or, if the number is_negative, add 1 to the count of negative numbers. Otherwise, the only remaining possibility is that the number is 0, so the user is finished entering numbers and we should break out of the loop and show them their summary.
Hope this helps! Feel free to comment with any other questions you have.

Set IF statment to check for specific characters, breaks while loop when using any character instead

I am new to python. I was making a guess the random number game, and I run into issues when having both int and str as inputs, I want the user to exit the program when pressing Q or q, while the game to check for numbers as well. After hours of googling and rewriting this is what I came up with:
#! Python3
import random
upper = 10
number = random.randint(1, upper)
print(number) #TODO: THIS LINE FOR TESTING ONLY
print("Guess a number between 1 and {}. Press Q to quit!".format(upper))
total_guesses = 0
guess = 0
while guess != number:
total_guesses += 1
guess = input()
if guess.isalpha():
if guess == "q" or "Q":
break
elif guess != "q" or "Q":
print("Please type in a valid guess.")
guess = 0
if guess.isnumeric():
guess = int(guess)
if guess == number:
print("Good job! You guessed the number in {} tries!.".format(total_guesses))
break
if guess < number:
print("Guess Higher!")
if guess > number:
print("Guess lower!")
else:
print("Valid inputs only")
guess = 0
This code ALMOST works as intended; issues I have now is that at line 13 and 14 the loop breaks every time when any letter is typed, even though I set the if statement to only check for Q or q, and I can't understand why this is doing it. Any help is appreciated!
if guess == 'q' or "Q":
The way this line is read by python is -
if guess == "q":
and also -
if "Q":
"Q" is a character, which means it's truthy. if "Q" returns True. Try:
if guess == "q" or guess == "Q":
if you feels that's too much, other options include -
if guess in ["Q", "q"]:
if guess.upper() == "Q":

Mastermind Python Using "ABCDEF"

Mastermind Game using "ABCEF"I dont know how to check whether it is partial correct. I have to use red to mean correct letter and position. I use white to mean correct letter.
import random
def play_one_round():
N_code=''.join(random.sample("ABCDEF",4))
print (N_code)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess= 1
while N_code != guess and count_guess < 10:
check(N_code,guess)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess=count_guess + 1
print("This is your",count_guess, "guess")
if guess==N_code:
print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order.
def check(N_code,guess):
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)]
for index, char in enumerate(guess):
if result[index] !='r':
if char in result:
result[result.index(char)]='w'
print(result)
def Master_m():
print("Welcome to Mastermind!\n")
print("Start by Choosing four letters")
play_one_round()
answer=input("Play Again? ")
if answer[0]=='y':
Master_m()
Master_m()
I wrote this ages ago but it will do the trick
import random
import itertools
def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
rules()
elif path == '2':
print('Great lets play some Mastermind!\n')
begingame()
start()
else:
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')
start()
def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')
start()
def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""
#generate a 4 digit number
num = random.sample(range(1,9), 4)
#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))
return roll
def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')
#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0
#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
try:
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
pass
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
pass
else:
print ( "Your choice is", choice)
#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]
#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]
#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)
#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0
#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')
#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])
print ('Oh Mastermind that was a good try! ')
#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)
#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed
#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)
# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses
collectScore.append(totalResults)
#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')
break
#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')
#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")
#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)
#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')
if __name__ == '__main__':
start()
When you are stuck, decompose into smaller chunks and test those. Focusing on check, you can check whether a guess letter exactly matches the code via its index and whether its in the code at all with in. Here is a self-contained example. Notice that I've pulled out everything except the problem at hand.
If this works for you, I suggest writing a self-contained example of your next problem, test it, and if you are still stuck, post that as a new question.
def check(N_code, guess):
print('code', N_code, 'guess', guess)
result = []
# enumerate gives you each letter and its index from 0
for index, letter in enumerate(guess):
if N_code[index] == letter:
# right letter in right position
vote = 'red'
elif letter in N_code:
# well, at least the letter is in the code
vote = 'white'
else:
# not even close
vote = 'black'
# add partial result
result.append('{} {}'.format(letter, vote))
# combine and print
print(', '.join(result))
check('ABCD', 'ABCD')
check('DEFA', 'ABCD')

Option to save output printed on screen as a text file (Python)

Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break

Python 3.5.1 Introduction to Python 2.1 Mark Clarkson - While Loop Issue

I'm working my way through this set of tutorials. In section 3.2a - While Loops the following code is supposed to loop until the user enters the target number (7) then display a congratulations message however regardless of what number is entered Python either gives a right answer or a wrong answer, even 7 will sometimes flag a wrong answer. I know there are other ways to perform this sort of task but I would like to get the code from the tutorial working.
targetNumber = 7
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
print("Wrong, try again ")
guess = input("Guess a number between 1 and 10 ")
print("Congratulations - that's right!")
You should convert the target numger to an string before comparison. Also, you should exclude the congratulations message from the loop. I would suggest :
targetNumber = str(7)
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
print("Wrong, try again ")
guess = input("Guess a number between 1 and 10 ")
print("Congratulations - that's right!")
The detail is that input returns a string and if you compare a string to an integer, it will always return false.
Python's input function (or raw_input in Python 2.x) returns a string entered by the user. targetNumber, on the other hand, is an integer. In the Python Interpreter, try:
>>> 7 == "7"
False
You need to cast the user's input to an integer first.
try:
guess = int(input("Please enter a number: "))
except ValueError:
print("That is not a valid number!")

Resources