How to divide variable from input by two - python

On line 7 and 14 I cant figure out how to divide the variable.
import keyboard
import random
def main(Number, Start):
Number = random.randrange(1,100)
Start = False
QA = input('Press "K" key to begin')
if keyboard.is_pressed('K'):
Start = True
input('I"m thinking of a random number and I want that number divisible by two')
print(Number)
input('Please divide this by two. *IF IT IS NOT POSSIBLE RESTART GAME*\n')
if QA == int(Number) / 2:
print('.')
else:
print('.')
main(Number=' ' ,Start=' ')

What you probably want:
Pick a random number
Make user divide this number by two (?)
Do something based on whether the guess is correct
What is wrong with your code:
You are not picking a number divisible by two. The easiest way to ensure that your number is, indeed, divisible by two, is by picking a random number and then multiplying it by two: my_number = 2 * random.randrange(1, 50). Note the change in the range. Also note that the upper limit is not inclusive, which may be not what your meant here. A typical check for divisibility by N is using a modulo operator: my_number % N == 0. If you want users to actually handle odd numbers differently, you would need to write a separate branch for that.
input returns a string. In your case, QA = input('Press "K" key to begin') returns "K" IF user has actually done that or random gibberish otherwise. Then you are checking a completely unrelated state by calling keyboard.is_pressed: what you are meant to do here is to check whether the user has entered K (if QA == "K") or, if you just want to continue as soon as K is pressed, use keyboard.wait('k'). I would recommend sticking to input for now though. Note that lowercase/uppercase letters are not interchangeable in all cases and you probably do not want users to be forced into pressing Shift+k (as far as I can tell, not the case with the keyboard package).
input('I"m thinking of does not return anything. You probably want print there, possibly with f-strings to print that prompt along with your random number.
input('Please divide this by two. does not return anything, either. And you definitely want to store that somewhere or at least immediately evaluate against your expected result.
There is no logic to handle the results any differently.
Your function does not really need any arguments as it is written. Start is not doing anything, either.
Variable naming goes against most of the conventions I've seen. It is not a big problem now, but it will become one should you need help with longer and more complex code.
Amended version:
import random
import keyboard
def my_guessing_game():
my_number = random.randrange(1, 50) * 2
# game_started = False
print('Press "K" to begin')
keyboard.wait('k')
# game_started = True
print(f"I'm thinking of a number and I want you to divide that number by two. My number is {my_number}")
user_guess = input('Please divide it by two: ')
if int(user_guess) == my_number / 2:
# handle a correct guess here
print('Correct!')
pass
else:
# handle an incorrect guess here
pass

Alternatively, you can use the modulo operator % to test whether Number is divisible by 2:
if Number % 2 == 0:
print('.')
else:
print('.')
This will check whether the remainder of Number divided by 2 is equal to 0, which indicates that Number is divisible by 2.

Related

Have some doubts in this python program (PRIME or NOT)

So, I wrote a code to find if a number is PRIME or NOT...
I wrote it in 2 different ways, they are almost same but I just had a doubt. So here it is:
1st code:
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
2nd Code:
num = int(input("Enter the number: "))
for i in range(2,num):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
The 1st code takes the input(num) and according to the input sets a limit(which is the half number + 1)
and then checks if the num is divisible by all the numbers in range (2 to lim)
The second one is same but instead of setting a limit it just checks all numbers lower than the input, which means it has to do a little more work...
Now both of these are almost same, the only difference is I saved a line in 2nd one and output efficiency is also better!
Which code would you want me to prefer/
also if this code has any problems, pointing them out would be helpful!
Thanks :)
Explanation
The most important piece of iteration, namely determining whether a number is prime or not, is to keep track of it. Without this process and in the OP's program, a variable is not used to handle this, meaning that he checks whether a number is or isn't prime every single time and concludes at that point. He also uses an else statement which is syntactically incorrect.
To prevent this, we can use a variable to keep track of this. Let's call it isprime. We need to assume that a number will always be a prime unless otherwise said. This can be achieved by setting isprime to default be True, and setting it to be False when we conclude that it is not a prime, because is has a divisor. Finally, we can check this variable at the end and determine whether that number is a prime or not, because it would be set to False if not, or left as True if it is.
Another observation made is that the limit for determining primes can be reduced down to sqrt(n). This is because we do not need to find every factor if it exists, just its lowest corresponding factor. Let's look at an example:
Factors of 24: 2, 3, 4, 6, 8, 12
We can stop checking for the factors right here:
2, 3, 4 | 6, 8, 12, 24
This is because if a number has a factor (such as greater than the square root), it will have a corresponding factor less than the square root. As a result, we can set our limit to be sqrt(n), just for peace of mind + a time complexity of O(sqrt(n)) v. O(n).
As an extra note, sqrt is not inbuilt into Python. You will have to import it from the math library using:
from math import sqrt
Final Code
# Setup
num = int(input("Enter the number: "))
lim = sqrt(num)
isprime = True
# Loop & check
for i in range(2,lim):
if num % i == 0:
isprime = False
break
# Results
if isprime:
print("Prime!")
else:
print("Not prime!")
The logic of the solution is wrong. You gave to switch the "Prime" and "Not Prime" tags. Like follows;
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Not Prime!")
break
else:
print("Prime!")
The solution 1 is more efficient because you do not need to do extra
computation to check num//2 + 1. So it is preferable.

How to display an integer many times

I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)

