Python multiple number guessing game - python

I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the feedback to display as YYYY for 4 correct numbers guessed, YNNY for first and last number guessed etc. (you get the point). the code below keeps coming back saying IndexError: list index out of range.
from random import randint
guessesTaken = 0
randomNumber = []
for x in range(4):
tempNumber = randint(1, 9)
randomNumber.append(tempNumber)
Guess = []
Guess.append(list(input("Guess Number: ")))
print(randomNumber)
print(Guess)
if randomNumber[0] == Guess[0]:
print("Y")
elif randomNumber[1] == Guess[1]:
print("Y")
elif randomNumber[2] == Guess[2]:
print("Y")
elif randomNumber[3] == Guess[3]:
print("Y")
elif randomNumber[0] != Guess[0]:
print("N")
elif randomNumber[1] != Guess[1]:
print("N")
elif randomNumber[2] != Guess[2]:
print("N")
elif randomNumber[3] != Guess[3]:
print("N")

You need four guesses to match for random numbers, you can also shorted your code using a list comp:
from random import randint
guessesTaken = 0
randomNumber = []
Guess = []
for x in range(4):
tempNumber = str(randint(1, 9)) # compare string to string
randomNumber.append(tempNumber)
Guess.append(input("Guess Number: "))
print("".join(["Y" if a==b else "N" for a,b in zip(Guess,randomNumber)]))
You can also use enumerate to check elements at matching indexes:
print("".join(["Y" if randomNumber[ind]==ele else "N" for ind, ele in enumerate(Guess)]))
To give the user guesses in a loop:
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "N" for a,b in zip(guesses,randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)

Right now you're only asking the user for one guess, and appending the guess to the Guess list. So the Guess list has one element, but you're using Guess[1], Guess[2], etc., which of course results in the IndexError

I'll rearrange your code a bit, so it doesn't stray too far from what you've done.
from random import randint
guessesTaken = 0
randomNumbers = []
Guess = [] # Combine your guesses with your loop
for x in range(4):
tempNumber = randint(1, 9)
randomNumbers.append(tempNumber)
# This should be done four times too
# In Python 2, instead of this:
# Guess.append(input("Guess Number: "))
# do this:
Guess.append(int(raw_input("Guess Number: "))) # raw_input and pass to int
# in python 3, raw_input becomes input, so do this instead:
# Guess.append(int(input("Guess Number: ")))
print(randomNumbers)
print(Guess)
You can combine these in a loop to avoid the repetitive code:
if randomNumbers[0] == Guess[0]:
print("Y")
else:
print("N")
if randomNumbers[1] == Guess[1]:
print("Y")
else:
print("N")
if randomNumbers[2] == Guess[2]:
print("Y")
else:
print("N")
if randomNumbers[3] == Guess[3]:
print("Y")
else:
print("N")
Perhaps, to print your desired result e.g. YNNY, like this:
result = []
for index in range(4):
if randomNumbers[index] == Guess[index]:
result.append("Y")
else:
result.append("N")
print(''.join(result))
If you want terser code use Python's ternary operation:
result = []
for index in range(4):
result.append("Y" if randomNumbers[index] == Guess[index] else "N")
print(''.join(result))
Or use the fact that True == 1 and False == 0 as indexes:
result = []
for index in range(4):
result.append("NY"[randomNumbers[index] == Guess[index]])
print(''.join(result))

Related

How to loop back to the beginning in Python

