Python using random within a loop - separated by user action - python

I'm new to coding and started with a python course now.
I was trying to work on a word bingo game but can't seem to make it work.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
list = bingo.split()
print
print "Okay, let's go! "
random.shuffle(list)
for choice in random.shuffle(list):
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
#for words in range(len(list)):
#user = raw_input()
#if user == "":
#print(random.sample(list, 1))
#raw_input("")
#else:
#print "That's the end of the game ^.^"
#break
If i use choice in random.shuffle(list) I get a NonType error
before I used a for loop with random.sample (seen in the ## parts at the end)
That worked except in each iteration the words were still repeated.
I tried to search for similar questions but they all either had numbers or more automatic loops.
I want it so the user enters words, then each time they press enter, a new word appears from the list without repetition.
I can't seem to figure out how to get that into a loop - any help?
I tried to use random.choice and random.sample but the words still kept repeating in a for loop.
Tried shuffle and had a nonType error

Two comments:
Don't use list for variable name, it is a keyword in Python for type list
random.shuffle(l) does operation in-place (i.e. after you called it, l will be shuffled). So, you just supply l into the loop. Hope this helps.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
l = bingo.split()
print
print "Okay, let's go! "
random.shuffle(l)
for choice in l:
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
P.S.
Why did you decide to use Python 2? If you are new to Python it can be better to work with Python 3. It is your decision to make. FYI, https://www.python.org/doc/sunset-python-2/#:~:text=We%20have%20decided%20that%20January,as%20soon%20as%20you%20can.

Related

Why does my while loop repeat infinitely in Python 3?

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")

Making a game like Mastermind in Python

I'm trying to make a game like Mastermind in Python but by using numbers [1-9] instead of colours. The game needs to be a little complex however and that is where I am struggling. I want to be able to randomly generate a password of 5 digits between [0-9] and make the user have 10 tries to get it right. If they guess a number correctly, I want to tell them where it is in their list and ask them to keep going as well. So far, I have this:
import random
random_password = [random.randint(0,9) for i in range (5)]
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess != random_password :
print ("Guess again ")
#Here I am trying to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
elif guess
else print ("Sorry, you lose :( ")
if guess == random_password :
print ("Congrats, you win! ")
Any help is appreciated overflow bros, I am lost. I know that I need it to access items from a list. Would using a function like append work?
EDIT: This is my new code. Sorta works however my output is now showing it is wrong even when I guess the number correctly. It wants me to input with '' and , to separate the list but I shouldn't have to have the user do that to make the game function.
import random
random_password = [str (random.randint(0,9)) for i in range (5)]
for counter in range (10):
guess = input(str ("Crack the Mastermind code ") )
if guess != random_password :
print ("Guess again ")
#Here I am tryin to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
for i in random_password:
if(i in guess):
print (i)
if guess == random_password :
print ("Congrats, you win! ")
else :
print ("Sorry, you lose :( the correct answer was.... ")
print (random_password)
One way to do it quickly is to create a small function that will check if any of your string answer (from input) match with any characters of the password list
Also I change the order of your condition statement to make it more clear and efficient.
Finally I change your random_password from LIST to STRING because then you will be able to do guess == random_password properly.
Hope it helps!
PS:
IF you use Python2.X you should change input to raw_input (to get string value) else if you use Python3.X just keep it this way
import random
def any_digits(guess,password):
for character in guess:
if character in password:
return True
return False
random_password = ''.join([str(elem) for elem in [random.randint(0,9) for i in range (5)]])
print(random_password)
print(type(random_password))
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess == random_password :
print ("Congrats you win! ")
elif any_digits(guess, random_password):
print ("Some numbers are correct! ")
else:
print ("Guess again ")
print("No more chances, you lose...")
print("The code was ", random_password)

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

Python program - Random word generator

Im trying to make a program where it will randomly print one of the two words it can chose from when you hit enter. Here are the question & the anwsers. Its meant to be from the card game 'Smoke or Fire / Higher or lower'
sof = raw_input("Smoke or Fire?: ")
print "SMOKE" or "FIRE"
horl = raw_input("Higher or Lower?: ")
print "HIGHER" or "LOWER"
IOO = raw_input ("Inside or Out?: ")
print "INSIDE" or "OUT"
horl = raw_input("Higher or Lower?: ")
print "HIGHER" or "LOWER"
sof = raw_input("Smoke or Fire?: ")
print "SMOKE" or "FIRE"
Can anyone help?!?
You can use random.choice to choose what you want to print, randomly.
It's as simple to use as print random.choice(['SMOKE', 'FIRE']).

How do I have python run (if statements) based on the users input.?

I am not doing anything particularly complicated I am simply messing with import random and having the user type roll to roll a six sided die. I have gotten this far.
import random
roll = random.randint(1,6)
input("Type roll to roll the dice!\n")
# This is where I have my issue pass this line I'm trying things out, unsuccessfully.
if (userInput) == (roll)
print("\n" + str(roll))
else:
input("\nPress enter to exit.")
I don't want the program to print the str(roll) if the use presses enter, I'd rather it exit the program if no input is given. So how do I write the code to do particular thing based of user input when using the if statement. If user input is 'roll" then print("str(roll))?
You need to capture the user input in a variable. Currently, the return value of input(…) is being thrown away. Instead, store it in userInput:
userInput = input("Type roll to roll the dice!\n")
The if requires a colon at the end in order to start the block:
if someCondition:
# ^
If you want to compare the user input against the string 'roll', then you need to specify that as a string, and not as a (non-existent) variable:
if userInput == 'roll':
You also don’t need parentheses around the values
In order to check for just an enter press, check against the empty string:
elif userInput == '':
print('User pressed enter without entering stuff')
You should roll inside the condition, not before, so you don’t generate a random number although it’s not requested.
So in total, it could look like this:
import random
userInput = input('Type roll to roll the dice!\n')
if userInput == 'roll':
roll = random.randint(1,6)
print('You rolled: ', roll)
elif userInput == '':
print('Exit')

Categories

Resources