Project Slot Machine in Python - python

I am creating a slot machine using python and i don't have any idea how to print the slot machine but i want to print the slot machine from spin_slot_machine(symbols) there i have nine letters from symbol_count who were randomly chosen. For example if this is output from parameter columns of spin_slot_machine(symbols)-->['A', 'B', 'E', 'A', 'C', 'B', 'C', 'F', 'B'] i want to make like that like this ex:
import random
MAX_VALUE = 100
MIN_VALUE = 1
ROWS = 3
COLUMNS = 3
symbols_count = {
"A":2,
"B":4,
"C":3,
"E":3,
"F":2
}
def spin_slot_machine(symbols):
all_symbols = []
columns = []
length_of_spin = 9
for symbol,symbol_count in symbols.items():
for i in range(symbol_count):
all_symbols.append(symbol)
for i in range(length_of_spin):
get_random = random.choice(all_symbols)
columns.append(get_random)
return columns
def print_slot_machine(columns):
pass
def deposit():
while True:
deposit_money = input("How much money would you like to deposit?: $")
if deposit_money.isdigit():
deposit_money = int(deposit_money)
if deposit_money > 0:
break
else:
print("You should deposit more than 0$")
print("Enter a digit")
return deposit_money
def bet_on_lines():
while True:
lines = input("On how many lines would you like to bet(1-3)?: ")
if lines.isdigit():
lines = int(lines)
if lines >= 1 and lines <= 3:
break
else:
print("Number of lines should be between 1-3")
print("Enter a number of lines")
return lines
def get_bet():
while True:
bet = input("How much money would you like to bet(1$-100$): ")
if bet.isdigit():
bet = int(bet)
if bet <= MAX_VALUE and bet >= MIN_VALUE:
break
else:
print("Money should be between 1-100$")
else:
print("Enter a digit")
return bet
def main():
balance = deposit()
lines_number = bet_on_lines()
while True:
bet_money = get_bet()
total_bet = bet_money * lines_number
if total_bet > balance:
print(f"Your balance is {balance}$.Balance shoudn't be less than betting money , bet less!")
else:
break
print(f"You are betting {total_bet}$ on {lines_number} lines.")
slot_machine = spin_slot_machine(symbols_count)
print_slot_machine(slot_machine)
main()

If you just need to print them you can use something like this:
symbols = ['A', 'B', 'E', 'A', 'C', 'B', 'C', 'F', 'B']
print(' | '.join(symbols[0:3]))
print(' | '.join(symbols[3:6]))
print(' | '.join(symbols[6:9]))
It will give you what you wanted

Related

Getting module object is not callable when importing random into a function

Making a script as a project for my manager and getting an error on line 16 when trying to import random into the function and getting the module object is not callable on that line. Here is the code.
import time
import random
list1 = ['A', 'B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0','!','#','#','$','%','^','&','*','(',')','-','_','=','+']
password = input('Enter a three character password')
guess = 0
while password != input:
import random
print('Loading, this is a test')
rannum = random('1','2','3')
if rannum == 1:
ran1 = random.sample(list1)
guess = ran1
print(guess)
elif rannum == 2:
ran1 = random.sample(list1)
ran2 = random.sample(list1)
guess = ran1 + ran2
print(guess)
elif rannum == 3:
ran1 = random.sample(list1)
ran2 = random.sample(list1)
ran3 = random.sample(list1)
guess = ran1 + ran2 + ran3
print(guess)
EDIT: I was able to clean the code up a decent amount to this:
import time
import random
list1 = ['A' , 'B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0','!','#','#','$','%','&','*','(',')','-','_','=','+']
password = input('Enter a three character password')
guess = 0
while guess != password:
rannum = random.randrange(1,4)
guess = random.sample(list1, k =rannum)
print(guess)
However whenever it prints it comes out looking like ['x' , 'v' , '1'] for example. Any idea on how to make it come out looking cleaner? So instead of that it would just come out like xv1?

Python3 - while ids > Stop: TypeError: unorderable types: str()> int()

