How to make x variable change randomly and loop (Python) - python

I am trying to make a simple program to count how many times x equals 10.
Here is the code
from random import randint
x = randint(0, 10)
score = 0
if x == 10:
score += 1
print(score)
x == randint(0, 10)
elif x != 10:
x = randint(0, 10)
I used while clause and every possible clause for loop but I don't know why it wont work.
Any help would be appreciated.
I am still a beginner in python so please don't mock me for the bad code.

You can use a for loop if you know how many times you would like to loop.
from random import randint
x = randint(0, 10)
score = 0
for i in range(0,5): # This will loop 5 times
if x == 10: # If x is 10, add 1 to score
score += 1
print(score)
x = randint(0, 10)
You can also use a while loop to do this unlimited times or until a condition is met.
from random import randint
x = randint(0, 10)
score = 0
while True: # This will loop indefinitely or until you break
x = randint(0, 10)
if x == 10: # If x is 10, add 1 to score
score += 1
print(score)

Related

I am creating a game but the score wont update more than once in this simple code. it updates to 10 once and stays the same after that no matter what

This is the code -
import random
def game():
randno = random.randint(1,11)
a = int(input("guess a number from 1 to 10 - "))
if randno == a:
for d in range(0, 1000001):
d+=10
print ("gud, score increased by 10")
return d
else :
return (0)
with open("hiscore.txt", "r") as a:
S = a.read(int())
HS = game()
if S=="":
with open("hiscore.txt", "w") as b:
b.write(str(HS))
elif HS>S:
with open("hiscore.txt", "w") as b:
b.write(str(HS))
The score should be increased by 10 every time u guess the correct number, the score will increase by 10 and should appear in another file called hiscore.txt. the issue is that the score does get increased but only once. this means that it only increases the score to 10 the first time and does not increase after that no matter how many time you guess correct
I suppose that you want:
def game():
d = 0
for _ in range(0, 1000001):
randno = random.randint(1,11)
a = int(input("guess a number from 1 to 10 - "))
if randno == a:
d += 10
print ("gud, score increased by 10")
return d
Move the no loop outside, and skip the else part. Also return outside the loop.

How do you mulitply via addition?

I'm having trouble trying to
compute x * y using only addition, printing the intermediate result for each loop iteration, and
printing the final number. This is my
teacher's example of what the output should look like
I could really use some help figuring it out,, I don't really understand how to yet.
Edit: I am a first time coder so I'm not very skilled, I do know the basics though (Also very new to this website) Here's what my code looks like so far:
x = int(input("Input positive x: "))
y = int(input("Input positive y: "))
z = 0
w = 0
if x < 0:
exit("Please input a positive number for x")
if y < 0:
exit("Please input a positive number for y")
def multiplier(number, iterations):
for i in range(1, iterations):
number = number + 3
print(number) # 12
multiplier(number=3, iterations=4)
My answer. Little shorter than the others.
Ok, try thinking of multiplication as adding a number with itself by x times. Hence, 3*4 = 3+3+3+3 = 12, which is adding 3 by itself 4 times
Replicating this with a for loop:
#inputs
x = 3
y = 4
#output
iteration = 1
result = 0
for num in range(4):
result += x
print(f'Sum after iteration {iteration}: {result}')
iteration += 1 #iteration counter
The resulting output will be:
Sum after iteration 1: 3 Sum after iteration 2: 6 Sum after iteration
3: 9 Sum after iteration 4: 12
The code is simple and straightforward,Check which number is bigger and iterate according to that number.
x = 3
y = 4
out = 0
if x > y:
for v in range(0,x):
out += y
print("after iteration",v+1, ":", out)
if y > x:
for v in range(0,y):
out += x
print("after iteration",v+1, ":", out)
print(x,"*", y, "=", out)
Use print to print inside the loop to show each number after adding and the number of iteration occurs.
Here is a start. This assume both arguments are integers 0 or more:
def m(n1, n1a):
n1b = 0
while n1a > 0:
n1b += n1
n1a -= 1
return n1b
n = m(9, 8)
print(n == 72)

cant get a variable equal in a loop

So I'm just trying to learn programming/coding. and I'm trying to make a loop where the computer guesses at random a number that I put in (the variable), I mostly the loop with the "while" and "if/else" loops down but like...idk how to put the variable in. I'm sure there are other things wrong with the code. Its just a simple one since I actually just started 2 days ago. here is the code
input = var
x = 0
counter = 0
while x == 0:
from random import *
print randint(1, 3)
if randint == var:
x = 1
count = counter + 1
print (counter)
print "Good Bye!"
else:
x == 0
counter = counter + 1
print (counter)
if randint == var:
is always False. randint is the random function, var is an integer (well, it should be).
You mean:
r = randint(1,3)
if r == var:
...
(store the result of the random function to be able to display it and test it, calling it again yields another value, obviously)
and yes, the first line should be var = int(input()) to be able to input an integer value.
Updated according to the comments:
I just made a working version of your program, your input would be 1, and computer would randomly guess from 1,2,3 until it gives the correct answer.
#input = var this line is wrong as pointed out by others
input = 1 # this is your input number
x = 0
counter = 0
import random
while x == 0:
#from random import * this will import too much in the while loop according to comments
#randint(1, 3) this line is wrong
randint = random.randint(1, 3) # computer guess from 1-3, then you should assign random generated number to randint
print(randint)
# if randint == var: this line is wrong, you can't compare randint to var.
if randint == input: #
x = 1
count = counter + 1
print(counter)
print("Good Bye!")
else:
x = 0
counter = counter + 1
print(counter)
output:
3
1
1
1
Good Bye!
Process finished with exit code 0

