Mastermind Python with String.split() - python

How can you make this program make the user input 5 digits at once, instead of asking separate numbers each time? I know I have to use string.split() but where would I place the code and execute the code.
Heading
from random import randint
n1 = randint(1,9)
n2 = randint(1,9)
n3 = randint(1,9)
n4 = randint(1,9)
c = 1
while True:
print (n1,n2,n3,n4)
guess1 = input("guess the first number")
guess2 = input("guess the second number")
guess3 = input("guess the third number")
guess4 = input("guess the fourth number")
guess1 = int(guess1)
guess2 = int(guess2)
guess3 = int(guess3)
guess4 = int(guess4)
numberswrong = 0
if guess1 != n1:
numberswrong += 1
if guess2 != n2:
numberswrong += 1
if guess3 != n3:
numberswrong += 1
if guess4 != n4:
numberswrong += 1
if numberswrong == 0:
print('Well Done!')
print('It took you ' + str(c) + ' ries to guess the number!')
break
else:
print('You got ' + str(4-numberswrong) + ' numbers right.')
c += 1

You just have to split the numbers in a single input and convert them into integers using a list comprehension. You can also create your random_n using a similar method.
from random import randint
random_n = [randint(1,9) for i in range(4)]
c = 1
while True:
print(random_n)
user_input = [int(i) for i in input("guess the numbers: ").split()]
numberswrong = 0
if user_input[0] != random_n[0]:
numberswrong += 1
if user_input[1] != random_n[1]:
numberswrong += 1
if user_input[2] != random_n[2]:
numberswrong += 1
if user_input[3] != random_n[3]:
numberswrong += 1
if numberswrong == 0:
print('Well Done!')
print('It took you ' + str(c) + ' tries to guess the number!')
break
else:
print('You got ' + str(4-numberswrong) + ' numbers right.')
c += 1
if c > 10:
print('More than 10 failed attempts. End.')
break
>>
[3, 9, 1, 6]
guess the numbers: 1 2 1 6
You got 2 numbers right.
[3, 9, 1, 6]
guess the numbers: 3 9 1 6
Well Done!
It took you 2 tries to guess the number!
Edited: Added break if attempts more than 10, in this case when your counter c is more than 10.

You can try using raw_input:
Guesses= raw_input("Guess 5 numbers (separated by comma)")
Guess_list= Guesses.split(",")

Related

print statement only when the condition is CONSECUTIVELY met 3 times in a row

I'm currently making a guessing game where user can get a congrats statement if they guess correctly 3 times in a row or a hint statement if they guesses incorrectly 3 times in a row. If user makes two correct guesses and one incorrect guess the count will reset and vice versa for incorrect guesses. the goal is for the right/wrong guess to be 3 times in a row for the statement to print
Here is what I have
count = 0
rightGuess = 0
wrongGuess = 0
die1 = random.randint(1,6)
guess = int(input('Enter guess: '))
if guess == die1:
rightGuess += 1
print('Good job')
if rightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
wrongGuess += 1
print('Uh oh wrong answer')
if wrongGuess == 3:
print("Hint: issa number :)")
This works but it displays the text whenever the user reaches 3 wrong or right guesses even if it's not in a row. Please help
You can reset the rightGuess variable using rightGuess = 0 when you add 1 to the wrongGuess variable.
You just have to reset the opposite variable to 0 when incrementing either of them.
count = 0
consecutiveRightGuess = 0
consecutiveWrongGuess = 0
die1 = random.randint(1, 6)
guess = int(input('Enter guess: '))
if guess == die1:
consecutiveWrongGuess = 0
consecutiveRightGuess += 1
print('Good job')
if consecutiveRightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
consecutiveRightGuess = 0
consecutiveWrongGuess += 1
print('Uh oh wrong answer')
if consecutiveWrongGuess == 3:
print("Hint: issa number :)")
You could also do it like this only using one variable for counting guesses:
import random
count = 0
while True:
die1 = random.randint(1,6)
guess = int(input("Enter guess: "))
if guess == die1:
count = count + 1 if count >= 0 else 1
print('Good job')
if guess != die1:
print('Uh oh wrong answer')
count = count - 1 if count <= 0 else -1
if count == 3:
print('You guessed three times in a row!')
break
if count == -3:
print("Hint: issa number :)")
break