Hello I am trying to run a program that will return back students grades and their average. ALSO I KNOW I AM A BASIC BRAINLESS FIRST YEAR PROGRAMMER. I WILL PROBABLY BE HORRIBLE AT PROBABLY. HOWEVER PLEASE HELP THE BEST YOU CAN IT WOULD BE GREATLY APPRECIATED.
THANK YOU.
The error says to be in line 49.
saying that"
line 49, in <module>
while ids > STOP:
TypeErrorL unorderable types: str() > int()
XXXX
def assigngrades(scores):
avg = sum(scores)/len(scores)
print(avg)
for val in scores:
if val > avg + 10:
grade = 'A'
elif val > avg + 5:
grade = 'B'
elif val > avg -5:
grade = 'C'
elif val > avg - 10:
grade = 'D'
else:
grade = 'F'
grades.append(grade)
print("in assigngrades, grades: ",grades)
return grades
def printsummary(grades, ave):
print('ID Score Average Grade')
print('===========================================')
print( )
for val in range(len(ids)):
print('val', val)
print(ids,' ',scores, ' ', grades)
return
#main
ids = []
scores = []
grades = []
STOP = 0
ids = input("Enter an ID:")
while ids > STOP:
ids.append(ids)
score = eval(input("Enter a score:"))
scores.append(score)
id = (input("Enter an ID number, 0 to STOP:"))
grades = assigngrades(scores)
print("after while loop")
print("Ids:", ids, "Scores:", scores, "Grades:", grades)
printsummary(grades, avg)
Nonetheless, I am confused on what is the issue.I appreciate your time and help looking at this. Thank you so so so much. Yes I know I am stupid.
The input() function returns a string, so you should convert it to an integer with int() so you can compare its value with another integer. You should also name the variable that stores the user input something other than ids since you already define it as a list:
ids = []
scores = []
grades = []
STOP = 0
id = int(input("Enter an ID:"))
while id > STOP:
ids.append(id)
score = eval(input("Enter a score:"))
scores.append(score)
grades = assigngrades(scores)
print("after while loop")
print("Ids:", ids, "Scores:", scores, "Grades:", grades)
printsummary(grades, avg)

Blackjack str iteration error

