calling a variable from another function in python 3.3? - python

I know that this has been asked before, but I cant for the life of me understand it. I'm trying to create a simple program that gets two dates, and counts shows how many days are left between them.
This is my current code:
month = 0
day = 0
year = 0
def getDate(): #gets the current date
global month
global day
global year
print( 'What is the current month?' )
month = month + int(input())
print( 'What is the current day?' )
day = day + int(input())
print( 'What is the current year?' )
year = year + int(input())
print( 'The current date is ' + str(month) + '/' + str(day) + '/' + str(year) + '. Is this correct?' )
YESNO = input() #confirms date
if YESNO == 'YES' or YESNO == 'yes':
print( 'Okay.' )
else:
getDate()
newMonth = 0
newDay = 0
newYear = 0
def newDate(): #gets the desired countdown date
global newMonth
global newDay
global newYear
print( 'What is the desired countdown month?' )
newMonth = newMonth + int(input())
print( 'What is the desired countdown day?' )
newDay = newDay + int(input())
print( 'What is the desired countdown year?' )
newYear = newYear + int(input())
print( 'The desired countdown date is ' + str(newMonth) + '/' + str(newDay) + '/' + str(newYear) + '. Is this correct?' )
YESNO = input() #confirms date
if YESNO == 'YES' or YESNO == 'yes':
print( 'Okay.' )
else:
newDate()
def COUNTDOWN(): #prints countdown
global newMonth
global newDay
global newYear
global month
global day
global year
if newMonth < Month:
countDownMonth = int(Month) - int(newMonth)
else:
countDownMonth = int(newMonth) - int(Month)
if newDay < Day:
countDownDay = int(Day) - int(newDay)
else:
countDownDay = int(newDay) - int(Day)
if newMonth < Year:
countDownYear = int(Year) - int(newYear)
else:
countDownYear = int(newYear) - int(Year)
print( countDownMonth + '/' + countDownDay + '/' + countDownYear )
getDate()
newDate()
COUNTDOWN()
EDIT:
I apologize, I didn't realize it wasn't indented.
EDIT:
My question is how do I create a cross-function variable?

The global keyword in python is used to rebind a global variable in a local context. That being said, it is generally good practice to avoid the usage of the global keyword whenever possible.
In the code that you posted, it is necessary to use global in the functions getDate and newDate in order to bind those names in the global environment. However, in COUNTDOWN, because you are not rebinding the names and are only accessing the values bound to those names, global is not necessary.
For more information look here: Use of "global" keyword in Python

I just make your code workable as below:
month = 0
day = 0
year = 0
newMonth = 0
newDay = 0
newYear = 0
def getDate(): #gets the current date
global month
global day
global year
print( 'What is the current month?' )
month = month + int(input())
print( 'What is the current day?' )
day = day + int(input())
print( 'What is the current year?' )
year = year + int(input())
print( 'The current date is ' + str(month) + '/' + str(day) + '/' + str(year) + '. Is this correct?' )
YESNO = raw_input() #confirms date
print YESNO
if YESNO == 'YES' or YESNO == 'yes':
print( 'Okay.' )
else:
getDate()
def newDate(): #gets the desired countdown date
global newMonth
global newDay
global newYear
print( 'What is the desired countdown month?' )
newMonth = newMonth + int(input())
print( 'What is the desired countdown day?' )
newDay = newDay + int(input())
print( 'What is the desired countdown year?' )
newYear = newYear + int(input())
print( 'The desired countdown date is ' + str(newMonth) + '/' + str(newDay) + '/' + str(newYear) + '. Is this correct?' )
YESNO = raw_input() #confirms date
if YESNO == 'YES' or YESNO == 'yes':
print( 'Okay.' )
else:
newDate()
def COUNTDOWN(): #prints countdown
global newMonth
global newDay
global newYear
global month
global day
global year
if newMonth < month:
countDownMonth = int(month) - int(newMonth)
else:
countDownMonth = int(newMonth) - int(month)
if newDay < day:
countDownDay = int(day) - int(newDay)
else:
countDownDay = int(newDay) - int(day)
if newMonth < year:
countDownYear = int(year) - int(newYear)
else:
countDownYear = int(newYear) - int(year)
print( str(countDownMonth) + '/' + str(countDownDay) + '/' + str(countDownYear) )
getDate()
newDate()
COUNTDOWN()
In my env, this code is working, but i am not sure whether the output correct or not.

