Why does my while loop repeat infinitely in Python 3? I'm trying to create a revamped riddle program and have run into 2 issues. My first is the while loop is running infinitely, and whatever the selected riddle is it's infinitely repeating. My program is supposed to create an empty list, and put 5 random numbers in it, then take that list and check if the length of it is less than 5. If it is the main program runs. I've already tried to take the integer version of the length of the list. (I'm new to programming and 12 so the answer is probably simple.) Here's my code :
import sys, random
print('Welcome to Random Riddles!')
print('This is a list of hard randomized riddles!')
print('Please type either (q)uit, or (s)tart to start this quiz or after each riddle')
Choices = input()
randRiddle_list = []
randomRiddle = random.randint(1,5)
for i in range(5) :
randomRiddle = random.randint(1,5)
randRiddle_list.append(randomRiddle)
while int(len(randRiddle_list)) <= 5 :
if randomRiddle == 1 :
if Choices == 's' :
print('Okay then, what is so fragile that saying its name breaks it?')
print('A: Silence, B: Light, C: Clothes, D: The Dark One')
elif Choices == 'q' :
sys.exit()
When you reach the following statement:
int(len(randRiddle_list)) <= 5
int(len(randRiddle_list)) is to the length of randRiddle_list. Each time the while loop re-evaluates this, the length is the same. So you need to edit the length of randRiddle_list with some command (del or pop) in order for the length to be <=5.
I think your main mistake is thinking that the while loop with your riddles is executing before the riddle list is full. What's happening is:
# After the user has entered a value, choices equals that value, and won't change
Choices = input()
randRiddle_list = []
# randomRiddle will equal one random number [1,5]
randomRiddle = random.randint(1,5)
for i in range(5) :
# You are adding that same random number to randRiddle_list 5 times
randRiddle_list.append(randomRiddle)
The code you provided doesn't ever change the length of randRiddle_list, because it's never edited after this point. Python doesn't go back here for the rest of the script.
Perhaps you would like to go over each riddle?
import sys
import random
print('Welcome to Random Riddles!')
print('This is a list of hard randomized riddles!')
print('Please type either (q)uit, or (s)tart to start this quiz or after each riddle')
Choices = input(">")
randRiddle_list = []
# This here is important, you add 5 random numbers.
# As random.randint(1, 5) gives a new random number each iteration of the loop
for i in range(5):
# Adds a random number 5 times
randRiddle_list.append(random.randint(1, 5))
for riddle in randRiddle_list:
if riddle == 1:
if Choices == 's':
print('Okay then, what is so fragile that saying its name breaks it?')
print('A: Silence, B: Light, C: Clothes, D: The Dark One')
# Ask the user for their input once again
Choice_riddle = input(">")
if Choice_riddle == "A":
print("Correct!")
else:
print("Wrong :(")
elif Choices == 'q':
sys.exit()
else:
# The random numbers in randRiddle_list are not 1, so if riddle == 1: didn't execute
print("You did not get riddle 1")
Related
in below code i have created function named cards_game in which it will give you random card which will be added to cards list . if we input "hit" then it will give you random no. which simultaneously added to the cards list then [ if you input "stay" then it will stop while loop and will check the sum and if the sum >= 21 then it will stop while loop and run next code ] <--- but this is problem , it repeats the same line in last 'else' condition. If you input hit it will ask for it again rather than proceeding..
sorry if i have elaborated my question badly ...but this my 1st time on this platform
please pardon me and guide me , i would be very grateful for you .
def cards_game():
cards = []
seed(1)
sequence= [i for i in range(10)]
print ("Now you will get to select 1 random card \n but to get that there is 1 code called \"hit\" \nAnd to not to pick card there will be code called \"stay\" ")
x = True
command = input("what would you like to do?\n>>> ")
while x :
if command == 'hit':
cards.append(sample(sequence,1))
elif command == 'stay':
"ok"
sum = 0
for i in cards:
sum = sum + i
if sum >= 21:
x = False
else:
print ("too bad!\n I think you are anout to spend your \nWhole life playing with me \nHAHHHAHHAHAHAAAAAAAAAAHAHAHAAHHAAAA")
else:
print("Bad command")
cards_game()
Taking input one time is one of the issue, include it in your while loop,
....
while x :
command = input("what would you like to do?\n>>> ")
if command == 'hit':
....
You don't have to make sequence list, simply use randint() funciton
import random
....
if command == 'hit':
cards.append(random.randint(1,10))
....
The problem is that you only ask the player once what move to do. The command input should be in the loop.
from random import *
def cards_game():
cards = []
seed(1)
sequence= [i for i in range(10)]
print ("Now you will get to select 1 random card \n but to get that there is 1 code called \"hit\" \nAnd to not to pick card there will be code called \"stay\" ")
x = True
while x :
command = input("what would you like to do?\n>>> ")
if command == 'hit':
cards.append(sample(sequence,1))
elif command == 'stay':
"ok"
som = 0
for i in cards:
som = som + i
if som >= 21:
x = False
else:
print ("too bad!\n I think you are anout to spend your \nWhole life playing with me \nHAHHHAHHAHAHAAAAAAAAAAHAHAHAAHHAAAA")
else:
print("Bad command")
cards_game()
Your code still doesn't compile, because the elements in cards are a list, since sample returns a list. I would advise you to replace it by choice, in random module too.
cards.append(choice(sequence))
EDIT: Thanks for each very detailed explanations for the solutions, this community is golden for someone trying to learn coding!! #DYZ, #Rob
I'm a newbie in programming, and I'm trying to make a simple lotto guesses script in Python 3.
The user inputs how many guesses they need, and the program should run the function that many times.
But instead my code prints the same results that many times. Can you help me with this?
I'm pasting my code below, alternatively I guess you can run it directly from here : https://repl.it/#AEE/PersonalLottoEn
from random import randint
def loto(limit):
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess
guess = [] #Need to create an empty list 1st
#User input to select which type of lotto (6/49 or 6/54)
while True:
choice = int(input("""Please enter your choice:
For Lotto A enter "1"
For Lotto B enter "2"
------>"""))
if choice == 1:
lim = 49 #6/49
break
elif choice == 2:
lim = 54 #6/54
break
else:
print("\n1 or 2 please!\n")
times = int(input("\nHow many guesses do you need?"))
print("\nYour lucky numbers are:\n")
for i in range(times):
result = str(sorted(loto(lim)))
print(result.strip("[]"))
Your loto function is operating on a global variable, guess. Global variables maintain their values, even across function calls. The first time loto() is called, guess is []. But the second time it is called, it still has the 6 values from the first call, so your while loop isn't executed.
A solution is to make the guess variable local to the loto() function.
Try this:
def loto(limit):
guess = [] #Need to create an empty list 1st
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess
My task is to produce a word game.
The code is rather simple and is defined as follows( ignore the undefined helper function, which will not appear for the sake of brevity):
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
* If the user inputs 'r', let the user play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, tell them their input was invalid.
2) When done playing the hand, repeat from step 1
"""
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
n=7
previous_hand={}
hand=dealHand(n)
while choice!= False:
previous_hand=hand.copy()
if choice=='n':
playHand(hand, wordList, n)
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
elif choice=='r':
if len(previous_hand)==0:
print 'You have not played a hand yet. Please play a new hand first!'
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
else:
playHand(previous_hand, wordList,n)
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
elif choice=='e':
break
else:
print 'Invalid command.'
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
Everything seems to be working fine except that 'r' bit. The main trick of this game is that a player can choose to replay a previous hand by inputting 'r'. Say player started a game, played one hand and then want to repeat exactly same hand (all the letters dealt are the same as previously dealt), and the game allows him/her to do so if a player input 'r'.
Something like this:
Enter n to deal a new hand, r to replay the last hand, or e to end game: n
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: tot
"tot" earned 9 points. Total: 9 points
Current Hand: p z u t
Enter word, or a "." to indicate that you are finished: .
Goodbye! Total score: 9 points.
Enter n to deal a new hand, r to replay the last hand, or e to end game: r
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: top
"top" earned 15 points. Total: 15 points
However, my code is not working properly on that bit. Everything else is working fine except that. I do not understand how to make a copy of the initial hand, story and then reuse it if player choose 'r'.
This is from a looong time ago but should work for your M.I.T pset:
def playGame(wordList):
hand = None
legalIn = ['r','e','n']
while True:
user = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
if user not in legalIn:
print "Invalid word."
continue
#if user inputs r but there have been no hands played yet
elif user == 'r' and hand is None:
print "You have not played a hand yet. Please play a new hand first!"
elif user == 'n':
hand = dealHand(n)
playHand(hand,wordList,n)
elif user == 'e': # exit game if player inputs e.
break
else:
playHand(hand,wordList, n)
def playHand(hand, wordList, n):
# Keep track of the total score
totalScore = 0
c = calculateHandlen(hand)
# As long as there are still letters left in the hand:
while True:
if c == 0:
print "Run out of letters. Total score: {} points.".format(totalScore)
break
# Game is over if ran out of letters), so tell user the total score
# Display the hand
displayHand(hand)
# Ask user for input
word = raw_input("Enter word, or a '.' to indicate that you are finished: ") # Ask user for input
word = word.lower()
# If the input is a single period:
if word == '.':
# End the game (break out of the loop)
print "Goodbye! Total score: {} points.".format(totalScore)
break
# Otherwise (the input is not a single period):
# If the word is not valid:
elif not isValidWord(word,hand,wordList):
# Reject invalid word (print a message followed by a blank line)
print "Invalid word, please try again."
print
# Otherwise (the word is valid):
else:
hand = updateHand(hand,word)
# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
getWordScore(word,n)
totalScore += getWordScore(word,n)
print "{} earned {} points.: {}.".format(word,getWordScore(word,n),totalScore)
# Update the hand
c = calculateHandlen(hand)
Here's how I'd do it. There's only a single variable, hand, which is only modified if we're playing a new hand. If we're replaying the previous hand, we just leave it be (unless it's None, in that case we reject the input):
hand = None
while True:
choice = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if choice == "n": # deal a new hand
hand = dealHand(n)
elif choice == "r": # reuse the old hand, if there was one
if hand is None:
print 'You have not played a hand yet. Please play a new hand first!'
continue
elif choice == "e": # exit
break
else: # any other input
print 'Invalid command.'
continue
playHand(hand) # actually play here
first time writing here.. I am writing a "dice rolling" program in python but I am stuck because can't make it to generate each time a random number
this is what i have so far
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8)
print("Roll or Quit(r or q)")
now each time that I enter r it will generate the same number over and over again. I just want to change it each time.
I would like it to change the number each time please help
I asked my professor but this is what he told me.. "I guess you have to figure out" I mean i wish i could and i have gone through my notes over and over again but i don't have anything on how to do it :-/
by the way this is how it show me the program
COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r
1
r
1
r
1
r
1
I would like to post an image but it won't let me
I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU
Simply use:
import random
dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8) # this only gets called once, so r is always one value
print("Roll or Quit(r or q)")
Your code has quite a few errors in it. This will only work once, as it is not in a loop.
The improved code:
from random import randint
computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
print('COP 1000') # q and r are initialized to avoid user error, see the bottom description
print("Let's play a game of Chicken!")
player_input = '' # this has to be initialized for the loop
while player_input != 'q':
player_input = raw_input("Roll or quit ('r' or 'q')")
if player_input == 'r':
roll = randint(1, 8)
print('Your roll is ' + str(roll))
# Whatever other code you want
# I'm not sure how you are calculating computer/player score, so you can add that in here
The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q, it would stop the loop, and go to the next part of the program. See: Python Loops --- Tutorials Point
The picky part about Python 3 (assuming that's what you are using) is the lack of raw_input. With input, whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input 'q' or 'r'. However, a way to avoid an user error (if the player inputs simply q or r, without the quotes) is to initialize those variables with such values.
Not sure what type of dice has 8 numbers, I used 6.
One way to do it is to use shuffle.
import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])
Each time and it would randomly shuffle the list and take the first one.
This is a python dice roller
It asks for a d(int) and returns a random number between 1 and (d(int)).
It returns the dice without the d, and then prints the random number. It can do 2d6 etc. It breaks if you type q or quit.
import random
import string
import re
from random import randint
def code_gate_3(str1):
if str1.startswith("d") and three == int:
return True
else:
return False
def code_gate_1(str1):
if str1.startswith(one):
return True
else:
return False
def code_gate_2(str2):
pattern = ("[0-9]*[d][0-9]+")
vvhile_loop = re.compile(pattern)
result = vvhile_loop.match(str1)
if result:
print ("correct_formatting")
else:
print ("incorrect_formattiing")
while True:
str1 = input("What dice would you like to roll? (Enter a d)")
one, partition_two, three = str1.partition("d")
pattern = ("[0-9]*[d][0-9]+")
if str1 == "quit" or str1 == "q":
break
elif str1.startswith("d") and three.isdigit():
print (random.randint(1, int(three)))
print (code_gate_2(str1))
elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
for _ in range(int(one)):
print (random.randint(1, int(three)
print (code_gate_2(str1))
elif (str1.isdigit()) != False:
break
else:
print (code_gate_2(str1))
print ("Would you like to roll another dice?")
print ("If not, type 'q' or 'quit'.")
print ("EXITING>>>___")
This is one of the easiest answer.
import random
def rolling_dice():
min_value = 1
max_value = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
print("Rolling dices...")
print("The values are...")
print(random.randint(min_value, max_value))
print(random.randint(min_value, max_value))
roll_again = input("Roll the dices again? ")
rolling_dice()
So I'm creating a very basic python game and I need some help with this step I'm stuck at. The concept of the game is for the program to roll two die and add the sums. With that number they can choose a number available from the number list (1-10) to "peg". They keep going until all numbers are pegged or are out of options. Earlier in the program I created two functions that I'm using in this step. Those two are ask_number and valid_moves. Basically the ask number just asks them which number they want to peg but it doesn't actually peg the number yet. The valid_moves function just checks which numbers are still available for the player to select.
The game pretty much just looks like this halfway through:
------------------------------
(1)(2)(3)(4)(X)(6)(7)(X)(9)(X)
------------------------------
The X are the numbers that were already pegged. In this part of the game I need to figure out how to replace the number with "X". I have this so far but I know I am way off and I am having trouble with figuring out what to do. (pegholes is the name of the list and move is the number they picked in the ask_number function). Thanks so much!
PEGGED = "X"
def enter_peg(pegholes, roll, total):
ask_number()
if ask_number == valid_moves():
pegholes.append(ask_number(PEGGED))
return pegholes, move
I am really not sure how your game is supposed to work, but this may help you out:
#!/usr/bin/env python
import random
import sys
pegs = range(2, 11)
def roll_dice():
return random.randint(1, 5) + random.randint(1, 5)
while True:
roll = roll_dice()
print "You rolled %s" %roll
available_choices = set(p for p in pegs if p != 'X') - set(range(roll+1, 11))
if len(available_choices) == 0:
print "FAIL SAUCE"
sys.exit()
while True:
choice = raw_input("Choose a number %s: " % (", ".join(str(x) for x in sorted(list(available_choices)))))
if choice == 'q':
sys.exit()
choice = int(choice)
if choice in available_choices:
break
print "Nice try buddy... pick a number in range, that hasn't been picked"
pegs[choice - 2] = 'X'
print "".join("(%s)" % p for p in pegs)
if len([x for x in pegs if x == 'X']) == 9:
print "WINNER!"
sys.exit()
I'm not clear on what you're trying to do...
When you say "add the sum" you mean add them together to get a sum, right?
Standard dice add up to 12 and two dice can't total 1 so for a fair game you want to go from 2 - 12
You could try something like this:
import random
#set up list of numbers from 2 to 10
numlist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#create a roll dice function, producing the sum of two random integers 1-6
def rolldice():
return (random.randint(1,6) + random.randint(1,6))
#run the rolldice function
roll = rolldice()
#set up a loop for while the sum of the roll appears in the list
while roll in numlist:
print "Your rolled %s" %roll
print "Your list was", numlist
print "Replacing %s with X" %roll
numlist[numlist.index(roll)]="X"
print "Your new list is", numlist
raw_input("Press enter to roll again")
roll = rolldice()
#once a roll not in the list show up:
print "Your roll was %s" %roll
print "This is not in your list"
You could also add another if statement to ask the user if they want to try again if the roll is not on the list... and then go back through the while loop.
Keep trying -- I was new to all of this last summer and am still learning. Just keep trying different things... you will learn from your mistakes.