This is how i have coded, but i am not able to get the result as i want
def arith():
import random
operators = ("+","*")
for i in range(4):
x = random.randint(1,10)
y = random.randint(1,10)
choose_operators = random.choice(operators)
print (x,choose_operators,y)
t1 = int(input("what is the answer:"))
counter = 0
if t1 == (x,operators,y):
counter = counter + 1
if counter > 3:
print("Congratulations!")
else:
print("Please ask your teacher for help")
I get the result as
arith()
7 * 3
what is the answer:21
3 + 2
what is the answer:5
8 * 9
what is the answer:72
3 * 9
what is the answer:2
That's it!
How do i make it count the number of correct answers and print the command i have written ?
Thanks in advance
The line if t1 == x,operators,y is not operating on x and y. The operator is the form of a string so it is checking if t1 is equal to, for example: (7, '*', 3). To actually do the operation you can use eval() Also, you need to fix some stuff in your code so it only checks counter after the for loop is finished.
def arith():
import random
operators = ("+","*")
counter = 0
for i in range(4):
x = random.randint(1,10)
y = random.randint(1,10)
choose_operators = random.choice(operators)
print (x,choose_operators,y)
t1 = int(input("what is the answer:"))
if t1 == eval(str(x) + choose_operators + str(y)):
counter = counter + 1
if counter > 3:
print("Congratulations!")
else:
print("Please ask your teacher for help")
Related
import random
from browser import timer
operators = ['*', '/', '+', '-']
number = input('How many problems would you like?')
number = int(number)
counter = 1
while counter <= number:
first = random.randint(0,10)
second = random.randint(0,10)
randoperator = random.choice(operators)
problem = '{} {} {} {}'.format(first, randoperator, second, "= ")
answer = input(problem)
correct = problem
counter+=1
I have tried putting this in but it doesn't run anything
if problem == answer:
print("Correct!")
You need to actually do the calculation to find out what the answer is. Here's a quick and dirty way to do that:
import random
operators = ['*', '/', '+', '-']
number = input('How many problems would you like?')
number = int(number)
counter = 1
while counter <= number:
first = random.randint(0,10)
second = random.randint(0,10)
randoperator = random.choice(operators)
problem = '{} {} {}'.format(first, randoperator, second)
answer = input(problem + ' = ')
if eval(problem) == float(answer):
print("Correct!")
counter+=1
Using eval is not a great idea for reasons outlined in the answers to this question. In your case, you already know the two integers and the operator, so finding the expected answer without eval is pretty easy. Say you define a function that can do this for you:
def arithmetic(op, a, b):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return a / b
Then call this function to get the expected answer and compare that with the answer that the user gave,
while counter <= number:
first = random.randint(0,10)
second = random.randint(0,10)
randoperator = random.choice(operators)
problem = '{} {} {}'.format(first, randoperator, second)
answer = input(problem + ' = ')
if arithmetic(randoperator, first, second) == float(answer):
print("Correct!")
counter+=1
def opdracht3()
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst += n
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()
I want to get the average of the list that is being created, but when I add numbers like 11, the len(waslijst) gets set to 2 instead of 1. Is there another way to get the average, or am I using the len function wrong?
You need use .append method to store all elements in a list.
def opdracht3():
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst.append(n)
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()
So in my coding class we are required to make a "Dice Poker" game. We need to implement a scoring system, however, mine keeps returning a "None", therefore causing issues when I want to add the accumulated score to the base score of 100, since NoneTypes and integers can not be added. I'm aware that I need to fix whatever is causing the None, but I'm not sure how. I believe the problem could be in the "scoring" function, but perhaps it is more lurking in the later parts (After the #Choosing Last Roll or #Scoring output comments) of the function "diceGame". I'm very new to coding, and after hours of looking at this thing I'm not really sure what I'm looking at anymore. Thank you so much for your help!
Text-based dice game
from random import randint
def rollFiveDie():
allDie = []
for x in range(5):
allDie.append(randint(1,6))
return allDie
def outputUpdate(P, F):
print(P)
print(F)
def rollSelect():
rollSelected = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
selectList = rollSelected.split()
return selectList
def rollPicked(toRollList, diceList):
for i in toRollList:
diceList[int(i) - 1] = randint(1,6)
def scoring(dList):
counts = [0] * 7
for value in dList:
counts[value] = counts[value] + 1
if 5 in counts:
score = "Five of a Kind", 30
elif 4 in counts:
score = "Four of a Kind", 25
elif (3 in counts) and (2 in counts):
score = "Full House", 15
elif 3 in counts:
score = "Three of a Kind", 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
score = "Straight", 20
elif counts.count(2) == 2:
score = "Two Pair", 5
else:
score = "Lose", 0
return score
def numScore(diList):
counts = [0] * 7
for v in diList:
counts[v] = counts[v] + 1
if 5 in counts:
finScore = 30
elif 4 in counts:
finScore = 25
elif (3 in counts) and (2 in counts):
finScore = 15
elif 3 in counts:
finScore = 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
finScore = 20
elif counts.count(2) == 2:
finScore = 5
else:
finScore = 0
return finScore
def printScore(fscore):
print(fscore)
print(" ")
def diceGame():
contPlaying = True
while contPlaying:
playPoints = 30
if playPoints > 9:
playPoints -= 10
else:
print("No more points to spend. Game Over.")
contPlaying = False
playing = input("Would you like to play the Dice Game? (Answer 'y' or 'n'): ")
print(' ')
if playing == 'y':
#First Roll
fiveDie = rollFiveDie()
outputUpdate("Your roll is...", fiveDie)
#Choosing Second Roll/Second Roll execution
pickDie = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
pickDie = pickDie.split()
rollPicked(pickDie, fiveDie)
outputUpdate("Your next roll is...", fiveDie)
#Choosing Last Roll
pickDie = rollSelect()
rollPicked(pickDie, fiveDie)
outputUpdate("Your final roll is...", fiveDie)
#Scoring output
scoring(fiveDie)
finalScore = numScore(fiveDie)
playPoints += finalScore
print(playPoints)
else:
contPlaying = False
def main():
diceGame()
main()
This is for homework. This particular school offers 0 assistance and the professor is less than helpful. I am just looking for guidance as to why this code isn't working. I have to use Python 2.7. When I run the program it asks me to enter the appropriate amount of pints but then does nothing.
# This program finds the average number of pints collected, the highest amount, and the lowest amount
# Lab 9-4 Blood drive
#the main function
def main():
endProgram = 'no'
print
while endProgram == 'no':
print
# declare variables
pints = [0] * 7
totalPints = 0
averagePints = 0
highPints = 0
lowPints = 0
# function calls
pints = getPints(pints)
totalPints = getTotal(pints, totalPints)
averagePints = getAverage(totalPints, averagePints)
highPints = getHigh(pints, highPints)
lowPints = getLow(pints, lowPints)
displayInfo(averagePints, highPints, lowPints)
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
while not (endProgram == 'yes' or endProgram == 'no'):
print 'Please enter a yes or no'
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
#the getPints function
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = input('Enter pints collected: ')
counter = counter + 1
return pints
#the getTotal function
def getTotal(pints, totalPints):
counter = 0
while counter < 7:
totalPints = totalPints + pints[counter]
counter = counter + 1
return totalPints
#the getAverage function
def getAverage(totalPints, averagePints):
averagePints = totalPints / 7
return averagePints
#the getHigh function
def getHigh(pints, highPints):
highPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] > highPints:
highPints = pints[counter]
counter = counter + 1
return highPints
#the getLow function
def getLow(pints, lowPints):
lowPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] < lowPints:
lowPints = pints[counter]
counter = counter + 1
return lowPints
#the displayInfo function
def displayInfo(averagePints, highPints, lowPints):
print "The average number of pints donated is ", averagePints
print "The highest pints donated is ", highPints
print "The lowest pints donated is ", lowPints
# calls main
main()
There is an infinite loop in function getLow() because counter is incremented only when the current value is less than the previous value. e.g. entering values 1, 2, 3, 4, 5, 6, 7 will result in an infinite loop, however, the loop will terminate if you entered 7, 6, 5, 4, 3, 2, 1.
Function getHigh() has a similar problem, but the values must be ascending if the infinite loop is to be avoided. Note that one of getLow() or getHigh() will always produce a loop in your code.
Hint: look at using Python's min() and max() functions.
I am making a code to simulate a dice and do other stuff, but there is a while loop which isn't breaking and I don't know why.
import random
import math
#infinite loop
while True:
while True:
a = 0
#input amount of dice
att_die = raw_input('Attacking dice: ')
def_die = raw_input('Defending dice: ')
#att
#if NaN
if str(att_die).isdigit() == False:
print('NaN')
#if not NaN
else:
a += 1
#def
#if NaN
if str(def_die).isdigit() == False:
print('NaN')
#if not NaN
else:
a +=1
if a == 2:
break
if att_die >= def_die:
no = def_die
else:
no = att_die
print (no)
x = 0
while x <= no:
att_loss = 0
def_loss = 0
roll_att = random.randint(1,6)
roll_def = random.randint(1,6)
if roll_att <= roll_def:
att_loss += 1
elif roll_att == roll_def:
att_loss += 1
else:
def_loss += 1
x += 1
print(x)
print('Att: -' + str(att_loss) + '\nDef: -' + str(def_loss))
everything works up until the last while loop, which just continuously outputs the value of x increasing.
Any help on how to fix this would be appreciated.
Thanks in advance
no is a str, not an int. x is an int. In Python2, ints are always compare less than strs:
In [187]: 9999 < '1'
Out[187]: True
The solution is to convert the str no into an int:
no = int(no)
In [188]: 9999 < int('1')
Out[188]: False
Note that in Python3, comparing an int with a str raises a TypeError, which will save many a programmer from this pitfall.
Here's a refactored version:
import random
import math
DIE_SIDES = 6
WINNING_ATTACK_ODDS = 0.5 * (DIE_SIDES - 1) / DIE_SIDES
def get_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def attack():
"""
Does the attacker win?
"""
return random.random() < WINNING_ATTACK_ODDS
def main():
while True:
att_die = get_int("Attacking dice: ")
def_die = get_int("Defending dice: ")
rolls = min(att_die, def_die)
def_loss = sum(attack() for _ in range(rolls))
att_loss = rolls - def_loss
print("Att: -{}\nDef: -{}".format(att_loss, def_loss))
if __name__=="__main__":
main()