I need a bit of help in finishing this code. I am stuck trying to figure out what's wrong with my code. I don't know how to loop back from the top using while loop. It also wont print the last bit. I got the prime numbers settled but I don't know how the looping back works. May you help me?
while True:
num=int(input("Enter a number:"))
no="n"
yes="y"
if num >=1:
for i in range(2, num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
x=str(input("If you want to continue press y, n if not:"))
if x==yes:
print()
#this part I don't know how to loop back to the start
elif x==no:
print("Okay")
#and also the loop won't stop and print the text up there^^^ when I choose n
put the if in the while loop only, and break out of the while loop if no
while True:
...
x=str(input("If you want to continue press y, n if not:"))
if x=="no":
print("Okay")
break
If you want this to repeat infinitely, your code structure might look like this:
while True: # The outer while loop, only ends when the player says "n"
while True:
# This is where you get the prime nums, paste the code for that here
if x == "n":
break # This method will only stop the loop if the input is "no", else it keeps looping forever
Or, more simply, you can do this in just one loop. The structure would be like this:
while True:
# Get if the num is prime, paste the code for that
if x == "n":
break
Possible solution if the following:
def is_prime(num):
if num <= 1:
return False
if num % 2 == 0:
return num == 2
d = 3
while d * d <= num and num % d != 0:
d += 2
return d * d > num
while True:
num=int(input("Enter a number: "))
if is_prime(num):
print(f'{num} is a prime number')
else:
print(f'{num} is not a prime number')
x = str(input("If you want to continue enter Y, or N if not: ")).lower()
if x == 'y':
print("let's start over...\n")
elif x == 'n':
print("Okay, see you")
break
Returns:
You can use code like this. In my opinion function more usefull for check prime numbers.
def is_prime(x):
for d in range(2, int(x**0.5)+1):
if x % d == 0:
return False
return x > 1
no, yes = "n", "y"
x = yes
while x == yes:
num=int(input("Enter a number:"))
if is_prime(num):
print(num,"is a prime number")
else:
print(num,"is not a prime number")
x = input("If you want to continue press y, n if not:")
print("Okay")

How to only show the final result after adding or multiplying all natural numbers

It has been a week since I started to self-study python and I tried making a program that adds or multiplies all natural numbers and the problem is I want to only show the final result of all the sum or product of all natural numbers. How do I do it?
repeat = 'y'
a=0
while repeat.lower() == 'y':
result = 0
choice = 0
i=0
product = 1
num = int(input("Enter the value of n: "))
if num < 1 or num > 100 :
print('must be from 1-100 only')
repeat = input("\nDo you want to try again?Y/N\n>>> ")
continue
print('1. Sum of all natural numbers')
print('2. Product of all numbers')
choice = int(input("Enter choice: "))
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('\nthank you')
break
The program prints you all the numbers because the print statement is in a while loop, so it gets executed with each run of the loop. Just move the print function out of the while.
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
You have two problems. First, your print statements that print the results need to be un-indented by one step, so they are not PART of loop, but execute AFTER the loop. Second, you need to initialize product = 1 after the if choice == 2:. As a side note, you don't need that final while loop. After you have exited the loop, just print('Thanks') and leave it at that.
So the end of the code is:
if choice == 1:
while num > 0 :
result += num
num -= 1
print(' ',result)
if choice == 2:
product = 1
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
print('thank you\n')
I presume you'll learn pretty quickly how to do those with a for loop instead of a while loop.

I'm trying to print the largest number from the inputs that the user gives, but it's printing the wrong number

Basically, I'm trying to build a code to get the largest number from the user's inputs. This is my 1st time using a for loop and I'm pretty new to python. This is my code:
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max = arr[0]
#Using for loop for 1st time to check for largest number
for i in range(1, n):
if arr[i] > max:
max = arr[i]
#Returning max's value using return
return max
while session_live:
print("Tell us a number")
num = int(input())
numbers.insert(a, num)
a += 1
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
pass
elif confirm == "N":
session_live = False
#Now I'm running the function
arr = numbers
n = len(arr)
ans = largest_num(arr, n)
print("Largest number is", ans)
else:
print(":/")
session_live = False
When I try running my code this is what happens:
Tell us a number
9
Continue? (Y/N)
Y
Tell us a number
8
Continue? (Y/N)
Y
Tell us a number
10
Continue? (Y/N)
N
Largest number is 9
Any fixes?
The error in your largest_num function is that it returns in the first iteration -- hence it will only return the larger of the first two numbers.
Using the builtin max() function makes life quite a bit easier; any time you reimplement a function that already exists, you're creating work for yourself and (as you've just discovered) it's another place for bugs to creep into your program.
Here's the same program using max() instead of largest_num(), and removing a few unnecessary variables:
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
continue
if confirm == "N":
print(f"Largest number is {max(numbers)}")
else:
print(":/")
break
So, first things first,
the use of max can be avoided, as it is a reserved keyword in python
And coming to your fix, you are comparing it with the value only once in the loop, and you are returning the number, the indentation is the key here. You will have to wait for the loop to complete its job then return the value.
There are many inbuilt methods to do the job, Here is your implementation (a bit modified)
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max_number = arr[0]
#Using for loop for 1st time to check for largest number
for i in range(1, n):
if arr[i] > max_number:
max_number = arr[i]
# --- The indentation matters
#Returning max's value using return
return max_number
while session_live:
print("Tell us a number")
num = int(input())
numbers.insert(a, num)
a += 1
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
pass
elif confirm == "N":
session_live = False
#Now I'm running the function
arr = numbers
n = len(arr)
ans = largest_num(arr, n)
print("Largest number is", ans)
else:
print(":/")
session_live = False
I made it without using the built-in function 'max'.
It is a way to update the 'maxNum' variable with the largest number by comparing through the for statement.
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
continue
if confirm == "N":
maxNum = numbers[0]
for i in numbers:
if i > maxNum:
maxNum = i
print("Largest number is", maxNum)
else:
print(":/")
break

