Why are applying log function? - python

import random
import math
low = int(input("Enter Lower number:- "))
up = int(input("Enter Upper number:- "))
# generating random number between the given numbers
x = random.randint(low, up)
print("\n\tYou've only ", round(math.log(up - low + 1, 2)),
" chances to guess the integer!\n")
# Initializing the numberof times
count = 0
# for calculation of minimum guess
while count < math.log(up - low + 1, 2):
count += 1
# taking guessing number as input
guess = int(input("Guess a number:- "))
# testing
if x == guess:
print("Congratulations you did it in ", count, " try")
# Once guessed, loop will break
break
elif x > guess:
print("You guessed too small!")
elif x < guess:
print("You Guessed too high!")
# If Guessing is more than required guesses
if count >= math.log(up - low + 1, 2):
print("\nThe number is %d" % x)
print("\tBetter Luck Next time!")
can any one explain this line math.log(up - low + 1, 2)) , why is this log function and comma 2

The idea behind is that you can find the solution using binary search https://en.m.wikipedia.org/wiki/Binary_search_algorithm
The 2 in the logarithm argument is the logarithm base.

Related

While loop spamming output instead of printing output once?

I'm making a regular guess the number game. I'm having problems when I enter the guess and the program spams lower or higher instead of just typing it once, since I'm using a while True loop.
Here I'm just opening the CSV file and picking a random number.
import random
numbers = open('numbers_1-200.csv').read().splitlines()
number = int(random.choice(numbers))
Here I'm importing numbers 1-50 and picking two random numbers which will be what's added and subtracted from the original number. So the computer can write two numbers where the original number is between.
I know I could have just made the program pick two numbers from the first fifty lines in the same CSV that includes numbers from 1-200 but I choose to make another CSV which only had the numbers 1-50.
differences = open('numbers_1-50').read().splitlines()
difference = int(random.choice(differences))
difference2 = int(random.choice(differences))
clue = number + difference
clue2 = number - difference2
This is my welcome screen which also includes the main program on the last row¨
def welcome_screen():
print('The number is between ' + str(clue) + ' and ' + str(clue2))
print('Guess the number: ')
guess_the_number()
This is my loop where you guess the number
def guess_the_number():
guess = int(input())
while True:
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')
I'm getting outputs like these:
The number is between 45 and 97
Guess the number: 72
lower
lower
lower
lower
lower
lower
lower
lower
How can I get a output where it just says "lower" (or "higher") one time and then I can guess again?
Just move the input function inside the while loop:
def guess_the_number():
while True:
guess = int(input())
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')
def guess_the_number():
while True:
guess = int(input())
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')

Python Game Of Chance

I have a school project for making a betting programme. It asks for the account balance and checks if the user can play more or tells them to stop if they are broke. I do not know how to add a while loop that checks if they have enough money to play again and asks them if they want to play again.
The code is below:
import random
for x in range (1):
x=random.randint(1,31)
point=int(0)
savings = int(input("Enter your total amount of money you have in your bank account"))
betmoney = int(input("Enter the money you are betting"))
num = int(input("Enter a number between 1 and 30"))
bef = (savings - betmoney)
if num == x:
print ("you have guessed the mystery number well done. Your earnings just got multiplied by 6")
point = point + 6
import random
for x in range (1):
x=random.randint(1,31)
if num % 2 == 0:
print("since your number is even, you get double your money back")
point = point + 2
else:
point = point + 0
if num % 10 == 0:
print("since your number is a multiple of 10 you get 3x your money back")
point = point + 3
else:
point = point + 0
for i in range(2,num):
if (num % i) == 0:
point = point +0
break
else:
print(num,"is a prime number so you will get 5x your money back")
point = point + 5
if num < 5:
print("since your number is lower than 5 you get double your money back")
point = point + 2
else:
point = point + 0
else:
print("unfortunatley you have nor guessed the right mystery number. better luck next time.")
win = (point * betmoney)
aft = (bef + win)
print ("Your bank account after playing is now" , aft)
print ("You have won" , win)
print ("btw the mystery number was" , x)
I added a while loop and i came up with this.
The following is the code:
import random
point = int(0)
savings = int(input("Enter your total amount of money you have in your bank account : "))
play = bool(True)
while savings > 0 and play:
for x in range (1):
x = random.randint(0, 30)
betmoney = int(input("Enter the money you are betting : "))
if savings >= betmoney:
savings = savings - betmoney
else:
print("Please enter an amount less than ", savings)
continue
num = int(input("Enter a number between 1 and 30 : "))
if num == x:
print("you have guessed the mystery number well done. Your earnings just got multiplied by 6")
point = point + 6
import random
for x in range (1):
x = random.randint(1, 31)
if num % 2 == 0:
print("since your number is even, you get double your money back")
point = point + 2
else:
point = point + 0
if num % 10 == 0:
print("since your number is a multiple of 10 you get 3x your money back")
point = point + 3
else:
point = point + 0
for i in range(2,num):
if (num % i) == 0:
point = point +0
break
else:
print(num,"is a prime number so you will get 5x your money back")
point = point + 5
if num < 5:
print("since your number is lower than 5 you get double your money back")
point = point + 2
else:
point = point + 0
else:
print("unfortunatley you have nor guessed the right mystery number. better luck next time.")
win = (point * betmoney)
aft = (savings + win)
print("Your bank account after playing is now", aft)
print("You have won", win)
print("The mystery number was" , x)
if savings > 0:
play = bool(input("Do you want to play again (Y/N)? "))
print("You have no more money left. You are broke. Thanks for playing though!")
If you are using an if statement, you could try something by setting a stopping point for the amount of money you need to play (e.g. you must have $1,000 to play).
For now, let's assume that you need $1000 dollars to play, and we'll call that in your already present variable aft. The code would be something along the following:
while aft > 1,000:
#confirms that the user can play
print("You can play! Have fun!")
#(Enter your current code here)
if aft <1,000:
print("Sorry, but your current value of " + aft + "is not enough to play. Please earn more money.")
exit()

