Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm making a simple program in order to compare the currentdate to another date, and I need to separate the "/" and remove trailing zeros; I made a function for that:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return
The code works just fine but i want to save the DaysLeft, Monthsleft to print it/edit it ETC..
so i do this:
correctdate(compare,Dayslist,Monthslist)
print(correctdate.Daysleft)
and i get this:
AttributeError: 'function' object has no attribute 'Daysleft'
There was a typo in printing the object attribute
I wrote:
print(correctdate.Daysleft)
Its supposed to be:
print(correctdate.DaysLeft)
Sorry for the inconvenience
You ve to return it in your function, and outside it get it into variables:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return correctdate.DaysLeft,correctdate.MonthsLeft
This for return outside function, now you ve to call function correctly:
DaysLeft,Monthsleft = correctdate(compare,Dayslist,Monthslist)
print(DaysLeft,Monthsleft)
Anyway this code "correctdate.MonthsLeft" looks like you want use class and not only functions, so you should use like that https://www.w3schools.com/python/python_classes.asp
def correctdate(compare, Dayslist, Monthslist):
You declare a function with name correctdate that accepts 3 parameters.
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
Then you try to assign a value to a function, which is not possible because correctdate is not a variable, not an object. You just declared it as a function.
What are you trying to achieve?
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I honestly do not know what to do. The questions I got on StackOverflow were about strings and csv inputs, but these variables I am expecting are different. Help would be very much appreciated. I always get ValueError: too many values to unpack (expected 3). I want the code to pass the three returned variables from speedCalc() to something I could use in the calculations in spellCheck() (line 35). What should I do?
Here's the code:
#!/usr/bin/env python
import time
import random
import string
import sys
import string
import sys
#from getkey import getkey
def generateTest():
mylines = []
with open ('phrases.txt', 'rt') as myfile: # Open phrases.txt for reading the typing tests
for line in myfile: # For each line of text,
mylines.append(line) # add that line to the list.
# Converting lines of list to select a random phrase
listLen = len(mylines) - 1
return (mylines[random.randint(0,listLen)])
def speedCalc():
# words / time passed (assuming it is 5)
start = time.time()
test = input(print(generateTest()))
end = time.time()
timePassed = (end - start)
generateTestLen = len(generateTest())
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
def spellCheck():
test, timePassed, wpm = speedCalc()
diff = 0
correctChars = 0
file_A = generateTest()
file_B = test
read_A=open(file_A,'r').read()
read_B=open(file_B,'r').read()
for char_a, char_b in zip(read_A, read_B):
if char_a == char_b:
correctChars = correctChars+1
read_A_len = len(read_A)
correctPercent = (correctChars/read_A_len)*100
errors = read_A_len - correctChars
errorRate = errors/timePassed
netWPM = wpm - errorRate
return correctPercent
return netWPM
correctPercent, netWPM = spellCheck()
print(netWPM)
Instead of using:
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
use
return test, timePassed, ((generateTestLen/5)/timePassed)*60
Your function as you defined in your example just returnes test and exits then. The second and third return is not executed any more.
When a return statement is reached, a function stops. Any code after the return statement is never executed.
The code
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
is equivalent to
return test
You should return a tuple of three values. Use
return test, timePassed, ((generateTestLen/5)/timePassed)*60
Adjust spellCheck accordingly, it has the same problem.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have a simple code to get user email information, I got a problem about something :
import sys
try:
argx = sys.argv(1)
except:
print("Please Input an email.")
Example For User argument :
py main.py example#example.com
I want to take arg (input) after the # char and the . char.
I need this to check the email provider, domain name and other stuff about the email.
Example of the thing i want :
import sys
try:
argx = sys.argv(1)
x = "The argument after the char #, and the ."
except:
print("Please Input an email.")
if(x.lower() == "gmail") :
gmail()
elif(x.lower == "protonmail") :
protonmail()
You can use split function of a string in order to split a string
like
x = 'name#example.com' #Your input
email = x.split('#') # will give ['name','example.com']
provider = email[1].split('.')[0] # will give 'example'
Asuming you have the following email example#example.com. In python you can split a string with the split function. The function itself needs a delimeter. In your case the delimeter would be #. The return value of the split function is an array.
parts_of_mail = email.split("#")
>>> [example, example.com]
You now have the array parts_of_mail, which stores the left and right part of the email. You can now split the string again, like above:
provider_info = parts_of_mail[1].split(".")
>>> [example, com]
Finally you can check the provider information:
if provider_info[0].lower() == "example":
# do stuff here
elif provider_info[0].lower() == "gmail":
# do stuff here
Note: provider_info[0] stores the provider and provider_info[1] stores the domain.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a function that takes a string input. I want to count no of times a string occurs in the input.
Example, I have a string cars = "Toyota, Honda, Toyota, BMW, Toyota"
I want a function that returns no of times a string occur
toyota_count = 0
honda_count = 0
BMW_count = 0
def count_cars(cars):
if "toyota" in cars:
toyota_count += 1
if "honda" in cars:
honda_count += 1
But this gives me error on toyota_count in the function, it says "Unresolved reference toyota_count"
Its because toyota_count is global.
Either define the variable inside your method (preferred) or specify it inside your methot as global like so:
def myfunc():
gobal toyota_count
EDIT
You can also just use cars.count("Toyota") to get the total number of substrings in a string.
Assuming your strings don't overlap, just use the string count() method. Whilst this isn't uber-efficient (three calls to count() and therefore 3 searches) it fits your described use case.
cars = "Toyota, Honda, Toyota, BMW, Toyota"
toyota_count = cars.count("Toyota")
honda_count = cars.count("Honda")
toyota_count = 0
honda_count = 0
BMW_count = 0
def count_cars(cars):
global toyota_count
toyota_count = cars.count('Toyota')
count_cars("Toyota, Honda, Toyota, BMW, Toyota")
print (toyota_count)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I try to write a program and get a variable from a constructor to a method but I don't know how to do it :( I get an error with p.liczba in the method sprawdz. I would like to have here a number from the user. The same situation is with p.wielokrotnosc. I know that I can write this program easier but I really would like to learn OOP with simple examples like this
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
def podajSzukana(self):
self.wielokrotnosc = 3
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
p = Przyklad(a)
def sprawdz(self):
if (p.liczba % p.wielokrotnosc == 0):
return true
print ('Witaj w programie szukającym wielokrotność liczby 3 \n')
d = Dane()
d.wczytaj()
d.sprawdz()
The problem is not getting the variable from the constructor of Przyklad. The problem is saving it in Dane. The common procedure is to attach it to instance of Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
Then, you'll have self.p available in Dane
This is happening because the variable liczba is contained within the class Przyklad, so when you try to access it in Dane, it is not possible.
You should try having liczba be a global variable (which is dangerous), or having Dane be a descendant of Przyklad (these names though....).
a and p are local variables not members of Dane. You have to use self. (as pointed by jonrsharpe) to be able to access this variable from the class context:
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
def sprawdz(self):
if (self.p.liczba % self.p.wielokrotnosc == 0):
return true
Another issue is that self.wielokrotnosc do not exists until you call podajSzukana(self) method. One way to fix this is calling that function inside your constructor:
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
self.podajSzukana() // Call the method here.
def podajSzukana(self):
self.wielokrotnosc = 3
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am getting an invalid syntax error
SyntaxError: invalid syntax
root#collabnet:/home/projects/twitterBot# python twitterBot2.py
File "twitterBot2.py", line 58
return screenNames
when returning a dictionary from this function:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print 'fetching usernames'
while i < l:
toGet = []
toAppend = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet.append(lookupIds[count])
count = count + 1
print toGet
else:#handles the remainder
print 'last run'
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet.append(lookupIds[count])
count = count + 1
i = l # kills loop
toAppend = api.lookup_users(user_ids=toGet)
print toAppend
screenNames.append(zip(toGet, toAppend)
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their count number as the
#index value
#print str(len(toGet)), 'screen names correlated'
return screenNames
I am running the function like so:
toPrint = {}#Testing Only
print "users following", userid
toPrint = getUserName(followingids)#Testing Only
I have tried commenting out and just printing screenNamesand I still get the same error except on the print statement instead. I am pretty sure I am running the return right thanks for the look.
You forgot a closing parenthesis on a preceding line:
screenNames.append(zip(toGet, toAppend)
# ^ ^ ^^?
# | \---- closed ---/|
# \----- not closed ---/
You'll have another problem here, as screenNames is a dict object, not a list, and has no .append() method. If you wanted to update the dictionary with key-value pairs, use update() instead:
screenNames.update(zip(toGet, toAppend))