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)
Related
I'm working on Visual studio about Python project. I have a module calls "module1.py" and main window "TestForPython.py"
I create and array and taking input from the user and using in function inside my main. I show you sample basic code (not my code) because of you can understand my question clearly.
dynamic_array = []
hexdec = input("Enter the hex number to binary ");
strArray = [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0]
dynamic_array = strArray
def FirstPointer(element):
print(int(element,16))
FirstPointer(dynamic_array[0])
Like I said you this is a basic code.However, my code is more longer and complicated, that's why I want to carry the function to the "module1" and call in the main.
Is there any way to do that?
Try this in the file you want to import (module1.py):
def ConvertHex(hexdec):
return [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0]
def FirstPointer(element):
print(int(element, 16))
In your main file (TestForPython.py), you can utilize these functions like this:
import module1
hexdec = input("Enter the hex number to binary ")
dynamic_array = module1.ConvertHex(hexdec)
module1.FirstPointer(dynamic_array[0])
If you are working with the same directory to achieve what you want, you only need to import module1 and use it's methods in your main.
If you're working with different directory then it is called package.
check documentation here
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.
Traceback (most recent call last):
File "C:\Users\sahib navlani\Desktop\gfh.py", line 107, in <module>
main()
File "C:\Users\sahib navlani\Desktop\gfh.py", line 98, in main
crit2.play()
File "C:\Users\sahib navlani\Desktop\gfh.py", line 34, in play
self.play -= play1
TypeError: unsupported operand type(s) for -=: 'instancemethod' and 'int'
I get this error whenever i put this code . I think this due to line self.play -= play
play1 = int(raw_input("Please enter the time for which you want to play = "))
self.play -= play1
It's because self.play is a member method. I think you have done mixing of names of member methods and member names. Give proper names to variables and be clear about the purpose for which you are using it.
I'm only guessing since you haven't shown us the code that's going wrong, but I think you're using the function name as a return value. This is a bad habit that Visual Basic teaches people -- nearly every other language uses return instead, which is what Python does. In Python, you would use a variable (I like to use result) to calculate what you'll return, then put return result at the end of your function. E.g.,
def addTwoNumbers(one, two):
# addTwoNumbers = one + two # Wrong!
result = one + two
return result
In a simple function like this, you could just write return one + two, but in more complicated functions, it's useful to use a variable to calculate the result, then return it at the end. So that's what I showed in this example.
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.
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!