class and functions in python [closed] - python

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 8 years ago.
Improve this question
I'm new to Python and I'm trying classes and objects, I have this script:
#!/usr/bin/env python
class test:
def __init__(self, username):
self.username = username
def name_again(self):
for i in range(0-4):
print ("username is %s" %self.username)
ahmed = test('ahmbor')
ahmed.name_again()
I'm expecting this script to print "username is ahmbor" 5 times
When I run this script, I have nothing
Please help find what's wrong with this

You are telling range() to loop over 0-4 (subtract four from zero), which is -4. Because the default is to start at 0 and count up, that is an empty range:
>>> range(0-4)
range(0, -4)
>>> len(range(0-4))
0
Use a comma instead, and use 5 to loop 5 times, not 4. The endpoint is not included:
>>> len(range(0, 4))
4
>>> len(range(0, 5))
5

Related

(Python) Why is my while loop not working? [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 5 months ago.
Improve this question
I have been working on an operating system inside of Python and I am starting off with the system booting code. I have a while loop that executes when the variable "Booting" = 1. Inside the while loop is a script that prints "Booting" then replaces that with "Booting.", then it gets replaced with "Booting.." and so on until it reaches "Booting....." which should make it reset to "Booting" and reset the cycle. Instead, it just stops at "Booting....." and doesn't continue to reset the cycle.
Here is the code:
import time
import sys
Booting = 1
while Booting == 1:
print("Booting")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting.")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting..")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting...")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting....")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting.....")
sys.stdout.write("\033[F")
time.sleep(0.2)
it does not erase the rest of the line, so you need to replace any existing variables you want to overwrite with spaces
try
...
print("booting ")
...
print("booting. ")
...
etc
(there are many ways to clear the line this is just one (#code provides another good alternative in the comments)

Uncaught Error: NameError: name 'true' is not defined [duplicate]

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 7 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to use Boolean ( true / false ) in my python source file, but after running the application, I receive the following error:
NameError: name 'true' is not defined
The error lies on while true:, when I am trying to make the Raspberry Pi run a HTML script when it receives input on port 17:
import RPi.GPIO as GPIO
import time
import os
inputSignal = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(inputSignal,GPIO.IN)
while true:
if (GPIO.input(inputSignal)):
os.system("html /home/pi/index.html")
else:
print("No Input")
Python’s boolean constants are capitalized: True and False with upper case T and F respectively.
The lower-case variants are just valid free names for variables, so you could use them for whatever you want, e.g. true = False (not recommended ;P).
You haven't defined a variable true. Maybe you meant the built-in boolean value True?
while True:
# but seems like inifite loop

Yes / No Function Always Returning False :( [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
I'm completely new to programming and am trying to write a function that takes a yes or no question. However, when I run the below it always seems to complete with my variable as False. There has to be something simple here that I'm missing. I'd love to hear any thoughts / feedback / improvements to it. Thank you!
def yes_or_no(question):
answer = input(question).lower().strip()
print("")
while not(answer == "y" or answer == "yes" or \
answer == "n" or answer == "no"):
print("\nSorry, only Y or N please.")
answer = input(question).lower().strip()
print("")
print(answer)
if answer == 'y' or answer == 'yes':
answer = True
else:
answer = False
You forgot to return the answer, so that function returns None by default. Add return answer at the end of the function.

Python can't implement timeit module [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
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.
Improve this question
This is a basic exercise. I just don't know hot to implement the timeit module correctly. I keep recieving syntax errors
import timeit
import random
def bubblesort(LAux):
for i in range(len(LAux)):
exchange = False
for j in range(len(LAux)-1):
if LAux[j] > LAux[j+1]:
tmp = LAux[j+1]
LAux[j+1] = LAux[j]
LAux[j] = tmp
exchange = True
if not exchange:
break
return(LAux)
a=int(input("Size of list: "))
lst = [0]*a
for i in range(a):
lst[i] = random.randint(1,100)
print(bubblesort(lst))
print(timeit.timeit()
You seem to have misinterpreted the function of timeit.timeit - the idea is that you tell it what to actually time, and it then times it. Normally, it does the thing you're timing many, many times, so you can get a meaningful average. This means it also needs to provide a 'setup' argument, as the list should presumably be different for each test. Refer to the examples in the documentation if you need - I normally find that they're easy enough to suit to your purpose. I've implemented timeit below:
a=int(input("Size of list: "))
n = 100000
setup = "lst = [random.randrange(100) for _ in range(a)]"
time = timeit.timeit("bubblesort(lst)", setup=setup, globals=globals(), number=n)
print("{} sorts took {}s".format(n, time))
Of course, if you're using IPython you can do something like this:
In [1]: from bubble import bubblesort
In [2]: from random import randrange
In [3]: %timeit bubblesort([randrange(100) for _ in range(50)])
10000 loops, best of 3: 175 µs per loop
Maybe you were expecting timeit() to tell you just how much time has passed. If so, this could be done using the time module, quite simply.
import time
start_time = time.time()
bubblesort(lst)
time_taken = time.time() - start_time
print("One sort took {}s".format(time_taken))
On another note, I'd recommend using a different name for the argument "Laux". As you can see, SO's syntax highlighting thinks it's a class, as normally anything starting with a capital letter is a class. Laux also doesn't particularly tell me as an outsider what it is, although I can infer from the name bubblesort.

Syntax error when using __init__ [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 8 years ago.
Improve this question
I apologize if the answer is obvious, but for some reason, the following code gives me a syntax error at every line after def _ _ init _ _ block.
If I simply comment out init, the entire program works fine however.
import graphics
from graphics import *
class Block:
def __init__(self,x,y,win,fid,length,orien,colour):
wind = win
if (orien == "horizontal"):
topL,dump = getPoint(fid)
lightRect = Rectangle(getPoint(fid)
# else:
# x =5
def draw(self):
return
def undraw(self):
return
def highlight(self):
return
def unhighlight(self):
return
def switchHighlight(self):
return
def move(self,target):
return
Any help would be greatly appreciated!
Missing ")" in:
lightRect = Rectangle(getPoint(fid)

Categories