Python- If statements with random numbers not working - python

I'm very new to programming and I'm trying to write a program in python 3.6 that generates a random number as an "answer" and then the computer has to guess that answer for x number of questions. To keep track of how many questions the computer guesses right, I created a variable called 'right' and if the computer's answer equals the guess, then add one to that variable. However, it does it everytime even if it's wrong. Sorry if this seems stupid, but thank you for your help
import random
def total(x, t):
for i in range(t):
cor = 0
gue = 0
n = 0
right = 0
def ans():
cor = random.randint(1,4)
print(cor, 'answer')
def guess():
gue = random.randint(1,4)
print(gue, 'guess')
while n <= x:
ans()
guess()
if cor == gue:
right += 1
n += 1
print(right, n)

I tried to slightly modify your code by moving the ans() and guess() functions outside the total(x,t) function since they seem independent from each other. Previously ans and guess were generating cor and gue randomly but not returning their values to be used in the if statement which was always using the initial values of 0. Now by saving the returned values as cor = ans() and gue = guess(), the initialised values of 0 for cor and gue are overwritten.
import random
def ans():
cor = random.randint(1,4)
print(cor, 'answer')
return cor
def guess():
gue = random.randint(1,4)
print(gue, 'guess')
return gue
def total(x, t):
for i in range(t):
cor = 0
gue = 0
n = 0
right = 0
while n <= x:
cor = ans()
gue = guess()
if cor == gue:
right += 1
n += 1
print(right, n)
print (total(2,3))
Output
1 answer
2 guess
3 answer
4 guess
1 answer
4 guess
0 3
3 answer
2 guess
1 answer
4 guess
3 answer
2 guess
0 3
2 answer
2 guess
2 answer
3 guess
3 answer
4 guess
1 3

Nesting functions like ans and guess can be useful but I'd steer clear of it while beginning programming. It makes your program harder to understand.
Here's my stab at what you are trying to do (if I've understood correctly!)
import random
# Play number_of_games_to_play of the number guessing game allowing a maximum of max_guesses per game played.
def play(number_of_games_to_play, max_guesses):
num_games = 0
guessed_right = 0
while num_games < number_of_games_to_play:
if guess_number(max_guesses):
guessed_right += 1
num_games += 1
print('\n\nI played', num_games, 'games and guessed right', guessed_right, 'times')
# Generate a random number, try and guess it up to max_guesses times. Returns whether the number was guessed correctly or not.
def guess_number(max_guesses):
answer = random.randint(1, 4)
print('\n\nPlaying guess_number. The right answer is', answer)
num_guesses = 0
while num_guesses < max_guesses:
guess = random.randint(1, 4)
print('The computer guesses', guess)
if guess == answer:
print('That is right!')
return True
else:
print('That is wrong')
num_guesses += 1
return False
play(number_of_games_to_play = 5, max_guesses = 4)

I think the you are having problems with the scope of the variables: cor and gue inside the functions are different from those outside them. Your functions are not changing the values of cor and gue, they are creating two new variables (named also cor and gue) that live only within them. For that reason, cor and gue are always 0, the condition in the if statement is always true, and you increment rigth every time.
To solve this issue, you could pass the variables as parameters to the functions.

The problem comes from variable scope. The variable core defined in method ans is different from variable core initalized in the for loop.
A better way is to do:
import random
def ans():
c = random.randint(1, 4)
return c
def guess():
g = random.randint(1, 4)
return g
def total(x, t):
for i in range(t):
n = 0
right = 0
while n <= x:
cor = ans()
gue = guess()
if (cor == gue):
right += 1
print("Answer: %6d Guess: %6d Right: %d" % (cor, gue, right))
n += 1
print(right, n)

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.

Factors of a number using Python recursive function

I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)

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

Monte Carlo simulation of amoeba population