use the global keyword, like so:
def function():
global variable
this basically says, I want to access variable, even though I know it is global I still want it anyway.
Only use this if you are Changing the variable, not just using whatever is inside it.
e.g.,
def example():
global eg
eg = 1
Here we use global because we are changing eg's content. If we were to instead, USE eg's content to do something different we would do this:
def example(eg):
eg2 = eg
Here we are saying, 'I want to use the value that eg contains, but I dont want to change it'.
Then we have declared eg2 to be the same as eg, but we have not changed eg
If you wanted to then use the outcome of the function example, you would add a 'return' line.
def example(eg):
eg2 = eg
return eg
then we would call the function like so:
eg3 = example(eg)
This puts the result of example into eg3.
Hope this helps :)

Related

Issues with naming variables for zellers congruence project

i'm working on making a program in python that uses arrays since it's the new chapter i'm learning. The goal of my program will ask the user for month day and day and I seem to have it almost done except that i have an issue with 2 lines in this whole code. I will write a comment in where i'm getting the errors.
def calc_zellers_congruence(get_day: int, get_year: int, get_month: int) -> str:
# Calculates the month day and year
days = [""] * 7
day_Of_Week = 0
day_of_month = 0
century = 0
year_of_the_century = get_year % 100
days[1] = "Sunday"
days[2] = "Monday"
days[3] = "Tuesday"
days[4] = "Wednessday"
days[5] = "Thursday"
days[6] = "Friday"
days[0] = "Saturday"
dayOfWeek = day_of_month + 13 * get_month + int(1) / 5 + year_of_the_century + int(year_of_the_century) / 4 + int(
century) / 4 + 5 * century % 7
name_of_day = days[day_Of_Week]
return name_of_day
def displayResults():
print("Result" + day)
def get_day():
print("Enter a Day")
get_day = int(input())
return get_day
def get_month():
print("Enter a Month")
month = int(input())
return month
def get_year():
print("Enter a Year")
get_year: int(input())
return year
# Main
# This program will calculate birthdays using arrays and zellers congruence
# References...Programming Fundamentals WiKi, J Robinson, GeeksForGeek.com
year = get_year()
month = get_month()
day = get_day()
calc_Zeller_Congruence: calc_zellers_congruence(get_year, get_month, get_day)
displayResults(calc_zellers_congruence)
I've tried renaming them but have gotten more errors after switching them from uppercase to lowercase and also adding snake cases.

Threading Error: NameError: name 'datelabelstringvar' is not defined [closed]

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 2 years ago.
Improve this question
In python, I want a function to run at the same time as my normal script. I searched the internet and found threading, however, when I implement it and run the code, the error NameError: name 'datelabelstringvar' is not defined appears. I don't know what is wrong but when I remove threading and assign the function to a button (which I don't want just to be clear, I want it to be automatic), it works fine.
Code:
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from numerize import numerize
import pygame
import os
import random
from datetime import datetime
import threading
import time
wholedate = datetime.date(datetime.now())
date = wholedate.strftime("%d")
month = wholedate.strftime("%m")
year = wholedate.strftime("%Y")
def advancetime():
global date
global month
global year
threading.Timer(5.0, advancetime).start()
if month == "09" or month == "04" or month == "06" or month == "11":
date = int(date) + 1
if date > 30:
date = 1
month = int(month) + 1
if month > 12:
month = 1
year = int(year) + 1
fixdate()
fixmonth()
datelabelstringvar.set(str(date) + "/" + str(month) + "/" + str(year))
return
if month == "01" or month == "03" or month == "05" or month == "07" or month == "08" or month == "10" or month == "12":
date = int(date) + 1
if date > 31:
date = 1
month = int(month) + 1
if month > 12:
month = 1
year = int(year) + 1
fixdate()
fixmonth()
datelabelstringvar.set(str(date) + "/" + str(month) + "/" + str(year))
return
if month == "02":
date = int(date) + 1
if date > 31:
date = 1
month = int(month) + 1
if month > 12:
month = 1
year = int(year) + 1
fixdate()
fixmonth()
datelabelstringvar.set(str(date) + "/" + str(month) + "/" + str(year))
def calendarOnClose():
root.deiconify()
calendarwindow.destroy()
def calendar():
global datelabelstringvar
global calendarwindow
root.withdraw()
calendarwindow = Toplevel()
calendarwindow.title("Calendar")
calendarwindow.geometry("400x350+300+100")
calendarwindow.protocol("WM_DELETE_WINDOW", calendarOnClose)
datelabelstringvar = StringVar()
datelabelstringvar.set(str(date) + "/" + str(month) + "/" + str(year))
datelabel = Label(calendarwindow, textvariable=datelabelstringvar).grid(row="0", column="0")
Button(calendarwindow, text="Advance Time", command=advancetime).grid(row="1", column="0")
totalfruitclickerstringvar = StringVar()
totalfruitclickerstringvar.set("Fruit Clicked: " + str(totalfruitclicked))
Label(calendarwindow, textvariable=totalfruitclickerstringvar).grid(row="2", column="0")
root = Tk()
root.title("Fruit Clicker")
root.geometry("400x350+300+100")
calendarbutton = Button(root, text="Calendar", fg="White", bg="Black", width="11", command=calendar)
calendarbutton.grid(row="8", column="0")
advancetime()
root.mainloop()
How do I fix this error? Thanks.
EDIT:
Full Error:
Traceback (most recent call last):
File "C:\Users\colli\Documents\GitHub\FruitClicker\windows\main.py", line 1708, in <module>
advancetime()
File "C:\Users\colli\Documents\GitHub\FruitClicker\windows\main.py", line 113, in advancetime
datelabelstringvar.set(str(date) + "/" + str(month) + "/" + str(year))
NameError: name 'datelabelstringvar' is not defined
Your code makes several references to a datelabelstringvar variable. However, you never define it. That's what Python is saying.
EDIT:
It doesn't appear that you ever call the calendar function where the variable is defined.

