I've created a function who makes a loading bar in the terminal window. It looks like this:
def loadingBar(length, time):
void = '-'
fill = '#'
count = 100/length
increaseCount = 0
sleepTime = time/20
for i in range(length):
print('['+(fill*i)+(void*(length-i))+'] '+str(int(increaseCount))+'%',end='\r')
increaseCount += count
time.sleep(sleepTime)
print('['+(fill*(i+1))+(void*(length-(i+1)))+'] '+str(int(increaseCount))+'%',end='\n')
I want to customize the sleep time with the variable “sleepTime”, but I have an error who says :
AttributeError: 'float' object has no attribute 'sleep'
I don't understand because the variable “time” and the variable “sleepTime” are float!
Note : I'm not very good at English.
Currently, the parameter time has the same name as the module time.
Change:
def loadingBar(length, time):
To:
def loadingBar(length, time1):
and
sleepTime = time/20
to
sleepTime = time1/20
This will work:
def loadingBar(length, time1):
void = '-'
fill = '#'
count = 100/length
increaseCount = 0
sleepTime = time1/20
for i in range(length):
print('['+(fill*i)+(void*(length-i))+'] '+str(int(increaseCount))+'%',end='\r')
increaseCount += count
time.sleep(sleepTime)
print('['+(fill*(i+1))+(void*(length-(i+1)))+'] '+str(int(increaseCount))+'%',end='\n')
Related
I have a program that I want to be able to print all of the instances of each variable using my method that I created. Problem is I can't figure out a way to print them since each are listed under a different variable that aren't configured from hardcoding them in and I need a way to automatically recall them in my code.
class fit:
def __init__(self,day,did,workout='Not Recorded',time='An unknown amount of',calories='An unknown amount of'):
self.day = day
self.did = did
if did.lower()=='no':
self.workout = 'Not Recorded'
self.time = "An unknown amount of Minutes"
self.calories = "An unknown amount of Calories"
else:
self.workout = workout
self.time = "{} Minutes".format(time)
self.calories = "{} Calories".format(calories)
def formate(self):
self.formate = "{}:\n\nDid you work out: {}\nWorkout focus: {}\nYou worked out for: {}\nYou burned: {}\n\n----------------------------------------------------------".format(self.day,self.did,self.workout,self.time,self.calories)
return self.formate
def reader(day,index):
file = open('readme.txt')
file = file.read()
stripped = file.rsplit("\n")
for i in range(len(stripped)):
stripped[i] = stripped[i].rsplit(" ")
del stripped[-1]
if int(index) >= len(stripped[day-1]):
return "none"
else:
return stripped[day-1][index]
x = 0
def create_new_instance(class_name,instance_name):
globals()[instance_name] = class_name(reader(x,0),reader(x,1),reader(x,2),reader(x,3),reader(x,4))
print('Class instance {} created'.format(instance_name))
while True:
try:
x+=1
ins = 'day_' + str(x)
create_new_instance(fit,ins)
except:
break
break
def printer(instance):
print(.formate())
while True:
x+=1
inst = 'day_' + str(x)
printer(inst)
An example of this might be that I have 8 lines of data from a text document and I have a system that creates instances of day_1, day_2, day_3 ect until day_8 and then I want to print each of those instances out, but again I don't have those instances directly hardcoded into my code so I don't know how I'd do it. I've tried looking into maybe a while loop and increasing a variable by 1 and concatenating it with day and trying to make a variable out of that but the my limited experience with python isn't helping.
A very unpythonic and ugly way would be to use exec, for example:
day_3=5
x = 'day_'+'3'
exec("print("+x+")")
I would recommend another way to store your variables though.
I am trying to use the value of a variable, which is a string, as an argument and I keep getting "'Str' not callable' error. I haven't used str as a variable name I can make the code work with eval, however, I've read dire warnings about eval, so am unsure what to do. My code is below.
from time import sleep
from binance.client import Client
from binance.websockets import BinanceSocketManager
class s33():
def __init__(self):
self.client = Client("", "")
self.bm = BinanceSocketManager(self.client)
def process_trade_message(self, message):
global count, conn_key
print(count)
if count >= 10:
print('closing socket')
# use either stop_socket or close, or both
self.bm.stop_socket(conn_key)
self.bm.close()
# reset the count
count = 0
def go(self, sockb):
global count, conn_key
print(sockb['1'])
sock = 'self.bm.'+sockb['1']
print(sock)
count = 0
conn_key = sock(self.process_trade_message)
self.bm.start()
if __name__ == '__main__':
while True:
s = s33()
socka = {'1':'start_miniticker_socket'}
s.go(socka)
sleep(20)
print('sleeping')
I have read people recommend using a dict, So I passed the dict as the arg and tried to extract the string in the function,which is the code below. I tried to extract the string and pass that as an arg to the function. s.go(socka['1'], I tried passing the just the variable as an arg, socka = 'start_miniticker_socket' and I can get that to work if I use eval('self.bm'+socka) I tried the percentage sign with no luck. Not sure how to do this without using eval. I am still fairly new and can't find an alternative answer after several hours of searching that works. any help would be appreciated.
I think what people meant when suggesting a dict is something like this:
class s33():
# Codes...
def go(self, func_name):
global count, conn_key
print(func_name)
mapper = {
'start_miniticker_socket': self.bm.start_miniticker_socket
}
# Get self.bm.start_miniticker or None
sock = mapper.get(func_name)
print(sock)
if sock:
count = 0
conn_key = sock(self.process_trade_message)
self.bm.start()
else:
pass # Handle when sock is None
if __name__ == '__main__':
while True:
s = s33()
socka = 'start_miniticker_socket'
s.go(socka)
sleep(20)
print('sleeping')
for x in non_neutral.collect():
tweet = str(x[2])
sid = x[1]
status = x[0]
text = word_tokenize(tweet)
text1 = list(text)
tweet = x[2].split()
pronoun = intersect(second_pronoun,tweet)
perojective = intersect(less_offensive,tweet)
if pronoun:
pronoun_index = tweet.index(pronoun[0])
pero_index = tweet.index(perojective[0])
if pero_index <= pronoun_index+3:
status = 1
return Row(status=status,tid=sid,tweet = str(tweet))
else:
status = 0
return Row(status=status,tid=sid,tweet = str(tweet))
For this particular snippet of code I am constantly getting this error and I don't understand why
File "<ipython-input-5-0484b7e6e4fa>", line 15
return Row(status=status,tid=sid,tweet = str(tweet))
SyntaxError: 'return' outside function
I have tried writing the code again but still getting the same error.
your program doesn't actually contain a function. Return statements must be contained within a function, you haven't defined any in this case.
Try something more like the following (note that this doesn't include all of your code it is just an example):
def Foo():
#Here is where you put all of your code
#Since it is now in a function a value can be returned from it
if pronoun:
pronoun_index = tweet.index(pronoun[0])
pero_index = tweet.index(perojective[0])
if pero_index <= pronoun_index+3:
status = 1
return Row(status=status,tid=sid,tweet = str(tweet))
else:
status = 0
return Row(status=status,tid=sid,tweet = str(tweet))
Foo()
So long as you put your code in a function it will work. The syntax for a basic function definition in python is: def Foo(Bar): Where Foo is the name of the function and Bar is any parameters you may need, each separated by a comma.
I don't see the keyword def in your code snippet, which would indicate the beginning of a function definition. Is the snippet taken from the body of a function?
Here is a working sample of return in a for loop:
from random import shuffle
def loop_return():
values = [0,1]
shuffle(values)
for i in values:
if i == 0:
return 'Zero first.'
if i == 1:
return 'One first.'
You don't actually have a function, so you can't return anything. You could fix it by making the code a procedure.
I am trying to do a time counter in python using QTime and show this time in a QLabel using PyQt. I need to do this, to show how many time has passed since my program started to work, using this format of time: 00:00:00. I read the docs of QTime and tried another code that I have searched for on the internet, but I can not make it work.
This is part of my code:
class MyApplication(QtGui.QApplication):
def __init__(self, *args, **kwargs):
super(MyApplication, self).__init__(*args, **kwargs)
self.t = QTime() #I start QTime at the same time
self.t.start() # the program starts.
self.label_1 = QtGui.QLabel("Time since the program started:")
self.time_label = QtGui.QLabel("00:00:00")
self.tmr = QTimer() #I use QTimer because I need it
#for another part of the code
self.tmr.timeout.connect(self.clock)
def clock(self):
self.m = 0
self.elapsed = self.t.elapsed()
self.s = int((self.elapsed)/1000)
if self.s == 60:
self.m += 1
self.s = 0
self.time_sec = str(self.s)
self.time_min = str(self.m)
self.time = self.time_min + ":" + self.time_sec
self.time_label.setText(self.time) #I show the time in this QLabel()
When I build this, I get this format of time: 0:0 and after 60 seconds (it shows the seconds) I get this result: 1:0, and nothing else happens.
How can I make the time counter that I need with this format: 00:00:00. Can I do it using QTimer? Hope you can help me.
------ EDIT ------
Thanks to #amicitas and #linusg answer, I´ve tried the datetime module, and wrote this simple code:
class MyApplication(QtGui.QApplication):
def __init__(self, *args, **kwargs):
super(MyApplication, self).__init__(*args, **kwargs)
self.t0 = datetime.now()
self.tmr = QTimer()
self.tmr.timeout.connect(self.clock)
def.clock(self):
self.t1 = datetime.now()
self.hour = self.t1.hour - self.t0.hour
self.minute = self.t1.minute - self.t0.minute
self.second = self.t1.second - self.t0.second
print self.hour, self.minute, self.second
But, when I build this, at the moment the counter reaches 45 seconds, it turns 45 to -15 and "1 minute" appears. This is:
When it reaches 0:0:44, it turns to 0:1:-15.
What could be the problem? And how can I show the time format that I need? This is 00:00:00. Hope you can help me.
I have written and tested the following code for you:
from datetime import datetime
import time
if __name__== '__main__':
initTimeObj = datetime.now()
nullRef = datetime(initTimeObj.year, initTimeObj.month, initTimeObj.day, 0, 0, 0)
print("Initial time:")
print(str(initTimeObj.hour) + ':' + str(initTimeObj.minute) + ':' + str(initTimeObj.second))
print("")
while(True):
time.sleep(1)
myDiff = datetime.now() - initTimeObj
myTimeObj = nullRef + myDiff
print(str(myTimeObj.hour) + ':' + str(myTimeObj.minute) + ':' + str(myTimeObj.second))
# Now you get a counting as follows:
# 0:0:1
# 0:0:2
# 0:0:3
# ...
# 0:0:59
# 0:1:0
# 0:1:1
# 0:1:2
# ...
This code does exactly what you need. It starts counting from 0:0:0and continues doing so. Some more tweaks might be necessary if you really want to have a double-digit format, like 00:00:00. If you want, I can look into that further.
I hope this helped you out. Please let me know if it worked for you.
import datetime
import time
start = datetime.datetime.now()
while True:
elapsed_seconds = (datetime.datetime.now() - start).total_seconds()
hour = int(elapsed_seconds // 3600)
min = int(elapsed_seconds % 3600 // 60)
seconds = int(elapsed_seconds % 60)
print '{:02d}:{:02d}:{:02d}'.format(hour, minute, second)
time.sleep(1)
I'm trying to use python to create a small look up program, that would show all the current prices of a theoretical portfolio, and then offer the option to basically refresh your portfolio, or look up a new quote of your choice.
I can get everything to work in the program, the problem I'm having is with the defined functions.
If you look at run_price1(), you'll notice that it is identical to that of run_price(); however run_price() is located within the update function.
If I take it out of the update function, the update function doesn't work. If I don't also list it somewhere outside of the update function, the later user input doesn't work.
The question: I am looking for either a way to call a function that is defined within another function, or a way to use a previously defined function inside of a secondary function.
My code:
import mechanize
from bs4 import BeautifulSoup
def run_price1():
myBrowser = mechanize.Browser()
htmlPage=myBrowser.open(web_address)
htmlText=htmlPage.get_data()
mySoup = BeautifulSoup(htmlText)
myTags = mySoup.find_all("span", id=tag_id)
myPrice = myTags[0].string
print"The current price of, {} is: {}".format(ticker.upper(), myPrice)
def update():
my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]
counter = 0
while counter < len(my_stocks):
web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
ticker = my_stocks[counter]
#'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
tag_id = "yfs_l84_{}".format(ticker.lower())
def run_price():
myBrowser = mechanize.Browser()
htmlPage=myBrowser.open(web_address)
htmlText=htmlPage.get_data()
mySoup = BeautifulSoup(htmlText)
myTags = mySoup.find_all("span", id=tag_id)
myPrice = myTags[0].string
print"The current price of, {} is: {}".format(ticker.upper(), myPrice)
run_price()
counter=counter+1
update()
ticker = ""
while ticker != "end":
ticker = raw_input("Type 'update', to rerun portfolio, 'end' to stop program, or a lowercase ticker to see price: ")
web_address = "http://finance.yahoo.com/q?s={}".format(ticker.lower())
tag_id = "yfs_l84_{}".format(ticker.lower())
if ticker == "end":
print"Good Bye"
elif ticker == "update":
update()
else:
run_price1()
You can simply call run_price1() from the update() function, where you now call run_price.
Functions defined at the top of a module are global in the module, so other functions can simply refer to those by name and call them.
Any value that your function needs does need to be passed in as an argument:
def run_price1(web_address, tag_id):
# ...
def update():
my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]
counter = 0
while counter < len(my_stocks):
web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
ticker = my_stocks[counter]
#'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
tag_id = "yfs_l84_{}".format(ticker.lower())
run_price1(web_address, tag_id)
counter=counter+1