Random.randint not generating a random number in Python - python

This function (playCraps()) is supposed to choose two random integers between 1 and 6, sum them up, and return a True or False value held in x.
For some reason, each time I run the program, it always returns True with either 7 or 11.
import random
wins = [7, 11]
losses = [2, 3, 12]
def playCraps():
x = 0
while x == 0:
sumDice = random.randint(1,6) + random.randrange(1,6)
if sumDice in wins:
x = True
elif sumDice in losses:
x = False
else:
sumDice = 0
print("The sum of the dice was " + str(sumDice))
print("So the boolean value is " + str(x))
Why does this happen? And how can this be fixed?

You always get True because your while loop will execute even if x is False. 0 is a falsy value in Python. Example:
>>> x = False
>>> if x == 0:
print 'x == 0 is falsy'
x == 0 is falsy
So your loop will eventually give True no matter what. A possible solution will be to define:
x = False
while not x:
...

You won't exit the while x == 0: loop until x is equal to True.
Because 0 == x

Related

Integer palindrome [duplicate]

This question already has an answer here:
Check if a number is a palindrome - fails for 11,22 etc
(1 answer)
Closed 10 months ago.
x = int(input())
if x<0 and (x%10 == 0 and x !=0):
print("false")
rev = 0
while x>0:
rev = rev*10 + x%10
x = x // 10
if rev == x:
print("true")
else:
print("false")
Since the reversed number is the same as entered one, the condition rev == x should return true but it's giving the opposite. What am I doing wrong?
Edit 1: converting to string is not allowed
Edit 2: 🤦 I see now.
Suggestion:
x = int(input())
You are reading x by input(), so a better idea to check if it's palindrome would be reversing it:
x = input()
if (x == x[::-1]):
...
To better understand [::-1] I would suggest you to read this.
Answer:
Your while loops modifies x, so it no longer has the original input value. It exits as 0
Somebody in the comments said this, which is your real problem.
while x>0:
rev = rev*10 + x%10
x = x // 10
To be clearer I would suggest you to read this part of your code, and to wonder what will be the value of x at the end of the while loop.
You are updating the 'x' value inside the while loop, irrespective of the input x equals 0 after the while loop.
Copy x value to some temp variable after the input() and compare that in the if condition.
x = 121
x1=x
if x<0 and (x%10 == 0 and x !=0):
print("false")
rev = 0
while x>0:
rev = rev*10 + x%10
x = x // 10
#print(x1,rev)
if rev == x1:
print("true")
else:
print("false")

manipulate list in python

I'm doing a python challenge and I cannot go further...
I need to verify if the numbers in the vetor are primes.
Like:
vetor = [2,5,12]
2 is prime(TRUE)
5 is prime(TRUE)
12 not prime(FALSE)
This is my code until now:
vetor = [ ]
def is_prime():
x = vetor
if x == 1:
return False
elif x == 2:
return True
for i in range(x):
if (x % i) != 0:
return True
else:
return False
def number():
value = int(input('Write an integer number bigger than 1: '))
if value >= 1:
vetor.append(value)
return number()
elif value < 0:
return number()
elif value == 0:
return is_prime()
print(number())
But doing this, Python returns me:
TypeError: 'list' object cannot be interpreted as an integer
What could I do to manipulate that data inside my list?
Try this:
vetor = [ ]
def is_prime(x):
if x == 1:
return False
elif x == 2:
return True
for i in range(1, x):
if (x % i) != 0:
return True
else:
return False
def number():
value = int(input('Write an integer number bigger than 1: '))
if value >= 1:
vetor.append(value)
return number()
elif value < 0:
return number()
elif value == 0:
for x in vetor:
if is_prime(x):
print(x, 'is prime')
else:
print(x, 'is not prime')
print(number())
You're trying to evaluate the value of a 'whole' list (datatype) against an integer (datatype) value (1 or 2), and then you're using the whole list as it were a single integer value again. You should address every single value in the list and check it separately.
You can do it, per example, with a for-each loop:
for value in vetor:
#do wahtever you want with 'value'
I would recommend making is_prime accept an integer as an argument. Then it's just a pure function that takes in an integer and outputs a boolean value.
I also notice a problem in your is_prime implementation. In your if-else statement, the function returns no matter what during that statement, so the for loop will always stop after only one iteration. You should only return False if all of the divisors you check do note divide the number:
import math
def is_prime(n):
if n <= 1:
return False
for d in range(2, int(math.sqrt(n))+1):
if n % d == 0:
return False
return True
# >>> is_prime(7)
# True
# >>> is_prime(8)
# False
I also think it would be clearer to write your program iteratively, rather than recursively (your number function currently calls itself). This might look like
vector = []
while True:
value = int(input('Write an integer bigger than 1: '))
if value == 0:
break
elif value > 0:
vector.append(value)
for n in vector:
print(n, is_prime(n))
# prints something like:
#
# 1 False
# 2 True
# 11 True

how to print sum of primes in a list in python?

