cant get a variable equal in a loop - python

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

Related

Looping a function that changes it's output every iteration

I'm new to python and I'm trying to create something that if the number is odd for example 7 it does this (7 * 3+1) and if it is even for example 6 it does this (6/2) but the problem is that I want to loop this but it updates the number every output from the example earlier 7 I want this to turn to (22/2) and so on and if the number 1 is reached it stops.
output = []
number = 7
def mat(self):
if (self % 2) == 0:
even = self / 2
return even
else:
odd = self * 3 + 1
return odd
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))
print(output)
this part doesn't work because it will never reach 1 and it only has 1 output (22) starting from the number 7 :
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))
To update number, you need to assign it:
number = mat(number)
The best place to do this is in the while loop:
while number != 1:
number = mat(number)
For an exercise like this, it makes sense to just print the value on each iteration rather than trying to create an array of results:
while number != 1:
print(number)
number = mat(number)
Just update the value
For while loop:
a = 0
while a<10:
print("Hello World")
a = a + 1
For for loop:
a = 0
for i in range(10):
print("Hello World")
a = a + 1
if a >= 10:
break

My current code receives an input which states how many fibonacci numbers is going to add up, but the output is wrong in one of the six test runs

The code basically receives one input which is the number of Fibonacci numbers that is going to add up. First, it generates the Fibonacci list with a for loop, and then with another for loop, it adds up the elements inside the said list.
I don't know what the problem is with the code since it's working fine with 6 test runs but there's one that is not giving the correct answer. The output my code is giving is '1', but apparently that's not correct and the test doesn't show me what the input is.
If anyone could help me by pointing out any mistakes or corrections it would be really helpful.
PS: I'm kind of new with python and coding as a whole, so if you could simplify complicated coding terms I would appreciate it :S
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the 'sumOfNFibonacciNumbers' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER n as parameter.
def sumOfNFibonacciNumbers(n):
n1,n2=0,1
fib=[]
s = 0
if n <= 0:
fib.append(0)
return 0
elif n == 1:
fib.append(1)
return 1
else:
fib.append(0)
fib.append(1)
for i in range(2,n):
x=fib[i-1]+fib[i-2]
fib.append(x)
for i in range(0,len(fib)):
s = s + fib[i]
return(s)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
result = sumOfNFibonacciNumbers(n)
fptr.write(str(result) + '\n')
fptr.close()
For now you have an incorrect result starting at index 2, regarding fibonnaci values 0 1 1 2 3 5 8
i=0 sum=0
i=1 sum=1
i=2 sum=1 should be 2
i=3 sum=2 should be 4
i=4 sum=4 should be 7
i=5 sum=7 should be 12
For loop should go to n+1 so that interval is [2;n] (n included)
Then you can simplify a bit, removing the use of fib in first if cases, and use built-in sum then
def sumOfNFibonacciNumbers(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
fib = [0, 1]
for i in range(2, n + 1):
fib.append(fib[i - 1] + fib[i - 2])
return sum(fib)

Why doesn't my program count the the last game scores?

I want to input scores of 30 matches of football game and calculate the number of the winning match and total scores. I have 30 input but it doesn't calculate the last match (30th match). What am I to do?
scores=0
win_number=0
game_number=0
x=int(input())
count=0
while count!=30 :
if x==3:
scores=scores+3
win_number=win_number+1
game_number=game_number+1
count=count+1
x=int(input())
elif x==1:
scores=scores+1
win_number=win_number+1
x=int(input())
count=count+1
elif x==0:
game_number=game_number+1
count=count+1
x=int(input())
else :
print(scores,'',win_number,game_number)
Had a little fun refactoring your code. This is what I came up with:
count = 0
scores = 0
win_number = 0
game_number = 0
while count < 30:
x = int(input())
if x not in [0, 1, 3]:
print("Wrong input - enter either 0, 1 or 3")
continue
scores += x
count += 1
game_number += 1
if x == 3 or x == 1: # is x == 1 really a win, though?
win_number = win_number+1
print(scores,'',win_number,game_number)
I will make a simplified use case to explain why your code doesnt work as you think. Imagine we only want 1 score. you set count to 0 and read the first input before your loop. So you have taken the input before the loop started. At this point the count is still set as 0. So you start your loop count != 1. This takes the input you collected outside the loop and adds to the stats. It then increments the count by 1 so the count now equals 1. You then ask for the input again. This second input is given (even though you only wanted 1 match). this input is stored in x and the first iteration of the loop ends. the loop condition count!=1 is now broken so the loop finishes after 1 iteration. so the second input which is allocated to x is never added to the stats. Which is the correct behaviour. The issue is your code structure meant that you would ask for 1 more input but never count the last one and still get 30 matches
Instead you can use a range to generate X number of iterations. Your code can also be cleaned up as there are a lot of lines that occur in each if statement these can be removed from the if and just written once in the loop.
scores=0
win_number = 0
game_number = 0
for _ in range(3):
x = int(input('score: '))
scores += x
if x == 3 or x == 1:
win_number=win_number+1
if x == 3 or x == 0:
game_number += 1
print(scores,win_number,game_number)
CONSOLE
score: 3
score: 1
score: 0
4 2 2

How to make x variable change randomly and loop (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)

Python- If statements with random numbers not working

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)

Categories

Resources