This probably sounds stupid but I can't seem to make a basic counter. Basically I need it to have two real time inputs, keyboard 'f' for positive points, keyboard 'j' for negative points, then I need one more input 'q' to stop the iteration and then print how many times f and j keys were pressed respectively.
edit: Okay this is frustrating. I searched around more to find out that for real time input I need msvcrt module, I used Windows so no problem. But, it still doesn't do anything, the code just runs and exit, nothing happens.
Here is what I want to do:
1. Run the code.
2. Open up a freestyle video in background.
3. Press the j and f key on the keyboard respectively in real time to count the freestyle score, it's based on clicks, positive points (j) and negative points (f).
4. Video ends, I press q to print how many times I pressed j and f key.
import msvcrt
def counter():
negative = 0
positive = 0
while True:
score = input("input starts:")
if msvcrt.getch() == "f":
negative += 1
print(negative)
if msvcrt.getch() == "j":
positive +=1
print(positive)
if msvcrt.getch() == "q":
print ("positive", positive)
print ("negative", negative)
break
There are plenty of issue, but here are a few pointers.
Instead of num = num + 1 - use num +=1
Define your counters before incrementing them.
Move your input inside the loop, or else it's going to use the first input over and over and just run through the entire loop with one input.
def counter():
end=1
negative = 0
positive = 0
while end <= 1000:
end += 1
score = input("input here:")
if score == "f":
negative += 1
print(negative)
if score == "j":
positive +=1
print(positive)
if score == "q":
print ("positive", positive)
print ("negative", negative)
break
counter()
You have to define positive and negative outside the while loop to keep the changes made to these variables during each iteration. E.g. like so:
def counter():
score = input("input here:")
end=1
positive = 0
...
There's a small typo in positive==positive+1. I think you meant positive=positive+1 (comparison vs. assignment)
The general syntax of your counter is correct though if you want something to be running in the background and are operating outside of the console then you need something like pyHook. getch() wont work in this situation.
from pyHook import HookManager
from win32gui import PumpMessages, PostQuitMessage
class Keystroke_Watcher(object):
def __init__(self):
self.hm = HookManager()
self.hm.KeyDown = self.on_keyboard_event
self.hm.HookKeyboard()
def on_keyboard_event(self, event):
try:
if event.KeyID == keycode_youre_looking_for:
self.your_method()
finally:
return True
def your_method(self):
pass
def shutdown(self):
PostQuitMessage(0)
self.hm.UnhookKeyboard()
watcher = Keystroke_Watcher()
PumpMessages()
that will detect the keypress and then you can increment the values. Of course you'll need to extrapolate the code but the framework is all there for you to be successful.
Related
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.
I am new to python and am doing a basic quiz. I'm running into a problem for scoring.
trials = 3
for i in range(trials):
ans_2 = ansTwo()
results.append(ans_2)
if ans_2 in ('c','C'):
print("Good Job",name)
score+=1
break
else:
remaining = trials-i-1
s = '' if remaining == 1 else 's'
print("Oops Try Again? [{0} Chance{1} Remaining]".format(remaining, s))
This is my code and I'm trying to make it that if they do not get the answer the first time they do not get any points, but if they get the answer the first time they get a point.
Just add an if statement before score += 1 that checks if the loop is running for the first time. In your case:
if i == 0:
score += 1
okay, so the task I am attempting to complete is:
"Write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total. When a blank line is entered, the program should print the average of all the numbers entered. You need to use a break statement to exit the while loop."
How would I go about doing this?
counter = 0
total = 0
while True:
value = input("enter value:")
if(value == " "):
break
else:
counter += 1
total += float(value)
print(total/counter)
python type casting
Okays so I'm new to python and I just really need some help with this. This is my code so far. I keep getting a syntax error and I have no idea what im doing wrong
count = int(input("What number do you want the timer to start: "))
count == ">" -1:
print("count")
print("")
count = count - 1
time.sleep(1)
You need to ensure you import the time library before you can access the time.sleep method.
Also it may be more effective to a for use a loop to repeat code. The structure of your if statement is also incorrect and is not a correct expression.
IF <Expression> is TRUE:
DO THIS.
Also consider using a range within your for loop see below;
import time
count = int(input("What number do you want the timer to start: "))
for countdown in range(count,0,-1):
print (countdown)
time.sleep(1)
Explanation;
for countdown in range(count,0,-1):
range (starting point, end point, step) . Starts at your given integer, ends at 0, steps by -1 every iteration.
In the 2nd line, you can't deduct 1 from ">" which is a string.
What you need here is apparently a for loop. EDIT: You forgot the import too!
import time
count = int(input("What number do you want the timer to start: "))
for i in range(count):
print("count")
print(i)
count = count - 1
time.sleep(1)
The syntax error presumably comes from the line that reads
count == ">" -1:
I'm not sure where you got that from! What you need is a loop that stops when the counter runs out, and otherwise repeats the same code.
count = int(input("What number do you want the timer to start: "))
while count > 0:
print("count", count)
print("")
count = count - 1
time.sleep(1)
You could also replace count = count -1 with count -= 1 but that won't make any difference to the operation of the code.
First, you must import time in order to use the time.sleep() function
Next, I'm not too sure what you mean by:
count == ">" -1:
If you're creating a "stopwatch", then it would be logical to use some sort of a loop:
while count > 0:
print(count,"seconds left")
count -= 1
time.sleep(1)
print ("Finished")
That should work fine.
There is a syntax error in your second line. I am not sure what you are trying to achieve there. Probably you want to check if count>-1.
do this:
import time
count = int(input("What number do you want the timer to start: "))
if count>0:
while(count):
print(count)
time.sleep(1)
count = count -1
I'm a bit new to python and was giving myself a task, I wanted a number guessing game that gets you to guess four numbers and the program will keep telling you how many numbers you guess right till you guess the full list of numbers.
running = True
import random
def compareLists(a, b):
return list(set(a) & set(b))
def start():
rNums = random.sample(range(10), 4)
gNums = []
print("Get ready to guess 4 numbers!")
for i in range(0, 4):
x = int(input("Guess: "))
gNums.append(x)
print("You guessed: ", gNums)
comparison = len(compareLists(rNums, gNums))
while gNums and rNums:
if gNums != rNums:
print("You guessed " + str(comparison) + " numbers right, keep guessing!")
break
elif gNums == rNums:
print("What amazing luck!")
while running:
start()
The problem is that when I use a break a new list of 4 numbers is created, I want python to just go back to the start of the loop and not make a whole new list!
You want to use continue. Try it with a toy example:
i = 0;
while i < 10:
i += 1
if i % 2 == 0:
continue
print i
Output:
1
3
5
7
9
You can put the
rNums = random.sample(range(10), 4)
outside the loop and pass rNums to start. This way you will have the same four numbers in the list. Hope this helps
For the sake of minimizing the amount of loops going on in your code, I would probably first pop your random numbers in a dictionary.
Something like this (probably more efficient way of doing this...but it's the first thing that popped in my head):
from collections import Counter
d = Counter(random.sample(range(10), 4))
Start your while loop, and keep asking the user to guess. Every time they make a right guess, just perform this operation:
d.pop(correctly_guessed_num)
Once your dictionary is empty, you are done and you break the loop.
EDIT adding my quick stab at the implementation. Not fully thought through, might be some edge cases that break this...but this is the overall idea. Hope it helps.
from collections import Counter
import random
d = Counter(random.sample(range(1, 10), 4))
size = len(d) - 1
while True:
x = int(input("Guess: "))
if size == 0:
print("you guessed them all, way to go")
break
if x not in d:
print("keep going buddy")
continue
else:
d.pop(x)
size -= 1
print("A right guess")