if statement is not running even if condition is true - python

the if condition is not running even if the condition is true. On line 29 there's a function set_row and on line 31 there's a function set_col. On Line 58 there's an if statement which checks if guess_row1 is equals to set_row and guess_col1=set_col even the condition is true if statement does not run else always run
from random import randint
user1 = {
"name":input("Enter your name"),
"board":[]
}
user2 = {
"name":input("Enter your name"),
"board":[]
}
def set_board(user):
for x in range(5):
user["board"].append(["O"]*5)
def print_board(user):
for row in user["board"]:
print(" ".join(row))
print("")
print("Let's start")
print("")
set_board(user1)
set_board(user2)
print("This is {}'s board".format(user1["name"]))
print_board(user1)
print("")
print("This is {}'s board".format(user2["name"]))
print_board(user2)
def set_row(user1):
return randint(0, len(user1["board"])-1)
def set_col(user1):
return randint(0, len(user1["board"])-1)
print("")
print("Answer for {}".format(user1["name"]))
print(set_row(user1))
print(set_col(user1))
print("")
def set_row2(user2):
return randint(0, len(user2["board"])-1)
def set_col2(user2):
return randint(0, len(user2["board"])-1)
print("Answer for {}".format(user2["name"]))
print(set_row2(user2))
print(set_col2(user2))
print("")
for turnu1 in range(3,0,-1):
print("turn's left for {} ".format(user1["name"]) + str(turnu1))
print("")
guess_row1 = int(input("Enter the row "))
guess_col1 = int(input("Enter the col "))
print("")
if guess_row1==set_row(user1) and guess_col1==set_col(user1):
print("your right")
else:
print("Wrong answer")

When you call and print the random numbers for user 2:
print(set_row2(user2))
print(set_col2(user2))
then those numbers are generated by randint() and never stored anywhere.
The calls for user 1 then will be new random numbers:
if guess_row1==set_row(user1) and guess_col1==set_col(user1):
and not correspond with the first set of calls. If you meant those to be equal, then store the random values you picked first:
user2_row = set_row2(user2)
user2_col = set_col2(user2)
so you can test against them later:
if guess_row1 == user2_row and guess_col1 == user2_col:

Related

Python Functions not being called. Only able to print the questions in my print statements

