How to assign keys to a word - python

Hello I'm new to programming and I'm having a hard time in giving giving an assigned key to directions.
import random
move = [
"Left!",
"Right!",
"Forward!",
"Backward!",
"Accelerate!",
"Stop!",
]
direction = random.choice(move)
print(direction)
drive = input("[keypad]> ")
What I want to do is for example if the chosen random word is "Left!" then if I click "a" for left then the program would recognize it as correct answer and feed another direction to me.
Any suggestion to my problem would greatly help me. Thank you!

You'd have to put the input in a loop for it to keep asking the user for the key. There are other ways of getting input without having to use input as that stops your entire program. I recommend looking into the keyboard library for python (https://pypi.org/project/keyboard/)

Related

Using Random Choice From Dictionary to Make An Image Appear?

Some preface:
I am using trinket. I am trying to make a tarot reading program for class. Using a nested dictionary, I have the name of each card, the facing of each card, and then a short (3-4 words) reading that is then outputted as a template for the user.
Example of nested dictionary:
card_names = {
"The Fool" : {"Up": "new beginnings, pleasure, & opportunity" , "Down" : "indecision, hesitation, & bad choices" },
"The Magician" : {"Up" : "creativity, self-confidence, & skill" , "Down" : "delay, insecurity, & lack of self-confidence" }
I then use the random.choice function to generate both a card and it's facing, like so:
card = random.choice(list(cards.card_names))
facing = random.choice(list(cards.card_names[card]))
Then it outputs a reading based on answers users put in & the randomly generated card:
print(__main__.answer_list[0] + ", your past was represented by " + random.choice(list(cards.card_names)) + ", which is facing " + random.choice(list(cards.card_names[card])) + "." " This tells me that your past relationships brought " + (cards.card_names[card][facing]) + " into your life.")
it ends up looking something like in output:
"
Em, your past was represented by The Chariot, which is facing Up. This tells me that your past relationships brought misery, greedy, & money into your life.
Now that I have the program actually working, I want to make it so that the random.choice cards that are chosen will actually show to the user, using files such as "tarot-fool.jpeg".
I made a second dictionary that looked like this:
card_images = {"The Fool": "tarot-fool.jpeg", "The Magician": "tarot-magician.jpeg"}
I hoped that I could have the program take the random.choice generated card from the card_names dictionary , parse the second dictionary for matches, and then once it found the card with matching keys, it would output the value of the second dictionary card_images, and then use the screen.bgpic() function to show users the card while they read their tarot reading output.
I tried something similar to this:
namesset = set(card_names)
imageset = set(card_images)
for name in namesset.intersection(card_images):
print name, card_images[name]
I also tried
card = random.choice(list(cards.card_names))
facing = random.choice(list(cards.card_names[card]))
key = card
key2 = cardimages.key()
value = cardimages.value()
if key in key2:
print value
just to see if I could get the program to isolate the correct value from card_images before I start trying to get them to show on screen, but I am unable to get the program to isolate the randomly selected card, remember it, and then parse the second dictionary for just that value. The code above works, but outputs every single name of every single .jpeg.
Please help! I honestly think this is something a little too complex to be using trinket for, especially with the images component. I have some experience coding outside of it but this is for a class project that we HAVE to turn in with trinket so if someone could either help me out or just tell me if this is not achievable through trinket so I can change direction a bit, it would be much appreciated.
see above for what I've tried

How to enter character(Captial Letter) and number combination using GUI automation modules?

I am doing an automation project, currently my aim is to type certain value in a data entry area of a website in an VDI environment.
The idea is to take a value from a dictionary and paste it into a website in an allocated area.
I cannot able to use selenium and pyautogui is not in this case working properly.
I use pynput key function for the entries so far.
Now the problem is, I need to enter a string like 'T123'.
I use keyboard.type('T123'), then it will only print like 123.
Shift function make all other terms different.
Either I am looking for a code which will type like 'T123' or is it possible to press Shift only for one time to enter 'T', for remaining value enter as normal.
Could someone help me with Pynput module or any other modules useful in this case?
I will show you the code below
import pyautogui
import pandas as pd
from pynput.keyboard import Controller, Key
keyb = Controller()
# click on the location to add the entry.
button = pyautogui.locateCenterOnScreen("image.png", grayscale=True, confidence=0.8)
pyautogui.doubleClick(button)
# read the excel file
df = pd.read_excel('Productlist.xlsx', sheet_name = 'Table3',na_values='n/a')
# convert into dictionaries
b = df.to_dict()
#get the data of references column from the dictionaries
b['References'].values()
#type this reference from a column ie., 'T123' to the website in VDI environment
keyb.type(b['References'][0])
When I run the code, I am only getting the result as 123, capital letter T is missing. But if I print in Python, it will be 'T123'.
I am looking for some code print this Capitalletter and numbers together.
OR
Press shift one time and enter the first digit. then release the shift and enter the remaining digits. Some code supporting it too, will be really helpful.
Any leads appreciated. Thanks

How can i create a exam generator program in python 3?

*I'm a newbie to python, I'm currently trying to create some random programs. I came accross this challenge. Would love to see how it can be solved, unfortunately I couldn't make this program.
I understand that we should use the random module and also the file handling functions in python.
If any detail is unclear I can re explain it
Write a program, which will help the user to generate exam tickets.
there are 2 files given . 1) with the exercises(exercises.txt):
it contains 30 exercises, each are already written on a new line.
2) we are given the students.txt file. Each line has a full name of a student. The program should allow the user to input the number of exercises which should be generated for the student. The new created ticket should have the students name with .txt file extension. The number must not exceed 30 exercises, if it does we should give them a new try to input the correct number. The exercises should be shuffled(randomized) .
import random
def logic():
number_input = int(input('sheiyvanet cifri'))
students_file = open('students.txt', 'r', encoding='utf8')
exercises_file = open('exercises.txt', 'r', encoding='utf8')
new_ticket_file = open('newTicket.txt', 'w')
while True:
if(number_input < 30):
new_ticket_file.write(str(random.shuffle(exercises_file.readlines())))
new_ticket_file.close()
break
else :
continue
logic()
Please do not simply provide a question and ask for it to be solved. Instead, show your current work and specify what is wrong with it.
Show examples of the text files, as in a few lines from each so that all viewers can properly understand it.
A good starting step is to write a piece of code that does only one thing. Eg:
Input a number.
The number must not exceed 30 exercises, if it does we should give them a new try to input the correct number.
Then write one that achieves a different part of your question. Try connecting these pieces. If it blows up or you really can't work it out, post a new question with the stuff you made and ask for help.