I am converting an array into a string to print, but the compiler still says not iterable.
Traceback (most recent call last):
File "python", line 157, in <module>
File "python", line 56, in total
TypeError: 'int' object is not iterable
The function total() is located on line 56, if you think it is the problem, but if you run the script, you should find that the function works properly every other instance.
import random
import time
def makeDeck():
cards = []
num = 1
for card in range(52):
cards.append(num)
num += 1
if num == 13:
num = 1
return cards
#def shuffle(cards):
#for card in cards:
#num = random.randint(0,51)
#cards.insert(0, cards[num])
#return cards
def shuffle(deck):
for card in deck:
hold = deck.pop(0)
deck.insert(random.randint(1,51),hold)
return deck
def cardToString(hand):
cardString = []
for card in hand:
if card == 1:
cardString.append('Ace')
elif card == 11:
cardString.append('Jack')
elif card == 12:
cardString.append('Queen')
elif card == 13:
cardString.append('King')
else:
cardString.append(str(card))
for card in cardString:
return card
def deal(user,deck):
hand = []
for x in range(2):
hand.append(deck.pop(0))
return hand
def deal1(user,deck):
hand = []
for card in deck:
hand.append(deck.pop(0))
return hand
def total(hand):
score = 0
for card in hand:
if(card>10):
score += 10
elif(card != 1):
score += card
else:
if(score>=11):
score+=1
else:
score+=11
return score
#def playGame():
#to do
name1 = input('Player 1, please enter your name:\n')
p2q = input('Will there be two plaers? (y/n)')
if(p2q == 'y' or p2q == 'Y' ):
p2yn = 1
name2 = input('Player 2, please enter your name:\n')
elif(p2q == 'n' or p2q == 'N'):
p2yn = 0
deck = makeDeck()
shuffle(deck)
p1hand = deal(name1,deck)
if(p2yn == 1):
p2hand = deal(name2,deck)
else:
print(end = ' ')
hs=0
print(str(name1)+', your hand is:', end = ' ' )
cardToString(p1hand)
print(str(p1hand[0])+',',p1hand[1], end = ' ')
print('and your total is', total(p1hand))
time.sleep(2)
tot1 = total(p1hand)
while(tot1 < 21):
p1cvar = input('Would you like another card? (y/n)\n')
if(p1cvar =='n' or p1cvar == 'N'):
break
else:
p1hand.append(deck.pop(0))
newCard = str(p1hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p1hand))
time.sleep(1)
if(total(p1hand) <= 21):
hs = total(p1hand)
else:
print('You went over 21!')
p1hand=0
time.sleep(1)
break
if(p1hand != 0):
print('The high score is', total(p1hand), 'held by', str(name1)+'.')
time.sleep(1)
shuffle(deck)
if(p2yn == 1):
print(str(name2)+', your hand is:', end = ' ' )
cardToString(p2hand)
print(str(p2hand[0])+',',p2hand[1], end = ' ')
print('and your total is', total(p2hand))
time.sleep(2)
tot1 = total(p2hand)
while(tot1 < 21):
p2cvar = input('Would you like another card? (y/n)\n')
if(p2cvar =='n' or p2cvar == 'N'):
break
else:
p2hand.append(deck.pop(0))
newCard = str(p2hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p2hand))
time.sleep(1)
if(total(p2hand)>21):
print('You went over 21!')
p2hand=0
time.sleep(1)
break
if(p2hand != 0 and total(p2hand)>hs):
print('The high score is', total(p2hand), 'held by', str(name2)+'.')
hs = total(p2hand)
time.sleep(1)
dealerHand = deal('Dealer',deck)
print("The dealer's hand is:", end = ' ' )
cardToString(dealerHand)
print(str(dealerHand[0])+',',dealerHand[1], end = ' ')
print('and their total is', total(dealerHand))
time.sleep(2)
totD = total(dealerHand)
while(totD < 21):
tdh = total(dealerHand)
if(tdh<hs and tdh<22):
dealerHand.append(deck.pop(0))
newCard = str(dealerHand[-1])
cardToString(newCard)
print('Dealer got a', newCard)
time.sleep(.5)
print("Dealer's total is now", total(dealerHand))
time.sleep(1)
if(total(dealerHand) <= 21 and total(dealerHand)>hs):
hs = total(dealerHand)
else:
print('Dealer went over 21!')
dealerHand=0
else:
break
if(dealerHand != 0):
print('The high score is', total(dealerHand), 'held by', str("Dealer")+'.')
while(total(p1hand)>21 or total(dealerHand)>21):
if(total(dealerHand)>21):
print('Dealer has been eliminated from play!')
elif(total(p1hand)>21):
print(name1,'has been eliminated from play!')
About 11 lines up from the bottom of your code block, you are setting the dealers hand to 0:
....
else:
print('Dealer went over 21!')
dealerHand=0
This is concerning since their hand should be a list. Thus when you try to iterate over it to count the total, you get that an int isn't iteratable.
Should probably be something like
dealerHand = []
Also, a few lines after that, you are asking if dealerHand!=0, when I think you mean total(dealerHand)
You should also be careful with your other assignments that change a variable from a list to an int such as
#Around line 111
print('You went over 21!')
p1hand=0
time.sleep(1)
break
.....
#Around line 140
print('You went over 21!')
p2hand=0
time.sleep(1)
break
Because Python is not strongly type, changing the type of a given variable name can lead to a lot of these kinds of problems
#Stephen gave you the direct answer. I suggest using pylint3 (or some other linter) on your code. It would have told you the problem
R:170, 6: Redefinition of dealerHand type from list to int
(redefined-variable-type)
This will help you in the future.

python, GPA calculator, about working code

