If statements and how to shorten them? - python

I am writing a lottery program, for my class. I have looked on stackoverflow for an answer but all I have found have been to advanced. I was wondering if there is a way to shorten the if statements and have fewer of them.
import random
def lottery():
lottoNumber1 = random.randint(1,50)
print(lottoNumber1)
lottoNumber2 = random.randint(1,50)
print(lottoNumber2)
lottoNumber3 = random.randint(1,50)
print(lottoNumber3)
return lottoNumber1,lottoNumber2,lottoNumber3
userChoice1 = int(input('Choose a number between 1 and 50: '))
userChoice2 = int(input('Choose a number between 1 and 50: '))
userChoice3 = int(input('Choose a number between 1 and 50: '))
lottoNumber1, lottoNumber2, lottoNumber3 = lottery()
if userChoice1 == lottoNumber1:
if userChoice1 == lottoNumber2:
if userChoice1 == lottoNumber3:
if userChoice2 == lottoNumber1:
if userChoice2 == lottoNumber2:
if userChoice2 == lottoNumber3:
if userChoice3 == lottoNumber1:
if userChoice3 == lottoNumber2:
if userChoice3 == lottoNumber3:
print('You win $1,000')
else:
print('Try it again!')
main()

If you create two sets, one holding the lottery numbers and the other holding the user choices then one if statement could compare them:
import random
# Use sets to ensure lottery numbers and user choices are unique
lottoNumbers = set()
userChoices = set()
while len(lottoNumbers) < 3:
lottoNumbers.add(random.randint(1,50))
while len(userChoices) < 3:
userChoices.add(input('Choose a number between 1 and 50: '))
print(lottoNumbers)
print(userChoices)
if lottoNumbers == userChoices:
print('You win $1,000')

This will work for you.
from random import randint
def lottery():
return [randint(1, 50) for x in range(3)]
user_choices = list(map(int, [input('Choose a number between 1 and 50: ') for x in range(3)]))
lotto_numbers = lottery()
print(user_choices)
print(lotto_numbers)
if any(user_choice == lotto_number for user_choice, lotto_number in zip(sorted(user_choices), sorted(lotto_numbers)))

Related

How to combine guesses/credits

