How would you make variables in python (you'll see) - python

Please Note That This Happened In 2019 So I picked up a few things from then
So please don't judge me.
So I have decided to try and make a very basic language in python.
And it is pretty basic right now but I want to improve it.
And one thing all languages need: variables
And right now I have this:
# Some other if statements up here
# neon is the name of the variable
# Something programmed real quickly to show example
elif neon[0:6] == ("addvar"):
var = neon[7:]
elif neon.startswith("add"+ var):
invar = neon.split("add"+ var , 1)[1]
elif neon.startswith("out"+ var):
print(invar)
YES it is very messy and horrid but I had to start with something and it is
very buggy. I had to start working on math so I skipped out on the variables. I tried a few tests before e. g. Appending data to a list and whatnot.
My Problem:
It only lets me have one variable
But now I wonder if there is a way that finally goes through the lexer and parser
Please tell me if there is

Use a dictionary to hold all your variables.
variables = {}
# some other code here
elif neon.startswith("addvar "): # addvar variablename
var = neon.split()[1]
variables[var] = None # create empty variable
elif neon.startswith("add "): # add variablename value
_, var, value = neon.split()
variables[var] = value
elif neon.startswith("out "): # out variablename
var = neon.split()[1]
print(variables[var])

Related

itertools.cycle(['eng', 'rus']).__next__ not works properly

Ayo, guys
Im started to learn python 2 days ago and started with simple Translator
My problem is:
I wanted to write "#" to the console, my values change, but I don't know how to achieve that "Toggle" effect, when when writing "#" is chekcing if language number 1 is enabled and I change it to language number 2 and vice versa, if Language number 2 is enabled then switch to Language number 1
I found a solution on the Internet by:
var = itertools.cycle(['1', '2']).__next__
However, I can't get langtoggle to give me values one by one
At the moment, I'm stuck on this moment, which gives me value number 2 and does not want to change it to value 1
Please tell me what am I doing wrong?
Thank you :)
import itertools
langtoggle = itertools.cycle(['eng', 'rus']).__next__
engstroke = 'ENGLISH > RUSSIAN'
russtroke = 'RUSSIAN > ENGLISH'
lstroke = engstroke
while True:
print (lstroke)
word = input('Введите слово: ')
if word == '#':
while True:
langtoggle()
if langtoggle() == 'eng':
lstroke = engstroke
if langtoggle() == 'rus':
lstroke = russtroke
break
to be honest, I need a solution what let me change to 1,2,3 and more values by same action so thats why I dont want to use boolean value for that problem
Also, I notice that "var()" cycling to next value even if im just checking this var in "if var() = 1"
that looks strange, but I dont understand a huge things in coding right now, so..
In your while block you're calling langtoggle() three times. Change this to be called only once.
Something like this:
import itertools
langtoggle = itertools.cycle(['eng', 'rus']).__next__
engstroke = 'ENGLISH > RUSSIAN'
russtroke = 'RUSSIAN > ENGLISH'
lstroke = eng
while True:
print (lstroke)
word = input('Введите слово: ')
if word == '#':
while True:
toggled = langtoggle()
if toggled == 'eng':
lstroke = engstroke
if toggled == 'rus':
lstroke = russtroke
break
This is your code but modified by setting toggled to the result of the first call to langtoggle(). Then the tests are looking at the value of toggled instead of separate calls they were making previously.

Filtering results from lists Python