How can I repeat my loop and add more information to my dictionary, and use different strings?

I am trying to create a program so that I can input all the shifts I work in a week, and it will calculate the total number of hours I work, and how much I money I will make.
I have created a dictionary called week_schedule and an input prompt to ask the user what day of the week they are going to log. The program then asks the shift start and finish, creating variables for both of them, and storing it all in a dictionary.
How can I rerun this loop, so that I can input more than one day, and store it all in a dictionary that I can then print out later? Currently rerunning the loop just adds more information to the same strings.
week_schedule = {}
day = input("Day of the week: ")
day_promp = True
while day_promp:
dayStart = input("Shift Start: ")
dayEnd = input("Shift End: ")
dayHours = (float(dayEnd) - float(dayStart)) / 100
dayPay = (float(dayHours) * 15.75)
week_schedule[day] = format(dayHours) + " hours", "$ " + format(dayPay)
repeat = input("\nMore days?: ")
if repeat == 'no':
day_promp = False
print("\n--- Week summary ---")
for day, dayHours in week_schedule.items():
print(format(day) + ": " + format(dayHours))
print("Total earned: $" + format(dayPay))
Currently I can run the program and it works for only one day.
For example if I imputed 'Tuesday" for the day, "1200" for the shift start, and "1800" for the shift end, it would output the following:
--- Week summary ---
Tuesday: ('6.0 hours', '$ 94.5')
Total earned: $94.5
--------------------
I would like to be able to print out all the days I input in the dictionary as well.
Move your day = input("Day of the week: ") inside the loop, so it will be
week_schedule = {}
grand_total = 0
day_promp = True
while day_promp:
# Do it each iteration
day = input("Day of the week: ")
dayStart = input("Shift Start: ")
dayEnd = input("Shift End: ")
dayHours = (float(dayEnd) - float(dayStart)) / 100
dayPay = (float(dayHours) * 15.75)
# sum up all the totals
total += dayPay
week_schedule[day] = format(dayHours) + " hours", "$ " + format(dayPay)
repeat = input("\nMore days?: ")
if repeat == 'no':
day_promp = False
print("\n--- Week summary ---")
# Now your dict has a key per day, so all values are printed.
for day, dayHours in week_schedule.items():
print(format(day) + ": {} ".format(dayHours))
print("Total earned: $ {0:.2f}".format(dayPay))
print("Grand Total earned $ {0:.2f}".format(total))
Your original code assigns day = input("Day of the week: ") only once, that's why
you're always getting only one value.
As mentioned in the comments above, the easiest way to make a program like this would be to have it write to a file in a given format. For example:
WagePerHour = 9.50
Mode = input("Would you like to log another day, clear the log, or see the current total? ")
if Mode == "log":
EnterMore = True
while EnterMore == True:
Day = input("What day of the week are you logging? ")
Hours = input("How many hours did you work? ")
Days = { "Sunday" : "1", "Monday" : "2", "Tuesday" : "3", "Wednesday" : "4", "Thursday" : "5", "Friday" : "6", "Saturday" : "7"}
File = open("File", "a")
DayAsNumber = Days[Day]
File.write(DayAsNumber + " " + Hours)
File.write("\r\n")
File.close()
continuevar = input("Would you like to log another day? (Y/N) ")
if continuevar != "Y":
EnterMore = False
if Mode == "total":
File = open("File", "r")
TotalHours = 0
for line in File.readlines():
if line[2:] != "":
TotalHours += int(line[2:])
TotalHoursString = str(TotalHours)
print("So far this week, you have logged " + TotalHoursString + " hours.")
File.close()
TotalHoursAsInt = int(TotalHoursString)
TotalWages = (TotalHoursAsInt * WagePerHour)
TotalWagesString = str(TotalWages)
print("Your wages before taxes are " + TotalWagesString)
else:
print("You have not logged any hours this week.")
if Mode == "clear":
File = open("File", "w")
File.write("")
File.close()