Lucky Number counting

I'm trying to make a lucky number counter where if there is a number containing either a 6 or an 8 between the two inputs the number is lucky, but if there's both a 6 and an 8 the number is unlucky. I'm having an issue where it's double-counting numbers, like 66, 88, etc., and not calling unlucky numbers like 68, 86, etc. Please help fast :\
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
for j in range(len(i)):
if i[j] == '6' or i[j] == '8':
count += 1
print(count)
Try this:
import sys
temp1 = ""
while len(temp1) != 2:
temp1 = input("Enter 2 digits: ")
try:
temp2 = int(temp1)
except ValueError:
print("You did not enter valid input")
sys.exit(1)
lucky = False
if "6" in temp1:
lucky = True
if "8" in temp1:
lucky = True
if ("6" in temp1) and ("8" in temp1):
lucky = False
print("Lucky number: "+str(lucky))
Something like this, probably:
number = ''
while len(number) != 2 or any(ch not in '0123456789' for ch in number):
number = input('Enter a 2-digit positive integer:')
print(f'{number} is {"lucky" if ("6" in number) != ("8" in number) else "not lucky"}')
# or, if you meant to say "exactly one 6 or 8":
print(f'{number} is {"lucky" if len([ch for ch in number if ch in "68"]) == 1 else "not lucky"}')
You could try using the count() method for Strings:
numbers = input().split(' ')
count = 0
for num in numbers:
if num.count('6') > 0:
if num.count('8') > 0:
continue
else:
count += 1
elif num.count('8') > 0:
count += 1
print(count)
this, while not as elegant or efficient, seems to be the correct code for the implied question
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
if ('6' in i and '8' in i):
continue
if i.count('6') > 0 or i.count('8') > 0:
count += 1
print(count)

Counter in for loop always prints 0

I need to check if a number is Lychrel number and if not to print the number of times the loop did until it got to the palindrome, for some reason it always print 0
num = input('please enter your number ')
num = int(num)
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
update: thanks to Vova the code is now working.
fixed code:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
It will print 0 each time when you type 1 numeric number(0..9)
When you type more than 1 numeric not mirror number for example 2,3,4 etc(10,234 etc), it will print 1
Moreover it will never print True, coz you exit() it in if statement
Try to input 23, it will print 1:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')

conditions are met, but program not breaking out of while loop

The program isn't breaking out of the while loop even when either "exit" or num is inputted. At the bottom of the function, I tried checking with guess == num, and that returns true. The code outside of the function at the very bottom is the basic structure of this function and that one works properly. Would the problem for not breaking out of the while loop happen to have anything to do with the two for loops in the function? Thanks.
def cowsAndBulls():
guess = ''
num = str(random.randint(1000, 9999))
while guess != num or guess != 'exit':
guess = input('Please enter a guess for a 4-digit number (\'exit\' to leave): ')
numL = [digit for digit in num]
guessL = [digit for digit in guess]
cow = 0
bull = 0
for digit in guessL:
if digit in numL and guessL.index(digit) == numL.index(digit):
cow = cow + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
for digit in guessL:
if digit in numL and guessL.index(digit) != numL.index(digit):
bull = bull + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
print(num)
print('Number of cows: ' + str(cow))
print('Number of bulls: ' + str(bull))
print(guess == num)
cowsAndBulls()
guess = ''
num = str(random.randint(0,5))
while guess != num:
guess = input()
print(num)
The reason it doesn't end is because unless both of them are false, the while loop is satisfied. This line here is where your troubles are from:
while guess != num or guess != 'exit':
If guess == 'exit', this is what happens:
while False or True:
The loop will keep running because False or True returns True.
To fix this, I would use a single variable to keep the game running and make it false when you want to end the game.
while running:
Then inside the loop, if guess == 'exit' or num then set running to False and the program will end.
import random
def cowsAndBulls():
guess = ''
num = str(random.randint(1000, 9999))
while guess != num and guess != 'exit':
guess = input('Please enter a guess for a 4-digit number (\'exit\' to leave): ')
numL = [digit for digit in num]
guessL = [digit for digit in guess]
cow = 0
bull = 0
for digit in guessL:
if digit in numL and guessL.index(digit) == numL.index(digit):
cow = cow + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
for digit in guessL:
if digit in numL and guessL.index(digit) != numL.index(digit):
bull = bull + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
print(num)
print('Number of cows: ' + str(cow))
print('Number of bulls: ' + str(bull))
print(guess == num)
cowsAndBulls()
Change your or to an and.
I was playing around with your code and I found the error, Change your while loop from and or to an and
while guess != num or guess != 'exit':
to
while guess != num and guess != 'exit':
will make the loop stop once you type exit.
Good luck!

