connecting a variable output to send Keys string - python-3.x

I am trying to generate a random number that is six digits and then submit that 6 digit out put to a website.
here is my code:
send_code = self.chrome_browser.find_element_by_xpath("/html/body/div[1]/section/div/div/div[3]/form/span/button").click()
random_num = random.randrange(000000, 999999)
(f'{random_num:06}')
send_random_num = self.chrome_browser.find_elements_by_xpath('/html/body/div[1]/section/div/div/div[2]/form/div/input')
random_num.send_keys(Keys.random_num, Keys.ENTER)
the generating the random number is working but for some reason my send_random_num variable is not executing the right commands. I feel like I am formatting this wrong. Keys.(var) just isn't close to right so any suggestions? thanks (using selenium)

To me, it looks like you are using selenium. Maybe next time try adding that as a tag or clearly stating what module you are using. I believe this will work, and I took the liberty clarifying some of your variable names:
button = self.chrome_browser.find_element_by_xpath("/html/body/div[1]/section/div/div/div[3]/form/span/button")
button.click()
random_num = random.randrange(000000, 999999)
random_code = (f'{random_num:06}')
input = self.chrome_browser.find_elements_by_xpath('/html/body/div[1]/section/div/div/div[2]/form/div/input')
input.send_keys(random_code)

Related

append() not working corretly in IF statement

Im only about a month into python so still learning and I cant see a similar question or more like problem. I have a list and dictionary that I want to add new entries to. When I run this code:
n = input('Enter variable name to check: ')
varDict = {} #Key = label and Value = description
valList = [] #Lists the referenced values from the code
if n in varDict:
print(varDict[n])
print(valList[n])
if n not in varDict:
new = input('Not found, make new entry?')
if new == 'yes':
desc = input('Enter description: ')
varDict[n] = desc
valList.append(n)
print(n, 'has been added to the list')
elif new == 'no':
print('Done')
it seems to work fine, but when you re-run the code and enter new values, it overrides the first entry in the list and dictionary instead of adding new entries in both. Ive also googled this and my code seems 100% fine, but it just keeps the list and dict's length at 1 entry.
Im not sure what the problem is and any help would be great, thanks.
EDIT: I added the full code.
When you run a python program whatever data you put in is temperary, as it only is saved to variables while you're running it.
So when you rerun this program, and aren't seeing what you last entered in, that's purely python's functionality, as it is with every other (scripting) programming language.
If you want to keep these values, think about adding them to a file (learn open()) and retrieving them at the start of the program and putting them into the variables (varDict, valList) before asking for user input.

How do I align the user input in the output code?

I am currently taking Web, Pgm & DB Foundation and I am learning python but I am struggling with this assignment.
In the original assignment, you were to create an expense calculator (code below):
print("This program calculates and displays travel expenses", '\n')
user_budget = int(input("Enter Budget:"))
user_destination = input("Enter your travel destination:")
user_fuel = int(input("How much do you think you will spend on gas?"))
user_lodging = int(input("Approximately, how much will you need for accommodation/hotel?"))
user_meals = int(input("Last, how much do you need for food?"))
print('\n')
print('----------Travel Expenses----------')
print('Location:', user_destination)
print('Initial Budget:', user_budget)
print('Fuel:', user_fuel)
print('Accommodation:', user_lodging)
print('Food:', user_meals)
print('___________________________________')
user_total = (user_budget-(user_fuel+user_lodging+user_meals))
print('Remaining Balance:', user_total)
For the next assignment, we are asked to make the output look like this:
expected output:
I was able to figure out how to add the $ next to the output, but this is my first time ever learning python so I am pulling my hair out trying to figure out how to align the output as shown in the image above.
I've updated the code to this:
print('----------Travel Expenses----------')
print('Location:', user_destination)
print('Initial Budget:', "${:.2f}".format(user_budget))
print('Fuel:', "${:.2f}".format(user_fuel))
print('Accommodation:', "${:.2f}".format(user_lodging))
print('Food:', "${:.2f}".format(user_meals))
print('____________________________________')
user_total = (user_budget-(user_fuel+user_lodging+user_meals))
print('Remaining Balance:',"${:.2f}".format(user_total))
But I am completely lost as to how to align the output to the right.
Any help is greatly appreciated and if you could break it down barney style, that would be awesome.

PDFBox in Kotlin - Output of an Rectangle Field of an PDF File

Its my first time i'm posting here, so sorry if i did something wrong.
My english is also not the best at the moment.
I'm new at coding and did start with some usefull Tutorials at Youtube.
My first Project should get some data out of an pdf-file.
I've used therefor PDFBox and it works well for me.
The only problem i cant solve at the moment is:
The extracted data are 4 tables in the pdf, ive used extractbyarea and set the right ints (x, y, w, h).
The data is written in an output, to this point it works well for me.
I got a string called "daten61". But if i'm using println(daten61) i got the string
shown with linebreaks. I want to use it like:
09.08 3931 15:59 00:46
and not like:
09.08
3931
15:59
00:46
Ive tried trim, replace, whatever ... it wont work.
Any other solutions for it? Someone well inside of PDFBox to can help to solve the problem?
Further i want to use the String like [09.08,3931,15:59,00:46] to start the next step of my project.
Thanks!
Code ive used:
val document = File("C://test//test1.pdf")
val doc = PDDocument.load(document)
val stripper = PDFTextStripperByArea()
stripper.sortByPosition = true
val output = ""
val rect = Rectangle(x, y, w, h)
stripper.addRegion(output, rect)
val firstPage = doc.getPage(0)
stripper.extractRegions(firstPage)
return (stripper.getTextForRegion(output))
/After println(output) ive got the Data in 4 rows