history = []
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
def main():
def summation():
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
first_num = str(input(":ype the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
print("The Previous result is: " + str(history()))
def exits():
print("Exiting...")
while True:
x = str(input("Type your option: "))
if x == "1" or x == "2" or x == "3" or x == "4":
break
if x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
else:
exits()
main()
The indentation of your while is wrong. It should be inside of your main function.
Try removing the main function and just let your script run the while loop.
Also break only during the input that you want to exit the loop. If nothing is after the loop, it exits the script; with your current logic, the while loop exits for every option, nothing is printed beyond your first line and your input prompt, then the main function gets ran, but nothing runs because the main function is actually empty (only defines other functions)
history = []
def summation():
global history
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
global history
first_num = str(input("Type the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
global history
print("The Previous result is: " + str(history))
def exits():
print("Exiting...")
while True:
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
x = str(input("Type your option: "))
if x == "4":
exits()
break
elif x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
Note: input() always returns a str type, so there's no reason to cast it

python array count each elements

I want a small program to count each part numbers enter by user.
here is so far I can do.
Is there a way I can export part numbers and their frequency to .csv file?
from collections import Counter
thislist = []
frequency = []
partnumber = ""
def mainmanu():
print ("1. Create List")
print ("2. Print list")
print ("3. Exit")
while True:
try:
selection = int (input("Enter Choice: ")
if selection ==1:
creatlist(thislist)
elif selection ==2:
counteach(thislist)
elif selection ==3:
break
except ValueError:
print ("invalid Choice. Enter 1-3")
def creatlist(thislist)
# while True:
partnumber = input ("Enter Part number: ")
if partnumber =="end":
print(thislist)
mainmanu()
break
thislist.append(partnumber)
def counteach(thislist)
Counter(thislist)
mainmanu()
mainmanu()
Welcome to the StackOverflow.
You are calling the mainmanu function inside another function which is called by mainmanu function. Instead what you should be doing is letting mainmanu calling all the other helper functions. Antoher thing, you can't call break in another function and expect where it is called to break.
The execution goes like this:
mainmanu is called, it calls creatlist, after it finishes execution it continues to execute the instructions where it is left from.
from collections import Counter
thislist = []
frequency = []
partnumber = ""
def mainmanu():
print ("1. Create List")
print ("2. Print list")
print ("3. Exit")
while True:
try:
selection = int (input("Enter Choice: ")
if selection ==1:
if creatlist(thislist): # line x
break
elif selection ==2:
counteach(thislist)
elif selection ==3:
break
except ValueError:
print ("invalid Choice. Enter 1-3")
def creatlist(thislist)
# while True:
partnumber = input ("Enter Part number: ")
if partnumber =="end":
print(thislist)
return True #this value will make the the condition to be true see line x
thislist.append(partnumber)
return false
def counteach(thislist)
Counter(thislist)
mainmanu()

TypeError: unsupported operand type(s) for divmod(): 'NoneType' and 'Int'

I am doing past coursework for practice, but I'm not sure what to do.
The task: create a game where the user has to guess a random 4 digit number(no repeated digits).
The problem: my code kind of works - like when you input a number with no repeating digits, it's fine, but when you enter, for example, 1223 I get the error:
TypeError: unsupported operand type(s) for divmod(): 'NoneType' and 'Int'
I have looked online and cannot find an answer. Any help would be greatly appreciated.
Thank you
Code below
import random
from collections import Counter
def rng():
num = []
i = 0
while i <=3:
rng = random.randrange(1,9)
if num.count(rng) == 0:
num.append(rng)
i+=1
return num
def menu():
userGuesses = 1
num = rng()#sort out a new num every time
print(num)
x = True
while x == True:
userExit = input("Would you like to exit(yes or no)")
if userExit == "yes":
print("Exiting...")
exit()
elif userExit == "no":
x = False
over = game(num)
while over !=True:
over = game(num)
userGuesses+=1
print("Congratulations you got it right, and it only took you ", userGuesses, " guesses!")
menu()
else:
print("Invalid entry")
def userInput():
userNum = int(input("Please enter a four digit number(no repeated digits)"))
if(userNum > 1000 or userNum < 9999):
print("...")
c = Counter(str(userNum))
if any(value > 1 for value in c.values()):
print ("Your number has repeating digits, please change it.")
else:
x = False
return userNum
else:
print("Invalid entry")
def convertToArray(userNum):
userArray = []
while userNum != 0:
userNum, x = divmod(userNum, 10)
userArray.append(int(x))
userArray.reverse()
print(userArray)
return userArray
def check(userArray, num):
i = 0
bulls = 0
cows = 0
while i<=3:
if num[i] == userArray[i]:
bulls +=1
elif int(userArray[i] in num):
cows +=1
i+=1
print("Bulls:")
print(bulls)
print("Cows:")
print(cows)
if bulls == 4:
return True
else:
return False
def game(num):
userNum = userInput()
userArray = convertToArray(userNum)
if check(userArray, num) == True:
return True
else:
return False
#Main-----------------------------------------------------------------
print("""Hello and welcome to the game \"Cows and Bulls\":
*In this game you enter a 4 digit number
*We compare it to a random number
*If you get the right number in the right 'place' then you get one bull
*If you get the right number in the wrong 'place then you get one cow'
*The game is over when you get 4 bulls, or all the numbers in the right place""")
menu()
Yes - your function doesn't actually return anything because of the print statements, hence an implicit None is returned - but there's another solution you can use.
Take advantage of the fact that userInput will return None if the input isn't valid. Have a condition just before userArray = convertToArray(userNum) to check if userNum is None:
def game(num):
userNum = userInput()
if userNum is None:
# Bad input was given
return False
userArray = convertToArray(userNum)
if check(userArray, num) == True:
return True
else:
return False
def userInput():
userNum = int(input("Please enter a four digit number(no repeated digits)"))
if(userNum > 1000 or userNum < 9999):
print("...")
c = Counter(str(userNum))
if any(value > 1 for value in c.values()):
print ("Your number has repeating digits, please change it.")
else:
x = False
return userNum
else:
print("Invalid entry")
when userNum is repeated, you return nothing. you should return something and pass it to convertToArray

4 Digit Guessing Game Python

Im trying to make a 4 digit numbers guessing game in Python 3. It should work by generating a random number between 1000 and 10000 (random.range(1000,10000)) and then by the user guessing and it should return after each guess how many numbers you have got right. My code doesn't exactly work and, I can't think why it doesn't so help is appreciated.
import random as r
guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)
correct = 0
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(3):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
while guessing:
Player()
There are several issues in your code:
You're creating a new instance of Player class inside the main loop. It works, but it's not the best approach IMHO.
You're using guessing to stop the main loop. In Python, all variables are local by default. In order to reference a global variable, you must identify it as global:
def evaluate(self, correct):
**global guessing**
for n in range(3):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
However using global variables could lead to a messy code.
range provides values from the minimum (0 by default) inclusive and the maximum exclusive. That range(3) will provide the numbers 0, 1 and 2 (3 numbers total), which is not what you want.
Since you're using a class, I'd try the following:
Create a single instance of Player
Create a new method called guess
Change the evaluate method to return how many digits the player guessed right
Create a new method called run, that will call guess and evaluate
import random as r
class Player():
def __init__(self):
self.real_ans = str(r.randrange(1000,100000,2))
def guess(self):
self.player_guess = raw_input("Enter a guess")
def evaluate(self):
correct = 0
for n in range(4):
if self.player_guess[n] == self.real_ans[n]:
correct += 1
return correct
def run(self):
while True:
self.guess()
correct = self.evaluate()
if not correct == 4:
print(str(correct)," was correct")
else:
print("You guessed it! ")
break
Player().run()
#Digit Guessing Game by Deniz
#python 3.5.1 - Please note that from Python version 2.7 "Tkinter" has been renamed tkinter, with a lowercase "t".
import tkinter
import random
computer_guess = random.randint(1,10)
def check():
user_guess = int(txt_guess.get())
if user_guess < computer_guess:
msg = "Higher!"
elif user_guess > computer_guess:
msg = "Lower!"
elif user_guess == computer_guess:
msg = "Correct!"
else:
msg = "Houston we have a problem!..."
lbl_result["text"] = msg
txt_guess.delete(0, 5)
def reset():
global computer_guess
computer_guess = random.randint(1,10)
lbl_result["text"] = "Game reset. Guess again!"
root = tkinter.Tk()
root.configure(bg="white")
root.title("Guess the correct number!")
root.geometry("280x75")
lbl_title = tkinter.Label(root, text="Welcome to Deniz's guessing Game!", bg="White")
lbl_title.pack()
lbl_result = tkinter.Label(root, text="Good Luck!", bg="White")
lbl_result.pack()
btn_check = tkinter.Button(root, text="Check", fg="blue", bg="White", command=check)
btn_check.pack(side="left")
btn_reset = tkinter.Button(root, text="Reset", fg="red", bg="White", command=reset)
btn_reset.pack(side="right")
txt_guess = tkinter.Entry(root, width=7)
txt_guess.pack()
root.mainloop()
root.destroy()
After reading your comments, I think what you need is this:
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
else:
print(str(correct)," was correct")
correct = 0
break
if correct == 4:
print("You guessed it! ")
guessing = False
You can integrate it along with #Robson's answer to end the loop.
Use range(4), range(3) has the values [0, 1, 2] so 3 is missing:
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
The global guessing is not available inside the class method, so the loop never ends after guessing it right.
And working but ugly solution would be:
print("You guessed it! ")
global guessing
guessing = False
Here is a non infinite loop version without a class. I assumed you wanted to input one number at a time? If not, that could be changed.
Also, the 2 on the end of the randrange only included even numbers, so that wasn't necessary
import random as r
debug = True
real_ans = str(r.randrange(1000, 10000))
if debug:
print(real_ans)
correct = 0
for i in range(len(real_ans)):
player_guess = input("Enter a guess: ")
if str(player_guess) == real_ans[i]:
correct += 1
if correct == 4:
print('You guessed it!')
correct = 0
else:
print('Sorry!', real_ans, 'was correct')
Sample run (Correct)
9692
Enter a guess: 9
Enter a guess: 6
Enter a guess: 9
Enter a guess: 2
You guessed it!
Sample run (Incorrect)
4667
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Sorry! 4667 was correct
import random
from Tools.scripts.treesync import raw_input
x= random.randint(1000,9999)
num=0
while num < 1000 or num > 9999:
num = int(raw_input("Please enter a 4 digit number: "))
if num < 1000 or num > 9999:
print("///wrong input////")
print("system generated number is ",x)
print("The number you entered is ",num)
if num == x:
print("Congrats you win")
else:
rabbit=0
tortose=0
unum = str(num)
snum = str(x)
c1=0enter code here
for i in unum:
c1=c1+1
c2 = 0
for j in snum:
c2=c2+1
if(i==j):
if(c1==c2):
rabbit=1
else:
tortose=1
if rabbit==1:
print("you got rabbit")
elif rabbit==0 and tortose==1:
print("you got tortose")
else:
print("Bad Luck you dont have any match")
enter code here
what i did was just change n from n in range(3) to n in range(4) in line 14
import random as r
guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)
correct = 0
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
while guessing:
Player()

How to use function in another function? Python

I am trying to make a game and I am really stuck. The problem is that I cant figur out how to use object oriented programming correctly. The program should launch gameboard function
everytime when the number doesnt equal to arv. It should return the new board with one "O"
less.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
def gameboard(self):
self.__board = ["O","O","O","O","O"]
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
arv = input()
self.arv__ = arv
while 5 > x:
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
return gameboard()
print(self.board())
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()
Using object-oriented programming when you only ever need one instance of the object tends to overcomplicate the program. I suggest having only one main function.
Nevertheless, I fixed your program. Try to find the changes yourself because I am too lazy to explain them, sorry.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
self.__board = ["O","O","O","O","O"]
def gameboard(self):
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
while 5 > x:
arv = input()
self.arv__ = arv
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
self.gameboard()
print(self.__board)
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()
Here is a version of your program that avoids OO and is much more simplified:
from random import randint
lives = 5
print("Guess a number from 1 to 20")
number = randint(1, 20)
while (lives > 1 and number != int(input())):
print("incorrect")
print("lives: " + "O" * lives)
lives -= 1
if lives == 0:
print("The number was actually " + str(number))
else:
print("You were right")

Categories