Prime number(Python 3)

My goal is to build a programm, that says is a number prime or not.
A positive whole number n > 2 is prime if no number between 2 and sqrt(n)
divides n.
Here is my code:
import math
def main():
print("Prime number or not")
try:
N = -1
while N<2:
print("Error!Enter numbers greater than two")
N = int(input("Enter the right number:"))
values = list(range(2,round(math.sqrt(N))))
for i in values:
if i%N !=0:
continue
x = print("The number is not prime")
elif i%N ==0:
break
x = print("The number is NOT prime")
print(x)
except ValueError:
print("Error!Print correct number")
except NameError:
print("Error!Print the numbers")
main()
But is shows a syntax error in line
elif i%N ==0:
Please, give me some advice how to correct this error and about the code in general. I am new in learning Python, so any help and critic will be good!
Thanks.
If you wanted this to be your whole programme, here is my solution:
# Get num
num = input('Input a whole number: ')
# Is num valid
try:
num = int(num)
if num < 1 or num > 1000000000000:
print('Your field cannot be greater than one quantillion or less than one.')
else:
# Is num 2 or 5, if yes, prime.
if num != 2 and num != 5:
# Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
lastNum = str(num)[-1]
if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
print('Your number is composite.')
if lastNum == '5':
print(str(num) + ' is divisible by 5.')
else:
print(str(num) + ' is divisible by 2.')
else:
# List multiples of 3 less than 123, call it multiplesOf3.
multiplesOf3 = []
appendMultiple = 0
for i in range(40):
appendMultiple += 3
multiplesOf3.append(appendMultiple)
# Get sum of all numbers in num, name is sumOfNum
sumOfNum = 0
numStr = str(num)
for i in range(len(numStr)):
sumOfNum += int(numStr[i])
# Is sumOfNum in multiplesOf3?
numMultipleOf3 = sumOfNum in multiplesOf3
if numMultipleOf3 == True:
print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
else:
print('Your number is prime.')
else:
print('Your number is prime')
except:
print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
But if you wanted this to be just a function, here is my solution (Make sure you put in a parameter, it requires 1 argument; put in your number.)
def isPrime(num):
try:
num = int(num)
if num < 1 or num > 1000000000000:
print('Your field cannot be greater than one quantillion or less than one.')
else:
# Is num 2 or 5, if yes, prime.
if num != 2 and num != 5:
# Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
lastNum = str(num)[-1]
if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
print('Your number is composite.')
if lastNum == '5':
print(str(num) + ' is divisible by 5.')
else:
print(str(num) + ' is divisible by 2.')
else:
# List multiples of 3 less than 123, call it multiplesOf3.
multiplesOf3 = []
appendMultiple = 0
for i in range(40):
appendMultiple += 3
multiplesOf3.append(appendMultiple)
# Get sum of all numbers in num, name is sumOfNum
sumOfNum = 0
numStr = str(num)
for i in range(len(numStr)):
sumOfNum += int(numStr[i])
# Is sumOfNum in multiplesOf3?
numMultipleOf3 = sumOfNum in multiplesOf3
if numMultipleOf3 == True:
print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
else:
print('Your number is prime.')
else:
print('Your number is prime')
except:
print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
Another way,
def isprime(n):
if min(n//2,n//3,n//5) == 1:
return True
elif min(n%2,n%3,n%5) == 0:
return False
return True
This is SO much shorter!
assuming that the indentation on the question is correct NOW, the problem is that your elif block doesn't have an if parent. It's also indented wrong, which even if you fix the first error will throw an IndentationError but that's almost beside the point.
for i in values:
if i%N !=0:
continue
x = print("The number is not prime") # huh? you've left the `if` block
elif i%N ==0: # under-indented
break

Categories