Guess Random Number Why i m not able to enter input - python

Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).

how to make a python program using "while" to print at 0?

My assignment is to make a program that prompts the user to input numbers to be categorized as even or odd. It will then add them together and count the amount of inputs of evens or odds. So far, I have that down, but I can't figure out how to get my program to run through the outputs when 0 is typed in.
Here's my code:
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
sum = float(count_odd) + float(count_even)
while number >= 0:
if number%2 == 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number == zero:
print("Sum of odds: " +odd_sum)
print("Sum of evens: " + even_sum)
print("Odd count: " +count_odd)
print("Even count: " +count_even)
print("Total positive int count:" +sum)
else:
number = int(input("Input an integer (0 terminates the program): "))
I'm not even sure the ending is right at all. Especially not my attempt at creating a "zero."
Your current program does not work because 0 % 2 is also 0 , so it will go into the if block and it will never reach the elif number == zero: block.
You should move your elif to the top to become an if and move the if to elif , for your logic to work. and also, if you want to loop to break at 0 , you should add break statement in the number == zero block. Example -
while number >= 0:
if number == 0:
print("Sum of odds: ", odd_sum)
print("Sum of evens: ", even_sum)
print("Odd count: ", count_odd)
print("Even count: ", count_even)
print("Total positive int count:", even_sum + odd_sum)
break
elif number%2 == 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
Other issues that I noticed in your program -
"Sum of odds: " +odd_sum would not work because you cannot add int and string like that, instead pass them as separate arguments to the print .
You do not need the else: part, as it would never reach there.
When you input "0", this condition is true as well:
if number%2 == 0:
So your program counts the "0" as a valid input (an even number).
Try comparing with zero first, then the rest of the ifs.
Also, you should use a "break" to end the program when "0" is inputted.
Try this version:
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
sum = float(count_odd) + float(count_even)
while number >= 0:
if number == zero:
print("Sum of odds: ", odd_sum)
print("Sum of evens: ", even_sum)
print("Odd count: ", count_odd)
print("Even count: ", count_even)
print("Total positive int count:", sum)
break
elif number%2 == 0:
print "a"
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
else:
number = int(input("Input an integer (0 terminates the program): "))
I made some changes and addressed them with comments, the main problem was that you should have been checking for zero with the first conditional statement in your while loop.
# Setup your variables
# I removed the input line from here, since we only need to get input in the while loop
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
# Use a simple boolean flag to tell the while loop to keep going
keep_going = True
while keep_going == True:
# Grab the number from the user
number = int(input("Input an integer (0 terminates the program): "))
# IMPORTANT - Check for zero first
# If it is zero, set out flag to false, so we will exit the while loop
if number == 0:
keep_going = False
elif number % 2 == 0:
count_even += 1
even_sum += number
elif number % 2 != 0:
count_odd += 1
odd_sum += number
# Here we have exited the while loop
sum = float(count_odd) + float(count_even)
# Print everything here
To fully make your script function you'll need this:
import sys # allows the script to end after 0 properly
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
summation = float(count_odd) + float(count_even) # don't use sum because it's already taken by python, and you can also remove it, see below why
while number >= 0:
if number%2 == 0 and number != 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number == 0: # pay attention to the concatenation of strings, not string and integer
print("Sum of odds: " + str(odd_sum))
print("Sum of evens: " + str(even_sum))
print("Odd count: " + str(count_odd))
print("Even count: " + str(count_even))
summation = float(count_odd) + float(count_even)
print("Total positive int count:" + str(summation)) # add everything up after it's been done NOT before
sys.exit() # to stop your infinite loop
else:
number = int(input("Input an integer (0 terminates the program): "))

how do i edit this newton method in python to loop until the difference between consecutive guesses is less than 0.00001?

how do i edit this newton method in python to loop until the difference between consecutive guesses is less than 0.00001?
import math
def main():
x = eval(input("Enter the number to calculate square root of: "))
guess = x/2.0
print ("Initial guess is", guess)
n = eval(input("How many times to improve the guess: "))
print()
for cnt in range(n):
guess = (guess+x/guess)/2
print ("Improvement", cnt+1, ": next guess is", guess)
print()
print ("The final guess is", guess)
print ("math.sqrt(x) returns", math.sqrt(x))
main()
You could break out of the loop:
for cnt in range(n):
old_guess = guess
guess = (guess + x/guess)/2
print ("Improvement", cnt+1, ": next guess is", guess)
if abs(old_guess-guess) < 0.00001:
break
print()
print ("The final guess (after {0} improvements) is {1}".format(cnt+1, guess))
print ("math.sqrt(x) returns {0}".format(math.sqrt(x)))
I would use an infinite loop with a break on a condition :
def main():
x = float(input("Enter the number to calculate square root of: "))
guess = x/2.0
print ("Initial guess is", guess)
delta = float(input("Required precision : "))
print()
cnt = 0
while True:
old = guess
cnt += 1
guess = (guess+x/guess)/2
print ("Improvement", cnt+1, ": next guess is", guess)
if abs(guess - old) < delta: break
print()
print ("The final guess is ", guess, " in ", cnt, " passes")
print ("math.sqrt(x) returns", math.sqrt(x))

Categories

Resources