I barely started this python tutorial and I don't understand how I would set this variable(total)
Think about it this way: Your Variable meal now stores two meals plus the tax for both of them. The only thing that is missing is the tip.
Now you can create this
total = meal + tip
if meal or tip is changing, the result of total would change too. But you need to be careful to not get confused with this behaviour.
Variables are bound to their object content if you assign them directly like
variable = 1234
if you now got another variable that stores the same content you would (normally) not write this again:
vari2 = 1234
but instead:
vari2 = variable
The interesting about that is, if you print
print variable
print vari2
you get the same results as expected. But if you change your first variable after all this code, there will be a difference! You can try to run this last code piece to understand what i mean:
vari = 1234 #Integer variable
print "Vari: %r" % vari
varia = vari #The Variable varia is bound to the CONTENT of vari not to the Name vari!
print "varia from vari: %r\n... -> New vari " % (varia)
vari = 42 # Now if you change vari, the content of varia is still the same!
print "Varia %r from vari %r" % (varia, vari)
This behaviour is very useful to store the original starting value of a variable. So you can keep track how the variable changed over time.
I suggest to play a little with variables and print to get a better understanding.
You have already used the same concept in the previous lines.
total = meal + (meal * tax)
Related
I have a dictionary restaurants and want to change the value of opening hours and closing hours in a nested list in restaurants depending on the day inputted by the user.
opening_time=0
closing_time=0
##snippet of the dictionary
restaurants={"Macdonald's":\
\
[{"Monday":[700,2400],\
"Tuesday":[700,2400],\
"Wednesday":[700,2400],\
"Thursday":[700,2400],\
"Friday":[700,2400],\
"Saturday":[700,2400],\
"Sunday":[1000,2200]},\
\
"Block XXX, #01-XX",\
"Fast food restaurant known for its all round excellent menu.",\
\
["Breakfast",[opening_time,1100],\
{"Egg McMuffin":"$1",\
"Hotcakes":"$1",\
"Big Breakfast":"$1"}],\
["Lunch/Dinner",[1100,closing_time],\
{"Double Cheeseburger":"$3.20",\
"McChicken":"$3.95",\
"Big Mac":"$4.70",\
"Chicken McNuggets (6pcs)":"$4.95",\
"McWings":"$4.95"}],\
["All Day",[opening_time,closing_time],\
{"Fillet-O-Fish":"$4.60",\
"Corn Cup":"$1.95"}]]}
I want the code to loop through and print all the restaurants and menus while indicating whether said restaurants and menus would be available for a user inputted time.
for key in restaurants: #key refers to restaurant name
print("","",sep='\n')
if day_now in restaurants.get(key)[0].keys(): #check if restaurant is open on that day
opening_time=restaurants.get(key)[0][day_now][0] #set opening and closing hours to those on that day
closing_time=restaurants.get(key)[0][day_now][1]
if time_now>=opening_time and time_now<closing_time: #check if restaurant is open within that time period
status="Open"
open_restaurants.update(restaurants)
print(key,"Status: "+status,"Opening Hours Today:"+str(opening_time)+" to "+str(closing_time),\
"Location: "+restaurants.get(key)[1],"Description: "+restaurants.get(key)[2],sep='\n')
for i in range(3, len(restaurants.get(key))): #goes through the menus the restaurant has
print(restaurants.get(key)[i][1][0]) #prints 0
print(restaurants.get(key)[i][1][1]) #prints 0
if time_now>=restaurants.get(key)[i][1][0] and time_now<restaurants.get(key)[i][1][1]: #check if menu have
print("")
print(restaurants.get(key)[i][0]+" Menu: Available","Item: Cost:",sep='\n')
for item in restaurants.get(key)[i][2].keys():
print(item, restaurants.get(key)[i][2][item],sep=' ')
else:
print("")
print(restaurants.get(key)[i][0]+" Menu: Unavailable","Item: Cost:", sep='\n')
for item in restaurants.get(key)[i][2].keys():
print(item, restaurants.get(key)[i][2][item],sep=' ')
else:
closed_restaurants.update(restaurants)
status="Closed"
print(key,"Status: "+status,"Opening Hours Today:"+str(opening_time)+" to "+str(closing_time),\
"Location: "+restaurants.get(key)[1],"Description: "+restaurants.get(key)[2], sep='\n')
else:
closed_restaurants.update(restaurants)
status="Closed"
print(key,"Status: "+status,"Opening Hours Today:"+str(opening_time)+" to "+str(closing_time),\
"Location: "+restaurants.get(key)[1],"Description: "+restaurants.get(key)[2], sep='\n')
print(opening_time) #prints the correct opening and closing hours
print(closing_time)
However, the opening hours and closing hours variables in the dictionary could not be assigned to the desired values in the loop and remained as they were first assigned outside the loop.
Directly printing the variable names showed that the new values were assigned successfully.
Could someone help me with the issue here? Thanks.
Let's use this simple example to make clear where your assumptions are wrong:
var = 1
lst = [var]
var = 2
print(lst)
What should this print, [1] or [2]? It will print [1]. What you have here is not a list of variable references, it is a list of integers. You took the value var had, and put that into a list. A copy, if you want.
What about this?
a = 1
b = a
a = 2
Again, b is still 1 after this. You took what was written at the location where a is stored, and put it in the location where b is stored.
You need to actually update the values inside the dictionary, it is not enough to update opening_hours.
from lxml import html
import requests
page = requests.get('http://www.runningzone.com/wp-content/uploads/2016/09/Turtle-Krawl-Overall-Results-2016.html')
tree = html.fromstring(page.content)
x=2
while True:
xpathName = "/html/body/div[2]/table/tbody/tr['x']/td[4]//text()"
xpathTime = "/html/body/div[2]/table/tbody/tr['x']/td[9]//text()"
name = tree.xpath(xpathName)
time = tree.xpath(xpathTime)
print (name), (time)
x += 1
So I'm trying to make this print both the person name and time using the xpath. For some reason the code prints out an entire list of both the name and time, even though I'm pretty sure the xpath of the Name and Time should print a single name. If I replace the 'x' part with just a single number, it prints just one name. But if I tell the code to print 'x' where it replacesx with a different number each loop, it just prints huge lists.
'x' does not interpolate the x variable into the string. You need to do something like this:
xpathName = "/html/body/div[2]/table/tbody/tr[%d]/td[4]//text()" % (x,)
xpathTime = "/html/body/div[2]/table/tbody/tr[%d]/td[9]//text()" % (x,)
Also, as #grael mentioned, you need to terminate your loop somewhere.
I am learning to code in Python.
I am creating a program that will perform unit conversions, however I have been stuck on this error for a good while:
NameError: name 'ini' is not defined
Here is the code:
a = ("Distance")
b = ("Time")
c = ("Volume")
d = ("Temp")
e = ("Weight")
def conversion_type(first):
if first == ("Distance"):
ini = input("How great a distance am I converting?\n")
elif first == ("Time"):
ini = input("How much time am I converting?\n")
elif first == ("Volume"):
ini = input("How great a volume am I converting?\n")
elif first == ("Temp"):
ini = input("How many degrees am I converting?\n")
elif first == ("Weight"):
ini = input("How much weight am I converting?\n")
else:
print("That not was an afformentioned dimension you dolt.")
def variable_type_converter(ini):
ini = float(ini)
print ("\n Welcome to the Convert-O-Matic\n==============================\n")
print ("I support the following dimensions:\n")
print ("%s, %s, %s, %s, and %s," % (a,b,c,d,e))
first = input("What kind of conversion would you like to do?\n")
conversion_type(first)
variable_type_converter(ini)
print("==========================================")
ini is not declared in the global scope, only inside of functions (it is used in conversion_type() and therefore implicitly declared there, and it is an argument to variable_type_converter()). But since it was not declared in the global scope, it does not exist there. If you want to set the value of ini in conversion_type() and have the value be usable elsewhere, declare a value for ini somewhere before you call conversion_type().
This answer has a good summary of Python's scoping rules.
Update: As MadWombat points out in comments, your variable_type_converter() function doesn't do anything. It takes one argument, called ini, it casts it as float and reassigns back to ini, but then it doesn't return a value. So when the variable_type_converter() function exits, the value is discarded and and the float cast is never used.
When defining your variables you should use a = "Distance". You should also check the conversion type using first == "Distance"
ini is not defined, is occurring because the function conversion_type(first) is returning a value that is not stored. Try:
# get conversion type
conversion_type_chosen = conversion_type(first)
# calculate value
converted_value = variable_type_convertor(conversion_type_chosen)
# print result
print "result: {}".format(converted_value)
I would first like to apologize for how much of a beginner I am, however I have hit this wall after many other hurdles. The basis of this is to retrieve a value from a website, modify it using variables and print the final value. My knowledge of classes and objects is very very minimal. I just cannot figure out how I can take the value numTotal from my function getPlays and use it later to print as Final. The value prints correctly from within the function I just need to store that value for later use as a variable.
class GetPlaycount(object):
def getPlays(self):
print "Working"
browser = webdriver.PhantomJS('C:\Python27\phantomjs-2.0.0-windows\phantomjs.exe')
browser.get('https://osu.ppy.sh/u/4973241')
time.sleep(1)
Plays = browser.find_element_by_xpath('//*[#id="general"]/div[8]').text
numPlays = int(re.sub('[^0-9]', '', Plays))
numTime = int(numPlays) * int(numLength)
numTotal = int(numTime) * float(numVar)
print int(numTotal)
return numTotal
myClassObject = GetPlaycount()
myClassObject.getPlays()
Final = ????
print Final
raw_input("wait")
Thank you for your help and patience.
If I understand the question correctly
final = myClassObject.getPlays()
print final
Should be all you need.
Good day :)
So during the day, I decided to make a gambling simulation. I'm testing a fail gambling strategy (So mine you if you try to tried my method)
Let me show my code, then the whole thing what happened.
from random import randint
winningNumber=0
bankroll=5000
testCase=1
betLevel=0
bettingLevel=[1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987]
town=[]
bet=0
#----------------------------
my_file= open("output.txt","w")
my_file.write(" # Bet Number Outcome bankroll "+"\n")
def startTheSimulation():
print "OK"
for i in range(100):
if bankroll==0:
break
global betLevel
if bankroll < bettingLevel[betLevel]:
betLevel=0
bet= bettingLevel[betLevel]
print "betlevel",betLevel
print "bet",bet
winningNumber= randint(0,36)
print "winningnumber",winningNumber
if winningNumber== 4:
win(bet)
else:
lose(bet)
def win(inbox):
global bankroll
cow= inbox*35
bankroll+=cow
print "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"
print "bankroll",bankroll
town=[testCase,bet,winningNumber,"WIN",bankroll]
print town
betLevel=0
writing()
def lose(inbox):
global bankroll
global betLevel
wow= inbox
bankroll-=wow
town=[testCase,bet,winningNumber,"LOSE",bankroll]
betLevel+=1
if betLevel==16:
betLevel=15
writing()
def writing():
global testCase
testCase+=1
print "Hey!"
my_file.write(" ".join(town)+"\n")
startTheSimulation()
my_file.write("On all betting, player bet single bet on one number, which is number 4. How money money bet on number for is indicated.")
my_file.close()
My betting system is a weird one. It works like martingale betting system, but instead of doubling my bet, my next bet is based on Fibonacci sequence.
The parameter betLevel is used to decide how many should I bet. The bettingLevel shows the list of the Fibonnaci sequence.
Here comes trouble
Trouble #1:
My output contains blank line
The desired output file is this
& Bet Number Outcome bankroll
# 100 lines of information
On all betting, player bet single bet on one number, which is number 4. How money money bet on number for is indicated.
However, I in turn got this
& Bet Number Outcome bankroll
# 100 BLANK LINES
On all betting, player bet single bet on one number, which is number 4. How money money bet on number for is indicated.
My debugging process:
I actually print the list town. The list if filled (not empty). No other improvement.
Trouble #2: (Solved by using function with arguments.)
My bank roll doesn't update.
My debugging process:
I figured out the problem.
Notice the win function. When I print (int(35)*int(bet)). It turns out to return 0, causing the bankroll not moving.
HOWEVER
When I print "bet",bet in the startTheSimulation() function, it prints the right number. I'm stucked here.
That's my 2 biggest problem. Any help is appreciated.
PS: I use global to avoid UnBoundLocalError
PPS: I use Python 2.7.6
Your logic seems quite convoluted for a fairly simple process. Also, you write things like int(35), that tell me you just came to Python from another language (IDL, perhaps?).
If you are using this as an exercise to learn, I can give you a few hints on how to solve it:
First of all, global variables are almost always a bad idea. If you need to use one, you are probably doing something wrong. The proper way of sharing this information is creating a class. Something like this (very incomplete)
class Simulation(object):
def __init__(self, bankroll):
self.betlevel = 0
self.betting = [1, 1, 2, 3, 5] # You should actually generate this on the fly
self.bankroll = bankroll
self.outputfile = open('filename.txt', 'w')
def do_bet(self):
self.bet = self.betting[self.betlevel]
luckynumber = random.randint()
mynumber = random.randint()
if mynumber == luckynumber:
self.win()
def win(self):
self.bankroll -= self.bet
self.outputfile.write('I won:' + str(self.bet))
The idea is that the class methods have access to the class attributes, so you totally avoid global variables, and reduce the possibility of mistake.
Try to complete the implementation. Once you have it, you can post it again and we can see if there are improvements.
Trouble #1:
you didn't set town as global, so this will print correctly:
town=[testCase,bet,winningNumber,"WIN",bankroll]
print town
, but in writing() method town is empty, and that's why you get 100 empty lines
here is example:
#global town #uncomment if you want to change "town" in "one()"
town = ["not", "changed", "town"]
def one():
#global town #uncomment if you want to change "town" here
town = [1,"local", "town", True]
print "local -> ", town
def two():
# you don't need "global town" here because you do not change it, you only use it
print town
one()
two()
this is output:
local -> [1, 'local', 'town', True]
['not', 'changed', 'town']
Trouble #2:
similar as trouble #1, in startTheSimulation(): you need to write global bet , otherwise bet is local variable and never gets changed, that's why it's 0 in your win() method.
Those are solutions for your problems , but consider creating a class, like #davidmh said...global variables are almost always a bad idea