How do I combine my guesses and credits in my python guessing game? for example, if it took me 6 guesses with the first attempt then when I press y to do the game again and it took me 10 guesses how can I get those two to combine for 16 total guesses, same thing with credits (sorry if its a bad explanation) Heres what I have so far:
import random
# this function is for the welcome part of my code or the part where I give instructions on how to play
def game_intro():
print(" ---- G U E S S I N G G A M E ----")
print("\n L E T S P L A Y ")
print("""\nThe adjective of this game is to solve guess a 3 digit combination,
and it is your job to guess numbers 100-999 to find that combination!!""")
print("Credits")
print("1-4 guesses: up to 60 credits")
print("5-10 guesses: 10 credits")
print("if guesses more than 10 no credits")
num_of_guess = 0 # stores how many guess I have made
total_games = 1 # stores how many games I played
done = False # set done to False
credit = 0
def check_range_main():
global num_of_guess, credit # global for getting stuff outside functions
i = random.randint(100, 999) # generate number at random
num_of_guess = 0
while not done:
try: # anything other than a number between 100, 999 gets an error
user_input = int(input("\nEnter a guess between 100-999: "))
num_of_guess += 1
if user_input == i:
print('you got it right in ', str(num_of_guess), 'tries')
print(creditScore())
new_game_plus()
elif user_input < i: # if player guess lower than I tell player
print("To low")
elif user_input > i: # if player guess higher than tell players
print("to high")
elif user_input not in range(100, 999):
print("Invalid. Enter a number between 100-999")
num_of_guess += 1
except ValueError:
print("Invalid. Enter a number between 100-999")
def new_game_plus():
global done, num_of_guess
new_game = input("Do you want to start a new game? press y for yes n for no: ")
if new_game == "y":
check_range_main()
else:
done = True
def statistics(new_game): # statistics for games after players finish
global total_games, num_of_guess
if new_game == "n":
print()
total_games += 1
num_of_guess += num_of_guess
print("P O S T G A M E R E P O R T")
print()
print(f"total {total_games} games played.")
print('total guesses', num_of_guess)
print("your average guess per game is", num_of_guess / total_games)
def creditScore():
global credit, done
credit = num_of_guess
if 1 <= num_of_guess <= 4:
print("game credits", 60 / credit)
elif 5 <= num_of_guess <= 10:
print("game credits", 10)
else:
print("no credits")
#print("total credits", )
# def functions matches() that computes and returns the number of matching digits in a guess, you may assume that the
# combination and the guess are unique three-digit numbers.
# def play_one_game():
# global done
# i = random.randint(100, 999)
# while not done:
# try:
# user_input = int(input("\nEnter a guess between 100-999: "))
# if user_input == i:
# print("Nice Job")
# done = True
#
# elif user_input > i:
# print("input to high")
#
# elif user_input < i:
# print("input to low")
#
# elif user_input not in range(100, 999):
# print("invalid input a number in range of 100,999")
#
# except ValueError:
# print("invalid. input a number between 100,999")
# this is where all the different functions go
def main():
game_intro()
check_range_main()
new_game_plus()
statistics("n")
creditScore()
# play_one_game()
if __name__ == '__main__':
main()
Put out the num_of_guess = 0 from inside the check_range_main()
...
num_of_guess = 0 # stores how many guess I have made
total_games = 1 # stores how many games I played
done = False # set done to False
credit = 0
num_of_guess = 0
def check_range_main():
global num_of_guess, credit # global for getting stuff outside functions
i = random.randint(100, 999) # generate number at random
while not done:

Python: how to let dice not roll same value

In my Python program I want to roll a dice 8 times, but without it repeating the same value. I am trying different things but can't find a solution. My code is all follows:
if time%2 == 0 and counter_agents<max_agents:
succeeded=False
teller=0
while (not(succeeded)and teller<10):
dice = random.randint (0,7)
combis = []
if dice == 0:
pos_x=20
pos_y=75
elif dice == 1:
pos_x=21
pos_y=75
elif dice == 2:
pos_x=60
pos_y=75
elif dice == 3:
pos_x=61
pos_y=75
elif dice == 4:
pos_x=100
pos_y=75
elif dice == 5:
pos_x=101
pos_y=75
elif dice == 6:
pos_x=140
pos_y=75
elif dice == 7:
pos_x=141
pos_y=75
if counter_agents+1<=max_agents: #field[pos_y,x_pos]==0 and
succeeded=True
teller=teller+1
I believe this function does the job
import random
def roll_dice(min, max) -> int:
numbers = set()
for _ in range(max - min + 1):
while (dice_value := random.randint(min, max)) in numbers:
pass
numbers.add(dice_value)
yield dice_value
You can call it like this:
dice = roll_dice(0, 7)
dice_value = next(dice)
To get all values:
list(roll_dice(0, 7))
You can use this:
#Importing the library
import numpy as np
#create a function "def"
def roll():
numbers = list(np.random.choice(range(8), 8, replace=False))
return numbers
#calls the function
roll()

I can't count the number of tries in this game in pythin

I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue

Making Mastermind in Python