this is a GPA calculator code in my textbook. I'd like to ask about a few this I don't understand here.
# Semester GPA Calculation
def convertGrade(grade):
if grade == 'A+':
return 4
if grade == 'A':
return 3.7
if grade == 'A-':
return 3.3
if grade == 'B+':
return 3.0
if grade == 'B':
return 2.7
if grade == 'B-':
return 2.3
if grade == 'C+':
return 2.0
if grade == 'C':
return 1.7
if grade == 'C-':
return 1.3
if grade == 'D+':
return 1.0
if grade == 'D':
return 0.7
if grade == 'D-':
return 0.3
else:
return 0
def getGrades():
semester_info = []
more_grades = True
empty_str = ''
while more_grades:
course_grade = input('Enter grade (hit Enter if done): ')
while course_grade not in ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'E+', 'E', 'E-', 'F', empty_str]:
course_grade = input('Enter letter grade you received: ')
if course_grade == empty_str:
more_grades = False
else:
num_credits = int(input('Enter number of credits: '))
semester_info.append([num_credits, course_grade])
return semester_info
def calculateGPA(sem_grades_info, cumm_gpa_info):
sem_quality_pts = 0
sem_credits = 0
current_cumm_gpa, total_credits = cumm_gpa_info
for k in range(len(sem_grades_info)):
num_credits, letter_grade = sem_grades_info[k]
sem_quality_pts = sem_quality_pts + \
num_credits * convertGrade(letter_grade)
sem_credits = sem_credits + num_credits
sem_gpa = sem_quality_pts / sem_credits
new_cumm_gpa = (current_cumm_gpa * total_credits + sem_gpa * \
sem_credits) / (total_credits + sem_credits)
return (sem_gpa, new_cumm_gpa)
# ---- main
# program greeting
print('This program calculates new semester and cumulative GPAs\n')
# get current GPA info
total_credits = int(input('Enter total number of earned credits: '))
cumm_gpa = float(input('Enter your current cummulative GPA: '))
cumm_gpa_info = (cumm_gpa, total_credits)
# get current semester grade info
print()
semester_grades = getGrades()
# calculate semester gpa and new cumulative gpa
semester_gpa, cumm_gpa = calculateGPA(semester_grades, cumm_gpa_info)
#display semester gpa and new cummulative gpa
print('\nYour semester GPA is', format(semester_gpa, '.2f'))
print('Your new cummulative GPA is', format(cumm_gpa, '.2f'))
What does current_cumm_gpa, total_credits = cumm_gpa_info mean below? Does it create a new array? I tried simpler but it doesn't work.
def calculateGPA(sem_grades_info, cumm_gpa_info):
sem_quality_pts = 0
sem_credits = 0
current_cumm_gpa, total_credits = cumm_gpa_info
From this line:
cumm_gpa_info = (cumm_gpa, total_credits)
We can see that cumm_gpa_info is a tuple of two values. Then current_cumm_gpa, total_credits = cumm_gpa_info unpacks the values in the tuple to two variables, the first to current_cumm_gpa and the second to total_credits. It's a simpler way of doing:
current_cumm_gpa = cumm_gpa_info[0]
total_credits = cumm_gpa_info[1]
From the docs:
This is called, appropriately enough, sequence unpacking and works for
any sequence on the right-hand side. Sequence unpacking requires that
there are as many variables on the left side of the equals sign as
there are elements in the sequence. Note that multiple assignment is
really just a combination of tuple packing and sequence unpacking.
Tracing your program we see the following :
>>> total_credits = int(input('Enter total number of earned credits: '))
#3.2
>>> cumm_gpa = float(input('Enter your current cummulative GPA: '))
#4.6
>>> cumm_gpa_info = (cumm_gpa, total_credits)
>>> cumm_gpa_info
(3.2 , 4.6)
>>> type(cumm_gpa_info)
Tuple
So we see that cumm_gpa_info is a Tuple. Now this is passed to the function.
>>> ... = calculateGPA(semester_grades, cumm_gpa_info)
#inside function
>>> current_cumm_gpa, total_credits = cumm_gpa_info
#current_cumm_gpa, total_credits = (3.2 , 4.6)
>>> current_cumm_gpa
3.2
>>> total_credits
4.6
So as we can see, the values were unpacked from the tuple and assigned to current_cumm_gpa & total_credits respectively.
It is similar to doing :
>>> current_cumm_gpa = cumm_gpa_info[0]
>>> total_credits = cumm_gpa_info[1]
Note : sorry if its not exactly how it would look on a console. Can't get to my PC, writing it out on my mobile right now. So have put it approximately how it would look.

Exporting variables to a Excel spreadsheet