How do I print sum of primes in a list in Python?
I'm a new to Python, therefore I might be making a terrible mistake.
Please help out.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
l1 = []
l = len(l1)
i = 0
sum = 0
for i in range(0,l):
if(prime(l1[i]) is True):
sum = sum +l1[i]
print(sum)
l1 = [3,4,5,6]
print(sumprimes(l1))
Output should be equal to 8.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
sum=0
for x in l1:
if prime(x):
sum += x
return sum
l1 = [3,4,5,6]
print(sumprimes(l1))
Use the above code. You need to use the return statement to print the result of a function. And there is no need for your range() loop, there is a more elegant way to do this in python, use a for loop over all elements of the list.
You can do it using below code too.
lst = [1,2,5,7,9,10,12]
def isPrime(x):
if x == 1:
return False
for i in range(2,x-1):
if x%i == 0:
return False
return True
def getPrimeSum(l):
l = [i for i in l if isPrime(i)]
return sum(l)
print(getPrimeSum(lst))
#Check and add into the list of primeval numbers (all primeval number under a specific number)
H = int(input("What the maxium number?: "))
RangeFinding = list(range(3, H+1))
import math
Prime = [2]
for a in RangeFinding:
x = True
y = 2
while x:
NCanA = math.floor(math.sqrt(a))
if a %y == 0:
print(f'{a} is not prime')
x = False
else:
if y > NCanA:
print(f'{a} is prime')
Prime.append(a)
x = False
else:
y = y + 1
x = True
print(Prime)
#**this function will check weather number is prime or not**
def prime(k):
i = 2
j = 0
for i in range(1,k+1):
if(k % i == 0):
j = j + 1
if(j == 2):
return True
else:
return False
#**this function will add all prime numbers**
def sumOfPrimes(l1):
sum=0
for y in l1:
if prime(y):
sum += y
return sum
list1 = [3,4,5,6]
print(sumOfPrimes(list1))
**You Will get output as 8**
Explain
I have created a function prime() that will check whether numbers are prime or not.
I have created a function sumOfPrime() that will add all the prime numbers.
list1
4)Called the function sumOfPrime(list1)
I have shared a Screenshot of the code and outputProgram and Output

FizzzBuzz Python Work Through

Count up from 1. If the number is a multiple of 7 they say "zap" instead of the number. If the number has a digit of 3 in it they say "buzz" instead of the number, and if both things are true they say "zap buzz".
Devise a function zap_buzz that plays a turn of the game. Given a positive integer parameter it should either return that integer value if neither of the "zap"/"buzz" conditions hold. If some condition holds, it should return the string "zap", the string "buzz", or the string "zap buzz", whichever is appropriate. You are allowed to assume the parameter is less than 1000. As in the earlier exercises, please don't convert the integer to a string to determine its digits.
>>> zap_buzz(8)
8
>>> zap_buzz(14)
'zap'
>>> zap_buzz(13)
'buzz'
>>> zap_buzz(35)
'zap buzz'
^^^^^ is the prompt. I have gotten so far:
def zapbuzz(x):
x =0
if x % 3 == 0 and x % 7 == 0:
return str("ZapBuzz")
elif x % == 3 and x % 7 != 0 :
return str("Zap")
elif x % 3 != 0 and x % 7 == 0:
return str("Buzz")
else /* x % 3 >= 1 or x % 7 >= 1:
return x
****Please don't give me the answer, but a few good tips or maybe a "try thinking about XYZ/etc/whatevertip in a different way would be super awesome. Thank you!
okay I read through the comments, thank you for inspo!
I made the following changes:
n = input()
def ZapBuzz(n):
if n%7 == 0 & n%3 == 0:
return ("ZapBuzz")
elif n%7 == 0 & n%3 != 0:
return ("Zap")
elif n%7 != 0 & n%3 == 0:
return ("Buzz")
else:
return (n)
okay, just talked to a tutor.... I worked out the function, except the issue im having now is that when i input 1 into the function, the terminal spits out 'none'.
def zap_buzz(x):
i = 0
t = False
while i < 3:
if ((x // 10**i)%10) == 3:
t = True
i += 1
if t == True and x % 7 == 0:
return "zap buzz"
if x % 7 == 0:
return "zap"
if t == True:
return "buzz"

My is_prime function fails on 9, and I don't know why?

I have a bit of a problem. I am writing an is_prime function on, but whenever I run it, it fails on is_prime(9), and I cannot see why:
def is_prime(x):
if x < 2: ##because negative numbers, 0 and 1 are not prime##
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
else:
return True
it returns True for some reason on is_prime(9)?
That is because the function does not check all eligible divisors until it returns.
Instead, it exits early with True if x is not divisible by 2, which is not what you want for odd numbers (e.g. 9 is not divisible by 2, yet it's not prime).
Instead, you want to try all possible divisors from 2 to x-1, and then return if x is divisible by none of them.
To do so, rewrite as such:
def is_prime(x):
if x < 2: ##because negative numbers, 0 and 1 are not prime##
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
return True

Categories