Python program saying variable 'dateNumber' is not defined

def dateCalculationNorm(year):
a = year%19
b = year%4
c = year%7
d = (19*a + 24)%30
e = (2*b + 4*c + 6*d + 5)%7
dateNumber = 22 + d + e
return dateNumber
def dateCalculationSpecial(year):
a = year%19
b = year%4
c = year%7
d = (19*a + 24)%30
e = (2*b + 4*c + 6*d + 5)%7
dateNumber = 15 + d + e
return dateNumber
def dateOutput(year, date):
print("The date of Easter in the year {0} is {1}.".format(year, date))
def main():
print("Easter Date Calculator")
print()
year = eval(input("Enter the year: "))
if year >= 1900 and year <= 2099:
dateCalculationNorm(year)
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
elif year == 1954 or year == 1981 or year == 2049 or year == 2076:
dateCalculationSpecial(year)
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
else:
print("Sorry, but that year is not in the range of this program.")
if __name__ == '__main__':
main()
I am having trouble getting main() to accept dateNumber in the line following
(if year >= 1900 and year <=2099) Python is saying that dateNumber is not defined. I tried making dateNumber global at the beginning of the program and that worked (albeit with a warning from Python), but I know that's the sloppy way to get this program working.
Any help is very much appreciated.
You need to instantiate dateNumber.
if year >= 1900 and year <= 2099:
dateNumber = dateCalculationNorm(year) # Instantiate here.
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
As it stands, there's nothing like that inside your main() function. There's no need to set it to a global either.

Python output to command line; Error not defined

I am trying to write a script that takes one argument and writes the output to the command window. For some reason I am getting the error:
NameError: name 'month' not defined
Here is the entire script:
import sys
hex = str(sys.argv)
sys.stdout.write (month(hex) + " " + day(hex) + ", " + year(hex) + " " + hour(hex) + ":" + minute(hex) + ":" + second(hex))
def year (hex):
year = int(hex[0:2], 16)
year = year + 1970
return str(year)
def month (hex):
month = int(hex[2:4], 16)
if month == 0:
month = "January"
return month
elif month == 1:
month = "February"
return month
elif month == 2:
month = "March"
return month
elif month == 3:
month = "April"
return month
elif month == 4:
month = "May"
return month
elif month == 5:
month = "June"
return month
elif month == 6:
month = "July"
return month
elif month == 7:
month = "August"
return month
elif month == 8:
month = "September"
return month
elif month == 9:
month = "October"
return month
elif month == 10:
month = "November"
return month
else:
month = "December"
return month
def day (hex):
day = int(hex[4:6], 16)
return str(day)
def hour (hex):
hour = int(hex[6:8], 16)
if hour < 10:
return "0" + str(hour)
else:
return str(hour)
def minute (hex):
minute = int(hex[8:10], 16)
if minute < 10:
return "0" + str(minute)
else:
return str(minute)
def second (hex):
second = int(hex[10:12], 16)
if minute < 10:
return "0" + str(second)
else:
return str(second)
When I used an online python interpreter to run it, the functions worked fine. I just don't know how to run it from the command line and send the output back to the command window. Thanks
In python a file is parsed line by line from top to bottom, so the functions month,year,hour,minute and second are not defined yet for this line:
sys.stdout.write (month(hex) + " " + day(hex) + ", " + year(hex) + " " + hour(hex) + ":" + minute(hex) + ":" + second(hex))
Move these function definitions above this line.
And using a local variable with same name as the function name is not a good idea.
As sys.argv returns a list (with first element being the filename), so you can't apply hex over it. Apply hex on the items of the list, i.e hex( int(sys.argv[1]) )
>>> lis = ['foo.py', '12']
>>> hex( int(lis[1]) ) #use `int()` as hex expects a number
'0xc'
Put the line sys.stdout.write... after your function definitions.
Please, don't use month for both your function and a variable inside this function.

Categories