Python: Trouble with Nested loops. Want to run random variable multiple times and averaging results...

I tried to use a while loop inside a while loop but have had little success. We want to select a number from the deck variable. The selection variable will go up each time a number between 1 and 20 are selected.
We then want to run that piece 100 times and average the type1 variable. The end result should be a number between 1 and 7. Any help would be fantastic!
import random
deck = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]
a = 0
b = 0
type1 = 0
while b < 100:
while a < 7:
a += 1
selection = deck[random.randint(0,len(deck)-1)]
if selection > 0 and selection < 21:
print "success!"
type1 += 1
print type1
b += 1
print b
exit()
Few minor problems, see the comments.
import random
# Use a list comprehension to make it more readable
deck = [x for x in range(1, 61)]
# Consider creating a length variable, so you aren't calculating len(deck) every loop
deck_length = len(deck)
a = 0
b = 0
type1 = 0
while b < 100:
while a < 7:
a += 1
selection = deck[random.randint(0,deck_length-1)]
if selection > 0 and selection < 21:
print("success!")
type1 += 1
print type1
# Move this increment into the while loop, so that it gets updated.
b += 1
print b
exit()
Here is a functional version:
from random import choice
DECK = list(range(1, 61))
def get_hand(num_cards = 7):
return [choice(DECK) for _ in range(num_cards)]
def eval_hand(hand):
return sum(card <= 20 for card in hand)
def average(iterable):
lst = list(iterable)
return sum(lst) / len(lst)
def get_avg_hand(num_hands=100):
return average(eval_hand(get_hand()) for _ in range(num_hands))
avg = get_avg_hand()
but it still disguises the underlying math, which simplifies to:
Given 700 integers chosen uniformly from [1..60],
how many do you expect to be <= 20?
which gives a probability distribution like
from math import factorial
import matplotlib.pyplot as plt
SAMPLES = 700
TRUE_ODDS = float(20) / 60
FALSE_ODDS = 1. - TRUE_ODDS
def odds(x):
"""
Return the probability that exactly x samples are true
"""
return (
# number of possible arrangements
factorial(SAMPLES) / (factorial(x) * factorial(SAMPLES - x))
# odds of each arrangement
* TRUE_ODDS ** x * FALSE_ODDS ** (SAMPLES - x)
)
# domain
xs = list(range(SAMPLES + 1))
# range
ys = [odds(x) for x in xs]
plt.plot(xs, ys)
which looks like

Python Coin Toss