I have been trying to find the answer around the web without any results.
I am trying to create a system where a user can search through lists and return their subjects and grades, with a filter to only show subjects from one area (for example Informational science) and also filtering the level of the subject(if it is a 100lvl, 200lvl or 300lvl) I have tried with Sub_string but doesnt work properly.
So the view code i have so far(With sub_string) is this:
def finn():
global Karakterer
global Emner
print("Velg fag og/eller emnenivå (<enter> for alle)")
Fag = input("-Fag: ")
for sub_string in Emner:
if str(Fag) in sub_string:
print(*([sub_string] + ([Karakterer[sub_string]] if sub_string in Karakterer else [])))
these are my lists (converted to Dicts for it to work)
Emner = ["INFO100","INFO104","INFO110","INFO150","INFO125", "RELV102"]
FagKoder = [["Informasjonsvitenskap","INF"],["Kognitiv vitenskap","Kog"],
["Religionsvitenskap","REL"],["DigitalKultur","DIK"],["Økonomi","ECO"]]
Karakterer=[["INFO100","C"],["INFO104","B"],["INFO110","E"], ["RELV102","A"]]
Karakterer=dict(Karakterer)
FagKoder = dict(FagKoder)
This is how it is printed out now, and is the way i need it to be printed:
My problem is that Sub_string dosent work properly for what i need, because i need to be able to allow the user to select an Area (INFO for example) and aswell a spesific level so (level 200) and then print out all INFO subjects at level 200.
But sub_string only litteraly checks that the string is contained in the list and prints that.
Does anyone have a better soluting?
hope that makes sense
Thank you!
A minimal fix might be to split out the number from the end and compare that separately.
def finn():
global Karakterer # ugh
global Emner # ugh
want_subj = input("Velg fag (<enter> for alle): ")
want_level = input("Velg emnenivå (<enter> for alle): ")
try:
want_level = int(want_level)
except ValueError:
want_level = None
for subject in Emner:
# no need for str(Fag); input by definition returns a string
if want_subj in subject:
if not want_level or int(subject[-3:]) == want_level:
print(*([sub_string] + ([Karakterer[sub_string]] if sub_string in Karakterer else [])))
A better solution might be to store the courses and their level as separate items so you don't have to parse out the number when you need it. (As an aside, you should not assign to a list and then recast as a dict when you can easily define a dict directly.)
Emner = [("INFO",100),("INFO",104),("INFO",110),("INFO",150),("INFO",125, ("RELV",102)]
FagKoder = {
"INF": "Informasjonsvitenskap",
"Kog": "Kognitiv vitenskap",
"REL": "Religionsvitenskap",
"DIK": "DigitalKultur"
"ECO": "Økonomi"
}
It should be fairly obvious how to adapt the code to work with these structures instead.
(As an aside, you seem to have "RELV" in Emner but "REL" in FagKoder.)

Can i have multiple global varibles within a python script?

Is it possible to have more than one global variable within a python script?
import os,csv,random
def user():
global Forname
Forname = input('What is your forname? ').capitalize()
while True:
try:
global answerr
answerr = input('Welcome to the phone troubleshooting system '
'\nApple\nSamsung '
'\nOut of the following options enter the name of the device you own ').lower()
except ValueError:
continue
if answerr in ('apple','samsung'):
break
myfile = open(answerr+'_device.csv','r')
answer = input(Forname + ', do you have anymore problems? ').lower()
if 'yes' in answer:
#do whatever
else:
#do whatever
Using the global variable 'answerr' I'd like to open a csv file, and the refer to the user with the forname they input, but I want to use them multiple times through out my code within def functions. I apologise in advance if you do not understand what I'm asking, I'm relatively new to coding given the fact that I'm still a school student.
Of course it's possible. But there is absolutely no reason to use any global variables in this code, let alone multiple.
The point of a function is that it can return a value:
def user():
forename = input('What is your forename? ').capitalize()
return forename
Can I have multiple global variables within a Python script?
Yes and here's how:
When you're assigning any variable at the top-level of a module like: n = "Stackoverflow!" then your variable is global automatically. So let's say we have this modules:
#globals.py
x = 2 + 2
y = 5 + x
both x and y are global variables which means they're accessible to functions, classes and so on. *Just remember any assignment at the top-level of a module is actually global (this is what we call a global scope and it can contain as much variables as your memory allows). This is just like the code you posted. However, what we cannot have is same named variables in any scope:
same = 20
same = "s"
print(same)
will print s, not 20.
Hope you'll find this helpful :-)

Assigning variables from a list, or "how to make an elegant save function"

I'm currently working on a small text based game, the game remembers the gamestate based on global variables, for example, goblins_dead to see if you've killed the goblins yet.
This worked pretty well, until I decided to add a save and load function. The save function works, the load function does not, and while I know why, I can't come up with an easy fix.
The way the save function currently works is this, I have a list with all the global variables we've used in the game so far. Then I have the list run through each varaiable and give a 1 if its true or a 0 if its not, at the end it prints a "seed" that consists of a list of 1s and 0s the user can input. It looks like this, in my sample test code
def game_save():
print "This will give you a seed. Write it down, or see seed.txt"
print "When you start a new game, you will be propted to give your seed. Do so to reload."
global goblins_defeated
global lucky
global princesshelp
end = "done"
load_seed =[goblins_defeated, lucky, princesshelp, end]
load_seed.reverse()
variable = load_seed.pop()
seed = []
print globals()
while end in load_seed:
if variable == True:
seed.append("1")
print "APPENEDED 1"
print load_seed
variable = load_seed.pop()
elif variable == False:
seed.append("0")
print "APPENED 0"
print load_seed
variable = load_seed.pop()
else:
print "ERROR"
break
seedstring = ' '.join(seed)
print "This is your seed %s" %seedstring
This code works, it yields a string, that matches the values in the way I want.
The issue comes when its time to load. I inverted this process, like this:
def game_load():
print "Please type your seed in here:"
global goblins_defeated
global lucky
global princesshelp
end = "done"
seedlist = [goblins_defeated, lucky, princesshelp, end]
seed = raw_input("> ")
seed_list = seed.split(" ")
seed_value = seed_list.pop()
variable_list = [end, goblins_defeated, lucky, princesshelp]
variable = variable_list.pop()
testlist = []
while end in variable_list:
if seed_value == '1':
variable = True
print variable_list
print variable
print seed_value
elif seed_value == '0':
variable = False
print variable_list
print variable
print seed_value
else:
print "ERROR ERROR FALSE LOOP RESULT"
break
if bool(seed_list) == False:
print "List is empty"
else:
seed_value = seed_list.pop()
variable = variable_list.pop()
The mistake will be obvious to more seasoned programmers, it turns out lists load what a variable points at, not the variable name, so I can't assign things in this way.
This is where I'm stumped, I could just make a long list of if statements, but that's not very elegant. Further reading suggests that a dictionary approach might be the way to solve this, but I'm unsure on how I would go about implementing a dictionary, more specifically, I'm not sure how dictionaries interact with variables, my understanding is that this is how variables are actually stored in python, but I'm not sure how to get started on accessing and storing those variables reliably, or if I could use a global dictionary to store all my variables in the game properly. Basically, I'm unsure of how to "correctly" use a dictionary to its full potential, specifically how it interacts with variables.
That's much larger than necessary. Just use string formatting to provide the save password:
print 'Your seed is {}{}{}{}'.format(goblins_defeated+0, lucky+0, princesshelp+0, end+0)
Adding 0 converts each boolean into its numeric representation. Each value is inserted into the string, replacing the {}.
Load like this:
seed = raw_input("> ")
goblins_defeated, lucky, princesshelp, end = map(bool, map(int, seed.split()))
This splits seed on whitespace, maps each element to an integer, then maps each of those integers to a boolean, then unpacks that map object into the appropriate variables.
You don't necessarily have to store these conditions as booleans at all, as 1 and 0 will evaluate similarly, with 0 for False and 1 for True. Booleans are actually a subclass of int anyway. You can even do math with them, e.g. True+True equals 2.

Trying to return a True variable from a nested chain of functions (in Python)...

I'm trying to write part of an adventure game program in Python, and though I have most of it down, I'm stuck at trying to return a value declared as "True" at the end of one branch in the function chain. Basically, this is a fight against a monster, which you can win if you choose the right options. If you win, you obtain the bow that he was guarding. Here is the code of the fight:
#The first line imports all the text displayed in the game, saved in gametext.py
#For purposes of clarity, all text has been saved to variables imported by the file.
#Any variable that is not "HaveBow", "why" or declared by a raw_input() is actually text.
from gametext import *
def BG_fight():
print BowGuardIntro
print InitOptions
BGfirstmove = raw_input('> ')
if BGfirstmove == "1":
spearfight()
elif BGfirstmove == "2":
dead(BGUnarmed1)
else:
dead(BGUnarmed2)
def spearfight():
print GotSpear
print SpearFight
spearact = raw_input("> ")
if spearact == "1":
blindfight()
elif spearact == "2":
dead(SeeChest)
elif spearact == "3":
dead(SeeArms)
else:
dead(NoUseSpear)
def blindfight():
print BlindFight
followblow = raw_input("> ")
if followblow == "1":
print Victory
HaveBow = True
return HaveBow
elif followblow == "2":
dead(BlindArms)
else:
dead(BlindNoKill)
def dead(why):
print why
exit(0)
BG_fight()
(If people are interested, I can also produce the contents of the gametext file, though I would rather not as it is lengthy and has nothing to do with the problem I'm having)
As you can see, only one branch there offers the winning condition (which would give the HaveBow = True value that I want to return), and it is nested two functions deep and part of an if-statement. What I want to know is how I return that "HaveBow = True" value back outside the function chain, so it can be used in other parts of the game? If I try to code:
HaveBow = blindfight()
print HaveBow
at the end of the code and try to run it, it just makes me repeat that part of the game twice, before declaring "True". Same goes if I try BG_fight() instead of blindfight(). But I don't want that; I just want the "True" for "HaveBow" so I can use the condition "HaveBow = True" in other parts of the game.
In short, my question is whether or not it's possible to return a value from a nested function chain without repeating the code of that chain, and if so, how?
Thanks.
You can only return a value, not a name and a value. In other words, you cannot "return HaveBow = True"; all you can do is return True. There's no way to return a value and at the same time assign it to a variable that exists outside the function. If you want to assign the value, you need to do it outside the function.
From what you say, it sounds like you want HaveBow to be a global variable that you can use anywhere in your program. In that case, you can change your code in blindfight to do:
if followblow == "1":
global HaveBow
print Victory
HaveBow = True
Note that in this case you do not need to return the True value -- you just directly assign it to a global variable.
Ultimately there are better ways to structure your code, but those issues are out of the scope of this question. For the moment, I would suggest that, if you have global state like HaveBow that you want to be able to use "anywhere else in the game", you should make those global variables using global as I showed in my example. As you progress learning more programming, you will gradually learn why using global variables is not usually the best idea, but for the purposes of this program it is the simplest solution.

Categories