Using Astericks to Display a Bargraph of User Inputted Numbers in Python

I am currently attempting to solve a homework problem. The problem states to collect user inputted numbers and then arrange them using asterisks to display a graph, with the largest number having forty asterisks and the rest becoming smaller as the numbers decrease.
_NumberList= []
print("Please type 'quit' to stop entering numbers.")
print("Please type 'print' to view the list that has been entered so far.")
a= True
while a:
_number= input("Please enter a number or make a selection. ")
if _number.isdigit():
_number=int(_number)
_NumberList.append(_number)
elif _number.isalpha():
_number= _number.lower()
if _number== 'quit':
a= False
if _number== 'print':
print(_NumberList)
else:
print("Please use digits to enter a number.")
print("For exmaple: 'ten' should be typed at '10'")
else:
print("Invalid entry.")
_NumberList.remove(max(_NumberList))
for i in range(len(_NumberList)):
_NumberList.remove(max(_NumberList))
However, I am unsure as to how to find the given proportions utilizing the numerical data. Thus far, I have considered utilizing the .pop function, but it simply isn't making a ton of sense so far. I considered making them go up by one step, but again, that doesn't seem logical, and the program can run for more than forty numbers. I know I will need to utilize a loop, hence the for loop at the end, but I'm not sure as to how to continue from there.
Your variable name _NumberList makes my eyes hurt, so I'll call it number_list
largest_number = max(number_list)
scale_factor = 40 / largest_number
scaled_number_list = [int(x * scale_factor) for x in number_list]
for scaled_number in scaled_number_list:
print('*' * scaled_number)

Construct a game so that two random numbers appear and the user has to choose which one is bigger

AIM: Construct a game so that two random numbers appear and the user has to choose which one is bigger
This is what I have but I don't know how to make it so the code can realise if the user has guessed the bigger number or not.
#Ask the user to input his/her name in which will be used in the
#opening comments about the game and how to play it
user_name=str(input("Please type in your name: "))
#print instructions
print('''Hello {}! Welcome!
This game is going to develop your number skills!
So here is how to play:
Firstly, {}, we are going to give you two numbers.
Then you must choose which of these numbers you think is the biggest.
Type this number in and we will tell you if you are right.
Get enough right and you can progress TO THE NEXT LEVEL!!!''' .format(user_name, user_name))
#RUN MODULE TO CHECK IF THE TEXT IS BEING PRINTED AND THE USERS NAME IS BEING SHOWN IN SPACE OF THE {}
#level 1
#import a random number
import random
a1 = random.randint(1, 10)
a2 = random.randint(1, 10)
#Making sure the integers are not the same
while a1 == a2:
a2 = random.randint(1, 10)
print('''
The two random values are {} and {}.
Which one do you think is bigger? ''' .format(a1, a2))
#RUN MODULE TO CHECK IF THE IF TWO NUMBERS ARE BEING PRODUCED AND ARE DIFFERENT, MAKING SURE THESE PRINT THROUGH THE THE PRINT STATEMENT.
The simplest thing you can do is ask for the value of the biggest number, and compare it to the biggest number:
biggest = max(a1, a2)
user_num = int(input("What is the biggest number?"))
if user_num == biggest:
print('Correct!')
else:
print('Wrong! The biggest number is {}'.format(biggest))
Note the use of int() for converting the input to integer before testing for equality.
The question you are asking your user is to choose one of two possible outcomes (bigger of smaller). You could say enter 1 if the first number is bigger than the second return if not.
k=raw_input("Enter 1 if first number bigger, else return: ")
the question is a choice between two outcomes.
You can alter your question slightly to generate a 1 or a zero using the random function then ask; Is a mystery number I have chosen a 1 or a zero enter 1 or 0
# do this code
a = raw_input()
# gets user input
if a1 > a2:
if a == a1:
print ('you got it right')
break
# all the ifs check if it is right or wrong
if a != a1:
print ('you got it wrong try again')
a = raw_input()
# then right this same code again but change if a1 > a2: do if a2 > a1: sorry if it does not work