Python loop list in function call

This is my first question on StackOverflow. I have always found what I was looking for just googling, but this time I'm stuck and can't figure it out.
I'm a beginner programmer with python and still learning a lot.
I want to change a dateEdit box in a Userinterface with a small code to set det current date time.
the code looks like this.
self.dateEdit_2.setDateTime(QtCore.QDateTime.currentDateTime())
Now i want to change every dateEdit box the same, starting from 2 and going to 29, without typing every single line out.
i have tried to make a for loop with a filled list.
and i get it to print out what i want, but how does i get "set_date_numb" to be a attribute that does what i want.
hope you understand, Thanks.
dateTimeList = ['2','3','4','5','6','7','8','9',
'10','11','12','13','14','15','16','17','18','19','20',
'21','22','23','24','25','26','27','28','29']
indexval = 0
for i in range(len(dateTimeList)):
date_numb = (dateTimeList[indexval])
set_date_numb ='self.dateEdit_{}.setDateTime(QtCore.QDateTime.currentDateTime())'.format(date_numb)
print(set_date_numb)
indexval += 1
You could use getattr(), see the documentation here. Since the functions you are after are members of your instance you can grab them with their names as strings (which I think is the main problem you are facing):
dateTimeList = [str(x) for x in range(2,30)]
for dt in dateTimeList:
name = "dateEdit_{}".format(dt)
currentDateEdit = getattr(self, name)
currentDateEdit.setDateTime(QtCore.QDateTime.currentDateTime())

Python3 - Advice on a while loop with range?

Good afternoon! I am relatively new to Python - and am working on an assignment for a class.
The goal of this code is to download a file, add a line of data to the file, then create a while loop that iterates through each line of data, and prints out the city name and the highest average temp from the data for that city.
My code is below - I have the output working, no problem. The only issue I am running into is an IndexError: list index out of range - at the end.
I have searched on StackOverflow - as well as digging into the range() function documentation online with Python. I think I just need to figure to the range() properly, and I'd be done with it.
If I take out the range, I get the same error - so I tried to change the for/in to - for city in mean_temps:
The result of that was that the output only showed 4 of the 7 cities - skipping every other city.
Any advice would be greatly appreciated!
here is my code - the screenshot link below shows output and the error as well:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt
mean_temps = open('mean_temp.txt', 'a+')
mean_temps.write("Rio de Janeiro,Brazil,30.0,18.0")
mean_temps.seek(0)
headings = mean_temps.readline().split(',')
print(headings)
while mean_temps:
range(len(city_temp))
for city in mean_temps:
city_temp = mean_temps.readline().split(',')
print(headings[0].capitalize(),"of", city_temp[0],headings[2], "is", city_temp[2], "Celsius")
mean_temps.close()
You have used a while loop, when you actually want to use a for loop. You have no condition on your while loop, therefore, it will evaluate to True, and run forever. You should use a for loop in the pattern
for x in x:
do stuff
In your case, you will want to use
for x in range(len(city_temp)):
for city in means_temp:
EDIT:
If you have to use a while loop, you could have variable, x, that is incremented by the while loop. The while loop could run while x is less than range(len(city_temp)).
A basic example is
text = "hi"
counter = 0
while counter < 10:
print(text)
counter += 1
EDIT 2:
You also said that they expected you to get out of a while loop. If you want a while loop to run forever unless a condition is met later, you can use the break command to stop a while or for loop.
I've been stuck with this as well with the index error. My original code was:
city_temp = mean_temp.readline().strip(" \n").split(",")
while city_temp:
print("City of",city_temp[0],headings[2],city_temp[2],"Celcius")
city_temp = mean_temp.readline().split(",")
So I read the line then, in the loop, print the line, create the list from reading the line and if the list is empty, or false, break. Problem is I was getting the same error as yourself and this is because city_temp is still true after reading the last line. If you add..
print(city_temp)
to your code you will see that city_temp returns as "" and even though it's an empty string the list has content so will return true. My best guess (and it is a guess) it looks for the split condition and returns back nothing which then populates the list as an empty string.
The solution I found was to readline into a string first (or at the end of the whole loop) before creating the list:
city_temp = mean_temp.readline()
while city_temp:
city_temp = city_temp.split(',')
print(headings[0].capitalize(),"of",city_temp[0],headings[2],"is",city_temp[2],"Celcius")
city_temp = mean_temp.readline()
This time city_temp is checked by the while loop as a string and now returns false. Hope this helps from someone else who struggled with this

Resources