How do I choose the position of the cursor when a user is inputting information in python?

Sorry If my code seems off, this is my first time asking here and I am somewhat new to python.
I want a user to give me the number of sets and reps for a workout.
Here is my code below:
print("Please enter the number of sets you would like to do followed by the number of reps. ")
sets, reps = input("Pushup- \n\t" + "Sets: " + "Reps: ").split()
So when I run this, naturally the cursor will be flashing at the end of "reps:" however what I want it to do is so that when I run it, the cursor will flash after "sets:" and when the user hits the space key, it will move all the way over to after "reps:".
I would recommend just having it as two inputs:
sets = input("Pushup-Sets: ")
reps = input("Pushup-Reps: ")
Is there a particular reason you need it done in one line?
Why don't you try doing something like this:
print("Please enter the number of sets you would like to do followed by the
number of reps.")
print("Pushup-")
sets = input("Sets:")
reps = input("Reps:")
It uses the return button instead of the spacebar, hope it helps!
As others have suggested, having it as two separate inputs will be much easier.
If you do want to make a text-based app which does it the way you've described, the library you're looking for is called "curses" (see: howto, reference).
However, it seems like a bit of an anachronism; for a quick app, separate inputs are much easier, and for a user-friendly app you'll probably want a graphical interface (or web) rather than a text-based one.

Use generic keys in dictionary in Python

I am trying to name keys in my dictionary in a generic way because the name will be based on the data I get from a file. I am a new beginner to Python and I am not able to solve it, hope to get answer from u guys.
For example:
from collections import defaultdict
dic = defaultdict(dict)
dic = {}
if cycle = fergurson:
dic[cycle] = {}
if loop = mourinho:
a = 2
dic[cycle][loop] = {a}
Sorry if there is syntax error or any other mistake.
The variable fergurson and mourinho will be changing due to different files that I will import later on.
So I am expecting to see my output when i type :
dic[fergurson][mourinho]
the result will be:
>>>dic[fergurson][mourinho]
['2']
It will be done by using Python
Naming things, as they say, is one of the two hardest problems in Computer Science. That and cache invalidation and off-by-one errors.
Instead of focusing on what to call it now, think of how you're going to use the variable in your code a few lines down.
If you were to read code that was
for filename in directory_list:
print filename
It would be easy to presume that it is printing out a list of filenames
On the other hand, if the same code had different names
for a in b:
print a
it would be a lot less expressive as to what it is doing other than printing out a list of who knows what.
I know that this doesn't help what to call your 'dic' variable, but I hope that it gets you on the right track to find the right one for you.
i have found a way, if it is wrong please correct it
import re
dictionary={}
dsw = "I am a Geography teacher"
abc = "I am a clever student"
search = re.search(r'(?<=Geography )(.\w+)',dsw)
dictionary[search]={}
again = re.search(r'(?<=clever )(.\w+)' abc)
dictionary[search][again]={}
number = 56
dictionary[search][again]={number}
and so when you want to find your specific dictionary after running the program:
dictionary["teacher"]["student"]
you will get
>>>'56'
This is what i mean to

Categories