Check if condition matches in python

Having trouble figuring out my list comprehension in python. I have 3 conditions that I'm looking for, and I know how to do two of them, but one of the conditions doesn't seem to work right.
My conditions are:
If all the numbers in my list are the same and they are all a specific number, then add points
If all numbers in my list are the same but they do not equal a specific number then do something else
If numbers in list do not match, but they equal a specific number than do something else.
I have 1 working, and I know how to do number 3, but I can't get number 2 working properly. No matter what numbers I put into my list (rolls), this condition still matches True. Can someone please assist? Here is my current code:
def check_conditions(rolls, round_number):
"""
Check if number on rolled die matches one of three conditions
:param rolls:
:param round_number:
:return round:
"""
round_score = ROUND_TOTAL
rolls = str(rolls)
bunco = all(roll == ROUND_NUMBER for roll in rolls)
mini_bunco = all(roll == roll[0] and roll != ROUND_NUMBER for roll in rolls)
if bunco == True:
print("BUNCO!")
round_score += 20
elif mini_bunco == True:
print("MINI-BUNCO!")
round_score += 5
else:
pass
return round_score
OUTPUT:
Starting Round Number 1
You rolled: [2, 3, 3]
MINI-BUNCO!
Points this round: 5
Something like this should get you there...
rolls = [5,5,5,5,5,5]
specificNum = 6
if len(set(rolls)) == 1:
if rolls[0] != specificNum:
print 'Do something'
#imports
import random
#variables
Roll_1_return = False
Roll_2_return = False
round_score = ROUND_TOTAL
#assuming you only want to roll twice
def Rolls():
Roll_1 = random.randrange(1, 10)
Roll_2 = random.randrange(1, 10)
While True:
if Roll_1 == 3:
Roll_1_return = True
return Roll_1_return
break
else:
break
While True:
if Roll_2 == 7:
Roll_2_return = True
return Roll_2_return
break
else:
break
Rolls()
if Roll_1_return == True:
print('Roll 1 is correct!')
round_score + 25
else:
print('Roll 1 is incorrect..')
if Roll_2_return == True:
print('Roll 2 is correct!')
round_score + 25
else:
print('Roll 2 is incorrect..')
if round_score == 50:
print('You won $100!')
elif round_score == 25:
print('You won $50!')
else:
print('Too bad, you lost!')
If I understand correctly, this should give you what you need! If this is not what you wanted, plz do not downvote me! I tried my hardest to understand.

Python number game with changing feeback

User guesses four digit number and feedback needs to be 'F' if a number is correct but not in the right place, 'X' if the number is not in the number at all and if the digit is correct and in the right position it displays the digit. Code below shows my attempt but it is giving me the error: expected str instance, list found
from random import randint
def check_char(a, b): #Function making output display F, number and X depending on user input
if a == b:
return randomNumber #Number is displayed when correctly guessed
elif b == randomNumber:
return 'F' #F means number is somewhere in the randomNumber
elif b != randomNumber:
return 'X' #X means number is nowhere in the randomNumber
guessesTaken = 1
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
print(randomNumber)
while guessesTaken < 10:
guesses = list(input("Guess Number: ")) # create list of four digits
check = ''.join([check_char(int(a), int(b)) for a, b in zip(guesses, randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
if guessesTaken == 10:
print("You lose")
You will be replacing X with F if the user has guessed a number and it is in randomNumber at another position it will be replaced with an ``F:
from random import randint
guessesTaken = 1
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
def check_char(a, b): #Function making output display F, number and X depending on user input
if a == b:
return b #Number is displayed when correctly guessed
elif a in randomNumber and a != b: # if
return 'F'
elif a != b:
return 'X'
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = ''.join([check_char(a, b) for a, b in zip(guesses, randomNumber)])
if check.isdigit(): # if check is all digits, number is guessed
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
else:
print("You lose")
You don't need to cast as ints in check_char(a, b) as strings will compare just fine "1" == "1" is True
You are returning the list return randomNumber not the substring b so you get an error trying to join as it expects a string not a list, also b would never be equal to randomNumber .

Categories