I am VERY new to Python and I have to create a game that simulates flipping a coin and ask the user to enter the number of times that a coin should be tossed. Based on that response the program has to choose a random number that is either 0 or 1 (and decide which represents “heads” and which represents “tails”) for that specified number of times. Count the number of “heads” and the number of “tails” produced, and present the following information to the user: a list consisting of the simulated coin tosses, and a summary of the number of heads and the number of tails produced. For example, if a user enters 5, the coin toss simulation may result in [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]. The program should print something like the following: “ [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]
This is what I have so far, and it isn't working at all...
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
You need a loop to do this. I suggest a for loop:
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
for amount in range(number):
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
I suggest you read this on for loops.
Also, you could pass number as a parameter to the function:
import random
def coinToss(number):
recordList, heads, tails = [], 0, 0 # multiple assignment
for i in range(number): # do this 'number' amount of times
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
Then, you need to call the function in the end: coinToss().
You are nearly there:
1) You need to call the function:
coinToss()
2) You need to set up a loop to call random.randint() repeatedly.
I'd go with something along the lines of:
from random import randint
num = input('Number of times to flip coin: ')
flips = [randint(0,1) for r in range(num)]
results = []
for object in flips:
if object == 0:
results.append('Heads')
elif object == 1:
results.append('Tails')
print results
This is possibly more pythonic, although not everyone likes list comprehensions.
import random
def tossCoin(numFlips):
flips= ['Heads' if x==1 else 'Tails' for x in [random.randint(0,1) for x in range(numflips)]]
heads=sum([x=='Heads' for x in flips])
tails=numFlips-heads
import random
import time
flips = 0
heads = "Heads"
tails = "Tails"
heads_and_tails = [(heads),
(tails)]
while input("Do you want to coin flip? [y|n]") == 'y':
print(random.choice(heads_and_tails))
time.sleep(.5)
flips += 1
else:
print("You flipped the coin",flips,"times")
print("Good bye")
You could try this, i have it so it asks you if you want to flip the coin then when you say no or n it tells you how many times you flipped the coin. (this is in python 3.5)
Create a list with two elements head and tail, and use choice() from random to get the coin flip result. To get the count of how many times head or tail came, append the count to a list and then use Counter(list_name) from collections. Use uin() to call
##coin flip
import random
import collections
def tos():
a=['head','tail']
return(random.choice(a))
def uin():
y=[]
x=input("how many times you want to flip the coin: ")
for i in range(int(x)):
y.append(tos())
print(collections.Counter(y))
Instead of all that, you can do like this:
import random
options = ['Heads' , 'Tails']
number = int(input('no.of times to flip a coin : ')
for amount in range(number):
heads_or_tails = random.choice(options)
print(f" it's {heads_or_tails}")
print()
print('end')
I did it like this. Probably not the best and most efficient way, but hey now you have different options to choose from. I did the loop 10000 times because that was stated in the exercise.
#Coinflip program
import random
numberOfStreaks = 0
emptyArray = []
for experimentNumber in range(100):
#Code here that creates a list of 100 heads or tails values
headsCount = 0
tailsCount = 0
#print(experimentNumber)
for i in range(100):
if random.randint(0, 1) == 0:
emptyArray.append('H')
headsCount +=1
else:
emptyArray.append('T')
tailsCount += 1
#Code here that checks if the list contains a streak of either heads or tails of 6 in a row
heads = 0
tails = 0
headsStreakOfSix = 0
tailsStreakofSix = 0
for i in emptyArray:
if i == 'H':
heads +=1
tails = 0
if heads == 6:
headsStreakOfSix += 1
numberOfStreaks +=1
if i == 'T':
tails +=1
heads = 0
if tails == 6:
tailsStreakofSix += 1
numberOfStreaks +=1
#print('\n' + str(headsStreakOfSix))
#print('\n' + str(tailsStreakofSix))
#print('\n' + str(numberOfStreaks))
print('\nChance of streak: %s%%' % (numberOfStreaks / 10000))
#program to toss the coin as per user wish and count number of heads and tails
import random
toss=int(input("Enter number of times you want to toss the coin"))
tail=0
head=0
for i in range(toss):
val=random.randint(0,1)
if(val==0):
print("Tails")
tail=tail+1
else:
print("Heads")
head=head+1
print("The total number of tails is {} and head is {} while tossing the coin {} times".format(tail,head,toss))
Fixing the immediate issues
The highest voted answer doesn't actually run, because it passes a string into range() (as opposed to an int).
Here's a solution which fixes two issues: the range() issue just mentioned, and the fact that the calls to str() in the print() statements on the last two lines can be made redundant. This snippet was written to modify the original code as little as possible.
def coinToss():
number = int(input("Number of times to flip coin: "))
recordList = []
heads = 0
tails = 0
for _ in range(number):
flip = random.randint(0, 1)
if (flip == 0):
recordList.append("Heads")
else:
recordList.append("Tails")
print(recordList)
print(recordList.count("Tails"), recordList.count("Heads"))
A more concise approach
However, if you're looking for a more concise solution, you can use a list comprehension. There's only one other answer that has a list comprehension, but you can embed the mapping from {0, 1} to {"Heads", "Tails"} using one, rather than two, list comprehensions:
def coinToss():
number = int(input("Number of times to flip coin: "))
recordList = ["Heads" if random.randint(0, 1) else "Tails" for _ in range(number)]
print(recordList)
print(recordList.count("Tails"), recordList.count("Heads"))
import random
def coinToss(number):
heads = 0
tails = 0
for flip in range(number):
coinFlip = random.choice([1, 2])
if coinFlip == 1:
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
number = input("Number of times to flip coin: ")
recordList = []
if type(number) == str and len(number)>0:
coinToss(int(number))
print("Heads:", str(recordList.count("Heads")) , "Tails:",str(recordList.count("Tails")))
All Possibilities in Coin Toss for N number of Coins
def Possible(n, a):
if n >= 1:
Possible(n // 2, a)
z = n % 2
z = "H" if z == 0 else "T"
a.append(z)
return a
def Comb(val):
for b in range(2 ** N):
A = Possible(b, [])
R = N - len(A)
c = []
for x in range(R):
c.append("H")
Temp = (c + A)
if len(Temp) > N:
val.append(Temp[abs(R):])
else:
val.append(Temp)
return val
N = int(input())
for c in Comb([]):
print(c)
heads = 1
tails = 0
input("choose 'heads' or 'tails'. ").upper()
random_side = random.randint(0, 1)
if random_side == 1:
print("heads you win")
else:
print("sorry you lose ")

Categories

Resources