I came across a brain teaser problem. Im trying to simulate it, but having trouble getting the answer. The problem goes like this: there is one amoeba. every minute, an amoeba either may die, stay the same, split into 2 or split into 3 with equal probability. All of its offspring will behave the same way, independent of other amoebas. What is the probability that amoeba population will die?
My implementation in python:
import numpy as np
def simulate(n):
prob = np.array([0.25]*4)
ans = np.random.choice(np.arange(4),1,p=prob)
if ans == 0:
n = n - 1
if ans == 1:
pass
if ans == 2:
n = n * 2
if ans == 3:
n = n*3
return n
count = 0
for i in range(10000):
nold = 1
while True:
nnew = simulate(nold)
if nnew == 0: #amoeba has died
count += 1
break;
nold = nnew
Im getting an infinite loop. Can anybody help? thanks. The answer is 41%
The While loop needs to have some sort of breakpoint.
You have not set what is False.
while count < 10000:
...

working with negative numbers in python

I am a student in a concepts of programming class. The lab is run by a TA and today in lab he gave us a real simple little program to build. It was one where it would multiply by addition. Anyway, he had us use absolute to avoid breaking the prog with negatives. I whipped it up real quick and then argued with him for 10 minutes that it was bad math. It was, 4 * -5 does not equal 20, it equals -20. He said that he really dosen't care about that and that it would be too hard to make the prog handle the negatives anyway. So my question is how do I go about this.
here is the prog I turned in:
#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")
#standing variables
total = 0
count = 0
#output the total
while (count< abs(numb)):
total = total + numa
count = count + 1
#testing statements
if (numa, numb <= 0):
print abs(total)
else:
print total
I want to do it without absolutes, but every time I input negative numbers I get a big fat goosegg. I know there is some simple way to do it, I just can't find it.
Perhaps you would accomplish this with something to the effect of
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.
if b > 0:
num_times = b
else:
num_times = -b
total = 0
# While loops with counters basically should not be used, so I replaced the loop
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
total += a
# We do this a times, giving us total == a * abs(b)
if b < 0:
# If b is negative, adjust the total to reflect this.
total = -total
print total
or maybe
a * b
Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if numb is negative. If it is then multiply numa by -1 and do numb = abs(numb). Then do the loop.
The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb is negative.
So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.
#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")
#standing variables
total = 0
#output the total
for count in range(abs(numb)):
total += numa
if numb < 0:
total = -total
print total
Try this on your TA:
# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)
for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
print numa, numb,
accum = 0
negate = False
if numa < 0:
negate = True
numa = -numa
while numa:
if numa & 1:
accum += numb
numa >>= 1
numb <<= 1
if negate:
accum = -accum
print accum
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
How about something like that? (Uses no abs() nor mulitiplication)
Notes:
the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)
def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
if abs(a) > abs(b):
a, b = b, a # optimize by reducing number of iterations
total = 0
while a != 0:
if a > 0:
a -= 1
total += b
else:
a += 1
total -= b
return total
multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12
Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
#this is apparently a better way of getting multiple inputs at the same time than the
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])
#standing variables
total = 0
if numb > 0:
repeat = numb
else:
repeat = -numb
#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
total += numa
#check to make sure the output is accurate
if numb < 0:
total = -total
print total
Thanks for all the help everyone.
Try doing this:
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans = num1*num2
if num1 > 0 or num2 > 0:
print(ans)
elif num1 > 0 and num2 < 0 or num1 < 0 and num1 > 0:
print("-"+ans)
elif num1 < 0 and num2 < 0:
print("Your product is "+ans)
else:
print("Invalid entry")
import time
print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')
x = int ( input (':'))
y = int ( input (':'))
z = 0
print ()
while x > 0:
print (':',z)
x = x - 1
z = y + z
time.sleep (.2)
if x == 0:
print ('Final answer: ',z)
while x < 0:
print (':',-(z))
x = x + 1
z = y + z
time.sleep (.2)
if x == 0:
print ('Final answer: ',-(z))
print ()

Categories

Resources