Python Number Game

This is a piece of code that allows the user to choose a number and the computer guesses the number. However, when the computer is guessing it sometimes guesses the same number more than once. How do I stop the computer from guessing a number it has already guessed.
import random
print('This is a game where the user chooses\n' +
'a number for the computer to guess.')
guess = random.randint(1, 50)
number = int(input('\n\nChoose a number between 1 and 50: '))
while guess != number:
if guess > number:
guess = random.randint(number, 50)
else: guess < number
guess = random.randint(1, number)
print(guess)
input('Enter to see the next number')
print('The computer guessed your number:', guess,'!')
input('\n\n\nPress enter to exit!')
without rewriting other aspects of your game...
try this for not choosing the same number twice:
numbers = range(1,51)
ind = random.randint(0, len(numbers)-1)
guess = numbers[ind]
numbers.remove(ind+1)
numbers will contain only the list of unguessed numbers in the range to be guessed
(and won't take forever to find the unguessed number when you have a list of 49 guessed numbers!)
[EDIT] and from the comment below:
numbers = range(1,51)
guess = numbers.pop(random.randint(0,len(numbers)-1))
You can keep a cache of all of the numbers that the computer has guessed. Maybe using a dict or list or something.
However, this doesn't prevent the computer from guessing the same number (it just means it'll pick another number if it's already seen it).
If you want to NEVER guess the same number twice, you need to randomly draw numbers from a fixed set of numbers and then remove the number from the set. This guarantees that you will never pick the same number twice. However, depending on the number of candidates, this may or may not be a feasible solution (for example, if there are infinite number of possibilities).
The problem is you are only keeping the last guess information and guessing between that and the max or min of the total range. This will maintain the same approach but restrict guesses based on already knowing if its higher or lower then numbers already guessed.
max_guess = 50
min_guess = 1
guess = random.randint(min_guess, max_guess)
while guess != number:
if guess > number:
max_guess = guess - 1
else:
min_guess = guess + 1
guess = random.randint(min_guess, max_guess)
Do you want real random numbers and you are connected to Internet? https://pypi.python.org/pypi/randomdotorg/
I suggest also playing with random.seed or/and random.choice(range(min,max))
You could try this:
#!/usr/bin/env python
import random
print('This is a game where the user chooses a number for the computer to guess.')
guesses = range(1,51)
random.shuffle(guesses)
number = int(input('\n\nChoose a number between 1 and 50: '))
while True:
guess=guesses[0]
print "The computer guessed %d" % (guess)
if guess > number:
guesses=[x for x in guesses if x<guess]
elif guess < number:
guesses=[x for x in guesses if x>guess]
else:
break
print('The computer guessed your number!')
We'll store all possible guesses and randomize their order. Then we'll use information from the user to progressively eliminate potential guesses. We don't have to reshuffle or choose random numbers as we go because removing elements from a randomly ordered array maintains the "randomness" of the next element we'll pull from it.
While fixing the range on your random.randint() call would also resolve the problem (and in a cleaner fashion), the method I describe offers an alternative approach which is more general (say, for instance, if the user suddenly tells you that their number is odd).
Since this appears to be the "greater than, less than" game, I propose that the issue can be resolved by fixing the logic used for the range supplied to the random generator.
The computer should never guess from the same range twice as any choice the computer makes will always be "higher" or "lower" or "equal" to the number being sought - this information should be used to update the range of the next random number chosen. The updated range excludes the previous random guess.
Using number in the random range selection is wrong because it is independent of the guess made; it is simply what is being sought. You probably want two additional variables, minGuess and maxGuess, that are updated each loop and are used to limit the range of the random values.
Try to play the game against another person - how do you quickly "guess" the right number? If you're playing for minimum "guesses", you'll always divide the range directly in half, but you can pick randomly from the remaining range like the computer does (or should).

Categories

Resources