I have made a program that calculates the population of greenflies. A task that I am struggling with is exporting several a series of variables to excel. I have worked out the math for the greenflies, but I can't figure out how to put that into a spreadsheet. Here's the code:
import winsound
import time
winsound.PlaySound("SystemHand", winsound.SND_ALIAS) #startup
#menu
print("Greenfly population model")
time.sleep(1)
one=1
print("1: Set the generation 0 values")
time.sleep(1)
two=2
print("2: Display the generation 0 values")
time.sleep(1)
three=3
print("3: Run the model")
time.sleep(1)
four=4
print("4: Export the data")
time.sleep(1)
five=5
print("5: Quit")
time.sleep(1)
#base code
while True: #wont shut down till option 5 is entered
print("")
ans=int(input("Please enter the number of the choice you want "))
if ans == one:
while True:
generations=float(input("Enter the number of generations you want the model to run for (Must be in 5 and 25 inclusive) "))
if generations < 5 or generations > 25:
print("Between 5 and 25 please")
else:
break
while True:
adultsur = float(input("Choose adult survival rate between 0 and 1 "))
if adultsur < 0 or adultsur > 1:
print ("Between 1 and 0 please") #wont mess up the decimals
else:
break
while True:
juvensur=float(input("Choose juvenile survivle rate between 0 and 1 "))
if juvensur < 0 or juvensur > 1:
print ("Between 1 and 0 please")
else:
break
while True:
sensur=float(input("Choose senile survivle rate between 0 and 1 "))
if sensur < 0 or sensur > 1:
print ("Between 1 and 0 please")
else:
break
juv=int(input("Choose the amount of juveniles "))
adu=int(input("Choose the amount of adults ")) #had issue with floats here so left it as int(input())
sen=int(input("Choose the amount of seniles "))
birth=int(input("Enter the birthrate of the adults "))
if ans == two:
print("The new generation to model is ",generations) #no issues here
time.sleep(1)
print("The adult survivul rate is ",adultsur)
time.sleep(1)
print("The juvenile survivul rate is ",juvensur)
time.sleep(1)
print("The senile survivul rate is ",sensur)
time.sleep(1)
print("There are ",juv," juveniles")
time.sleep(1)
print("There are ",adu," juveniles")
time.sleep(1)
print("There are ",sen," juveniles")
time.sleep(1)
print("The birthrate of adults is ",birth)
if ans == three:
print("Running module.")
time.sleep(0.1)
print("Running module..")
time.sleep(0.1)
print("Running module...")
time.sleep(0.1)
counter = 0
print("GENERATION JUVENILES ADULTS SENILES")
while generations > counter:
print ("",int(counter)," ", int(juv)," ", int(adu)," ", int(sen))
int(sen)
int(adu)#gets rid off the neverending decimals and rounds it up
int(juv)
sen *= sensur #takes out the old seniles
adu *= adultsur #does the math in a much simpler way than basic maths
juv *= len
juvn = juv
juv = adu * birth
sen += adu
adu += juvn
counter= counter+1 #will only repeat how many times the code was set to run
if ans == four
print ("",int(counter)," ", int(juv)," ", int(adu)," ", int(sen))
int(sen)
int(adu)
int(juv)
sen *= sensur
adu *= adultsur
juv *= len
juvn = juv
juv = adu * birth
sen += adu
adu += juvn
counter= counter+1
if ans == five:
print("Understandable, have a great day")
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
winsound.PlaySound("*", winsound.SND_ALIAS)
break
Can I have some help with exporting it or just teach me how to do it.
Thanks.
There are multiple ways that you can write data in excel and, additionally there are multiple formats that you can use.
Python csv module implements classes which can be used for writing and reading tabular data. For writing into file you can either use csv.writer or you can use csv.DictWriter.
The csv.writer returns a writer object which is responsible for converting the data into delimited strings. Here is an example on how to use it:
import csv
data_header = ['id', 'width', 'height']
data = [[0, 10, 5],
[1, 2, 3],
[2, 50, 40]]
with open('test.csv', 'w') as file_writer:
writer = csv.writer(file_writer)
writer.writerow(data_header)
for item in data:
writer.writerow(item)
The csv.DictWriter returns an object which operates like a regular writer but maps dictionaries onto output rows. Here is an example on how to use it:
import csv
data_header = ['id', 'width', 'height']
data = [{'id': 0, 'width': 10, 'height': 5},
{'id': 1, 'width': 2, 'height': 3},
{'id': 2, 'width': 50, 'height': 40}]
with open('test.csv', 'w') as file_writer:
dict_writer = csv.DictWriter(file_writer, data_header)
dict_writer.writeheader()
for item in data:
dict_writer.writerow(item)
As you can see, the difference between csv.writer and csv.DictWriter is how you provide the data to the interface. In csv.writer you provide the data in a list, and you are responsible for keeping the order in the list so it would be written in the correct columns and in csv.DictWriter you provide a dictionary where the keys are the column names and the value is the data for the column.

Categories