I am simply wondering how I can make my game of Mastermind work, more specifically how I would go about making "finish" global, how I would call these functions so that the program works correctly, and overall tips that would help enhance my code. I would also like to know how to make it so the program doesn't 'reroll' the computer-generated number every single loop. This was just a difficult problem for me and I can't seem to understand how to close it out with the correct function calls and niche aspects such as that. Thank you.
run = True
def get_guess():
while run:
guess = input("Provide four unique numbers: ")
count = 0
if len(guess) == 4:
guessdupe = guess[0] == guess[1] or guess[0] == guess[2] or guess[0] == guess[3] or guess[1] == guess[2] or guess[1] == guess[3] or guess[2] == guess[3]
else:
guessdupe = False
try:
try:
for i in range(4):
if int(guess[i]) <= 7 and int(guess[i]) >= 1 and len(guess) == 4:
count += 1
if len(guess) != 4:
print "Your guess must consist of 4 numbers!"
if guessdupe:
count -= 1
print "You can only use each number once!"
except ValueError:
print "You can only use numbers 1-7 as guesses"
except IndexError:
print "You can only use numbers 1-7 as guesses"
if count == 4:
break
return guess
def check_values(computer_list, user_list):
final_list = [''] * 4
for i in range(4):
if user_list[i] in computer_list:
if user_list[i] == computer_list[i]:
final_list[i] = "RED"
else:
final_list[i] = "WHITE"
else:
final_list[i] = "BLACK"
random.shuffle(final_list)
print final_list
return final_list
def check_win(response_list):
if response_list[0] == "RED" and response_list[1] == "RED" and response_list[2] == "RED" and response_list[3] == "RED":
print "Congratulations! You've won the game!"
global finish
finish = True
def create_comp_list():
while run:
compList = [random.randint(1, 7), random.randint(1, 7), random.randint(1, 7), random.randint(1, 7)]
listBool = compList[0] == compList[1] or compList[0] == compList[2] or compList[0] == compList[3] or compList[1] == compList[2] or compList[1] == compList[3] or compList[2] == compList[3]
if listBool:
continue
else:
return compList
def play_game():
for i in range(5):
print create_comp_list()
print get_guess()
check_win(check_values(create_comp_list(), get_guess()))
if finish:
break
play_game()```

How do you keep track of a global variable in python

I want to keep track of the variable TOTAL_TRI. TOTAL_TRI contains the number of correctly answered questions from the game. I need to save that value and pass it to the function statistics when statistics is called. Essentially, the player will play the game py_game, TOTAL_TRI will hold the number of questions they got right, and when the player calls the function statistics, it will display the number of questions they got right? I've been toying with this for a while with no significant progress. Any ideas?
P.S.
The other games in the menu are not yet implemented, but they'll do the same play-save correct number of questions-and let the player call to statistics kind of thing.
import random
from random import choice
from random import randint
#py_game------------------------------------------------------------------------
def py_game():
for k in range (1,3):
print('\nPractice Problem', k, 'of 2')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
else:
print("Sorry that's not the correct answer")
points = 0
for k in range (1,11):
print('\nProblem', k, 'of 10')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
points +=1
else:
print("Sorry that's not the correct answer")
TOTAL_TRI = points
#------------------------------------------------------------------------------
def statistics(points):
print('\nPyramid Game---------------------------')
incorrect = 10 - (points)
print ('You answered', points, 'questions correctly')
print ('You answered', incorrect, 'questions incorrectly')
#Main Menu--------------------------------------------------------------------------
def main_menu():
calculation_game = print("Enter 1 for the game 'Calculation'")
bin_reader = print("Enter 2 for the game 'Binary Reader'")
trifacto_game = print("Enter 3 for the game 'Trifacto'")
statistics = print("Enter 4 to view your statistics")
display_data = print("Enter 5 to display data")
save_game = print("Enter 5 to save your progress")
user_input = int(input('Make your selection: '))
if user_input == 1:
calculation()
if user_input == 2:
binary_reader()
if user_input == 3:
py_game()
if user_input == 4:
statistics(TOTAL_TRI)
if user_input == 5:
save_game()
if user_input != 1 or 2 or 3 or 4 or 5:
print('invalid input')
print('\n')
main_menu()
main_menu()
Using globals is code smell just waiting to happen. Pass your variable as an argument to your function. That's all.

Categories

Resources