So, kind of new to python, as I kinda started learning it a few months ago. I'm currently trying to make my own game (not expecting it to be super good, but I want it to work decently) The game is basically going around a dungeon, fighting monsters, leveling up, doing puzzles, and then fighting the final boss. Basically, your average RPG game. I am making it all text though. Currently stuck on a bit of code for my levelup script and my stats script. I have a variable in stats called "constitution", and whenever i level up (if exp >= expmax) i add 3 to the value of constitution. (starts out at 10)
import LevelUP
constitution = 10
that one is my code in the Stats script, and the one is the code in the LevelUP script.
import Stats
level = 1
expMax = 100
exp = 100
if exp >= expMax:
level=level+1
exp = 0
expMax = expMax+expMax*0.5
Stats.constitution = Stats.constitution+3
Stats.strength = Stats.strength+4
Stats.dexterity = Stats.dexterity+4
Stats.intelligence = Stats.intelligence+3
Stats.wisdom = Stats.wisdom+3
Stats.charisma = Stats.charisma+2
Stats.luck = Stats.luck+2
This is the error that comes up
Traceback (most recent call last):
File "main.py", line 3, in <module>
import Stats
File "/home/runner/Stats.py", line 1, in <module>
import LevelUP
File "/home/runner/LevelUP.py", line 9, in <module>
Stats.constitution = Stats.constitution+3
AttributeError: module 'Stats' has no attribute 'constitution'
exited with non-zero status
Kind of new to the site, but I have looked around for something like this and all i could find was using print() in different scripts.
There is a cyclic import in your code. Please see Circular imports in Python with possible undesired behaviours.
Anyway, it seems that your Stats module does not need LevelUp (does it?). I suggest rethinking your architecture.
Related
I'm learning python, now I'm learning for and while, the exercise that I'm doing asks me to make the square of a number using a for loop.
So I'm trying to make it but I don't know how to solve a problem, that I know why it is there, but I don't know how to solve it.
Anyway here's the code
def main():
#start
givn_n = eval(input("Tell me the number:\n"))
for i in givn_n:
#start
double_givn_n = givn_n ** 2
print(double_givn_n)
#end
return
#end
main()
The error is:
Traceback (most recent call last):
File "C:\Users\Simone\Desktop\progetto python\Tutorial-python\w ext libraries\somma_quadrati.py", line 12, in <module>
main()
File "C:\Users\Simone\Desktop\progetto python\Tutorial-python\w ext libraries\somma_quadrati.py", line 6, in main
for i in givn_n:
TypeError: 'int' object is not iterable
Your question has already been answered but I want to mention about how to improve your code.
eval is a dangerous function. I recommend you to not use it. In your case, int can be called.
What about something else. Simple. Try ast.literal_eval. Secure way of doing the evaluation.
def main():
# start
givn_n = int(input("Tell me the number:\n"))
for i in range(givn_n):
# start
double_givn_n = givn_n ** 2
print(double_givn_n)
#end
return # Your code already ends, I think no need to return :)
#end
main()
Your code needs a small correction
for i in range(givn_n):
I place the following in a .py script. Note the need for absolute value:
#!python
givn_n = abs(int(input("Tell me the number:\n")))
double_givn_n = 0
for i in range(0,abs(givn_n)):
double_givn_n += givn_n
print(double_givn_n)
I am teaching myself Python and am trying out a challenge I found to create a quote program for a gardener. I have almost all of it working and have added in iteration so that the user can make more than one quote without re-starting the program.
It produces the quote perfectly the first time but on the second run it presents this error:
Traceback (most recent call last):
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 105, in <module>
lawn = m2_items("lawn",0)
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 23, in m2_items
minutes = area*time[index]
TypeError: 'float' object is not subscriptable
I have the following code as a function that is producing the error:
def m2_items (item,index):
global costs, time, LABOUR
length = int(input("How long is the "+ item+"?\n"))
width = int(input("How wide is the "+item+"?\n"))
area = length*width
cost_m2 = float(costs[index])
total_cost = area*cost_m2
minutes = area*time[index]
hours = int(minutes/60)
labour = LABOUR*hours
labour_cost=round(labour,2)
m2_details = [area, cost_m2, total_cost,hours, labour_cost]
return m2_details
I have tried re-setting the local variables on the running of the function (but I didn't think this was needed as the variables should be removed from memory once the function has run).
I hope the question is clear and that I can get some insight. To re-iterate, what I want the program to do is allow me to call this function multiple times.
You are using the global time variable, which is initially subscriptable (probably an array). As your program continues, some other part of your code will assign a new value to time, maybe accidentally because you wrote time = some_calculation() instead of time[i] = some_calculation(), or maybe you are using the name time somewhere else without realizing it's already in use.
Do a search for all the places where you use the name time and you will probably find your error.
This is a common problem with global variables. Sometimes something updates them from another part of the code, and the error will sneak up on you like this.
Right now I'm working on making Python "type" on your screen (I was feeling bored and experimental), and I got this far on my own, but I can't find any way to use decimals in my script, as Python only accepts whole numbers for randint().
#include <stdio.h>;
import sys;
import time;
import os;
import random;
os.system("clear");
script = "I just really need to type something right now. I'm not sure why, but I really feel like typing on the Chromebook right now. It seems kinda weird, but I like doing this. It helps me practice what I'm doing. I've noticed that I'm a lot worse at typing lately, and I don't know why. Maybe it's because I've been working with a chunky keyboard, and these Chromebook keyboards are extremely thin. Yup, this is actually entertaining for me. I'm not exactly sure why I want to do this, but I just do. It's almost addicting to me, and I don't know why.\n";
for i in range(0, 587):
sys.stdout.write(str(scripti));
sys.stdout.flush();
time_num = random.randint(0.1, 0.4);
time.sleep(time_num);
The output I get is:
ITraceback (most recent call last):
File "main.py", line 11, in <module>
time_num = random.randint(0.1, 0.4);
File "/usr/lib64/python2.7/random.py", line 242, in randint
return self.randrange(a, b+1)
File "/usr/lib64/python2.7/random.py", line 187, in randrange
raise ValueError, "non-integer arg 1 for randrange()"
ValueError: non-integer arg 1 for randrange()
Any ideas?
EDIT: Don't tell me how to make this simpler, as this was just for learning.
Why don't you use the random uniform distribution instead? In this case you can get non integer number values. Use:
import random
random.uniform(0.1,0.4)
If you have to use randint, you could do time_num = randint(1, 4)/10.
for i in range(0, 587):
... nothing is indented there (unless you didn't post the indents in the question).. so it's practically useless
For the time_num Variable you could cast it like this:
time_num = double(random.randrange(1, 4) \ 10
you must be trying to get it in milliseconds because python uses Seconds for the time import
but you could also rephrase it like instead of using randint use random.randrange(#1, #2)
And I don't know the sys import but you used this -> sys.stdout.write(str(scripti));
BUT your variable is named "script".........
I'm fairly new to python and understand that recursion is an important concept to grasp. I've been dabbling with various scripts to exercise my knowledge and have come up with the following script to simulate a lottery draw, where you simply draw six from 49 numbers and compare them with another six to see if you've won. I'm struggling though with the recursive function taking the value of another function.
I'm sure it's going to be straightforwardish, but cannot fathom it myself.
Here's my code so far:
from random import randint
def drawSix():
six = []
while len(six) < 6:
a = randint(1,49)
if a not in six:
six.append(a)
return sorted(six)
def lottery(draw,ticket):
if draw == ticket:
return 'win'
return lottery(drawSix(),drawSix())
I call the function with lottery(drawSix(),drawSix())
and get the following recursively.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
lottery(drawSix(),drawSix())
File "/Users/johnhopkins/Desktop/lottery.py", line 14, in lottery
return lottery(drawSix(),drawSix())
def lottery(draw,ticket):
if draw == ticket:
return 'win'
return lottery(drawSix(),drawSix())
The odds of you actually generating two identical tickets are quite large, well over 1000 which is the maximum stack size of Python.
You need to either do this iteratively to avoid blowing your stack.
def lottery(draw,ticket):
while draw != ticket:
draw, ticket = drawSix(), drawSix()
return "win"
Note this has a very ugly O(n) of O(inf) you could end up running this forever if you were unlucky and still not finding a winning pair
Well, your question has has been answered, but I would suggest changing your drawSix function. As it is now, it could technically run forever. random has a sample method to generate unique numbers.
def drawSix():
return sorted(random.sample(range(1, 50), 6))
Yes - the lottery function will keep on calling itself, each time putting a new version of itself onto the call stack, going deeper and deeper into itself until there are two matching numbers.
This can take a long time, and Python will eventually say "oi! stop it!" and crash.
Some programming languages have a feature called 'tail call optimisation', which means if you try to return the result of the same function, instead of making a new call to the function inside the current one, it simply replaces itself in the stack.
Python doesn't do that.
def lottery():
while (drawSix() != drawSix()):
continue
return 'win!'
will have the same effect as your recursive version, but won't die with recursion errors.
You have not made any programming mistakes. However, the probility of winning the lottery is very small, so you need to generate a lot. Easy recursion add something to the stack.
Number of lotto tickets can be found by the formula for combinations with repetition:
(49+6-1)! / (6! * (49-1)!) = 25827165
This is a lot... Decrease the number 6 or 49, add some debugging lines and you'll see that the code works fine!
I'm stucked on the chapter 3.3 "Math functions" of "Think Python".
It tells me to import math (through the interpreter).
Then print math and that I should get something like this:
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
Instead I get <module 'math' <built-in>>
Anyway that's not the problem. Though I wasn't able to find a 'math.so' file in my python folder. The most similar file is named test_math.
The problem is that I'm supposed to write this:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
When I write the first line it tells me this:
Traceback <most recent call last>:
File "<stdin>", line 1, in <module>
NameError: name 'signal_power' is not defined
On the book says "The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that signal_power and noise_power are defined)."
So I assume that the problem might be that I didn't defined 'signal_power', but I don't know how to do it and what to assign to it...
This is the first time that I feel that this book is not holding my hand and I'm already lost. To be honest I don't understand this whole chapter.
By the way, I'm using Python2.7 and Windows XP. I may copy and paste the whole chapter if anyone feels that I should do it.
Python is my first language and I already tried to learn it using "Learn Python the hard way" but got stucked on chapter 16. So I decided to use "Think Python" and then go back to "Learn Python the hard way".
You've figured it out - you have to set signal_power's value before using it. As to what you have to set it to - it's not really a Python related question, but 1 is always a safe choice :) While you are at it, don't forget to define noise_power.
You indeed need to assign a value to both signal_power and noise_power. The author likely left them out because the values are arbitrary. Even when supplied with exact values in a text, you should also play around with the values. After all, there's not much point in having you type anything in if the results on the screen are the same as on the page.
signal_power = 100
noise_power = 17
This particular example defines the mathematical relationship between variables. If it were presented as such, it wouldn't be such a mystery that exact values were left out, as they would be supplied by someone when using the formula. The same holds for the code sample.
The book is for an older version of python apparently. But that is unrelated to your actual question.
Try defining signal_power. For example
signal_power = 0
You can't use a variable without defining/declaring it first. When you say ratio = signal_power / noise_power,
you're trying to access two variables that the interpreter has never heard about.
Before telling the machine what to do with the variables, you have to introduce them to it first.
You do this by declaring them:
signal_power = 123
noise_power = 321
You can define them as any number you want, not only 123 and 321, but you must define them before using them.