I started learning python few weeks ago (no prior programming knowledge) and got stuck with following issue I do not understand. Here is the code:
def run():
count = 1
while count<11:
return count
count=count+1
print run()
What confuses me is why does printing this function result in: 1?
Shouldn't it print: 10?
I do not want to make a list of values from 1 to 10 (just to make myself clear), so I do not want to append the values. I just want to increase the value of my count until it reaches 10.
What am I doing wrong?
Thank you.
The first thing that you do in the while loop is return the current value of count, which happens to be 1. The loop never actually runs past the first iteration. Python is indentation sensitive (and all languages that I know of are order-sensitive).
Move your return after the while loop.
def run():
count = 1
while count<11:
count=count+1
return count
Change to:
def run():
count = 1
while count<11:
count=count+1
return count
print run()
so you're returning the value after your loop.
Return ends the function early, prohibiting it from going on to the adding part.
Related
so i'm doing the dna problem for cs50 wherein i have to count the number of times a STR repeats in a dna sequence. i had an idea on how to solve the problem so i took one of the data and ran my code but the problem is that the program doesn't end and keeps running i think it has been about 10 minutes now from when i started the program and it still like this. here's the code:
text="AAGGTAAGTTTAGAATATAAAAGGTGAGTTAAATAGAATAGGTTAAAATTAAAGGAGATCAGATCAGATCAGATCTATCTATCTATCTATCTATCAGAAAAGAGTAAATAGTTAAAGAGTAAGATATTGAATTAATGGAAAATATTGTTGGGGAAAGGAGGGATAGAAGG"
length=len(text)
AGAT=0
tmp=0
for i in range(length):
while text[i]=="A" and text[i+1]=="G" and text[i+2]=="A" and text[i+3]=="T":
tmp+=1
if tmp>AGAT:
AGAT=tmp
else:
AGAT=AGAT
print("done")
As mentioned in the comments there is an infinite loop in your while loop, you could just remove it and choose to use a sliding window technique where you go over the text looking at neighbouring slices of 4 adjacent characters at a time:
text = "AAGGTAAGTTTAGAATATAAAAGGTGAGTTAAATAGAATAGGTTAAAATTAAAGGAGATCAGATCAGATCAGATCTATCTATCTATCTATCTATCAGAAAAGAGTAAATAGTTAAAGAGTAAGATATTGAATTAATGGAAAATATTGTTGGGGAAAGGAGGGATAGAAGG"
search_seq = "AGAT"
count = 0
for i in range(len(text) - len(search_seq) + 1):
if text[i:i+len(search_seq)] == search_seq:
count += 1
print(f"Sequence {search_seq} found {count} times")
Output:
Sequence AGAT found 5 times
I know this is a weird way to solve your problem but i wanted to do something a bit different...
Try this:
agat_string="AAGGTAAGTTTAGAATATAAAAGGTGAGTTAAATAGAATAGGTTAAAATTAAAGGAGATCAGATCAGATCAGATCTATCTATCTATCTATCTATCAGAAAAGAGTAAATAGTTAAAGAGTAAGATATTGAATTAATGGAAAATATTGTTGGGGAAAGGAGGGATAGAAGG"
agat_list=[AGAT for AGAT in range(len(agat_string)) if agat_string.find("AGAT", AGAT) == AGAT] #finds the indices of "AGAT" ;-)
print(len(agat_list))
The output:
5
Also, as someone said, tmp has nothing to do with the while condition. It just throws you in an infinite loop....
I'm trying to learn python and while learning I've come across a bit of a problem.
import time
import pyautogui
def SendScript():
time.sleep(2)
with open('script.txt') as f:
lines = f.readlines()
for line in lines:
time.sleep(2)
pyautogui.typewrite(line.strip())
pyautogui.press('enter')
SendScript()
I'm trying to print something to the screen every second time the 'enter' key has been pressed, but I'm an extreme beginner so I really don't know how to do that. Could someone help me accomplish this task?
You could create a new boolean variable to track if the enter key has been pressed before. That way, every time the for loop iterates, the value of pressed switches and only when the value of pressed is True will it print something.
import time
import pyautogui
def SendScript():
pressed = False
time.sleep(2)
with open('script.txt') as f:
lines = f.readlines()
for line in lines:
time.sleep(2)
if pressed:
print("Something")
pressed = not pressed
pyautogui.typewrite(line.strip())
pyautogui.press('enter')
SendScript()
From a more step-back approach, you could do:
events=['event1', 'event2', 'event3', 'event4', 'event5', 'event6', 'event7', 'event8']
counter = 0
for event in events:
counter += 1
if counter % 2 == 0: # ie do stuff when divisible by 2, ie when its even
print('print what you want to be printed every second time')
else:
pass
Of course you are not looping through events like I do in this example. The point is counting the events and only doing stuff when this count is even.
As indicated in another answer already, a simple toggle can be implemented with a bool and then code which toggles it every time something happens:
thing = False
:
if happens(something):
thing = not thing
This is fine for toggling between two states. A more general approach which allows for more states is to use a numeric variable and a modulo operator:
times = 0
maxtimes = 12
:
if happens(something):
times += 1
if times % maxtimes == 1:
print("ding dong")
The modulo could be compared to 0 instead if you want to print on the 12th, 24th etc iterations instead of the first, the 13th, etc, or of course any other offset within the period if that's what you want.
Another useful trick is to flip-flop between zero and some other value.
value = 0
othervalue = 1234
:
if happens(something):
value = othervalue - value
Of course, you can flip-flop between any two values actually; subtract the current value from their sum to get the other one.
Needless to say, just toggling or flip-flopping isn't very useful on its own; you'd probably add some (directly or indirectly) user-visible actions inside the if happens(something): block too.
You could use a generator for this:
def everySecondTime():
while True:
yield "hi"
yield "not hi"
mygen = everySecondTime()
print(next(mygen))
print(next(mygen))
print(next(mygen))
print(next(mygen))
This prints
hi
not hi
hi
not hi
I'm sure it's clear to you how you could adapt this to do some other actions instead.
Whether this approach is better than just using a boolean is highly debatable, but I thought I'd leave it here so you could learn about generators (the yield keyword) if you want to.
I have no idea anymore. I've been struggling for hours now.
I got a pi2golite here with wheel sensors.
the wheelCount() isn't working anyway (or at least I dont know how)
so I've been trying to find another solution.
The 2 motors I've got seem to run on different speed's. I wanted to see that in numbers to change the speed of each motor so they run the same.
import pi2go, time
pi2go.init()
running = True
countL = 0
countR = 0
def counter1():
global countR
countR += 0
speed = 60
try:
pi2go.stepForward(50,10)
time.sleep(2)
print counter1()
print countL
finally:
pi2go.cleanup()
->
When I try to run it, the motor's run fine and turn off after the 10 steps (so it has to be counting)
it outputs this:
for countL -> 0
for counter1() ->None
Why none?
This is expected bahaviour.
If you run code in a Python shell, then when you write an expression, the shell will print the result of the expression.
For a function call, this is what the function returns. In Python every function returns something. In case you do not specify a return statement, then None is returned. Some shells do not print None, but anyway, the result is None of sucht call.
So the function updates countR, then performs return None (implicitly). This is the result of the function call, and so the shell prints this. If you run code without the shell, then nothing is printed (as in no content at all).
You can let the function return the updated value. Furthermore you probably want to increment the value, so += 1:
def counter1():
global countR
countR += 1
return countR
I'm trying to write a function to count how many lines in my input file begin with 'AJ000012.1' but my function keeps returning None. I'm a beginner and not entirely sure what the problem is and why this keeps happening. The answer is supposed to be 13 and when I just write code eg:
count=0
input=BLASTreport
for line in input:
if line.startswith('AJ000012.1'):
count=count+1
print('Number of HSPs: {}'.format(count))
I get the right answer. When I try to make this a function and call it, it does not work:
def nohsps(input):
count=0
for line in input:
if line.startswith('AJ000012.1'):
count=count+1
return
ans1=nohsps(BLASTreport)
print('Number of HSPs: {}'.format(ans1))
Any help would be seriously appreciated, thank you!
(HSP stands for high scoring segment pair if you're wondering. The input file is a BLAST report file that lists alignment results for a DNA sequence)
When you simply return without specifying what you are returning, you will not return anything. It will be None. You want to return something. Based on your specifications, you want to return count. Furthermore, you are returning inside your for loop, which means you are never going to get the count you expect. You want to count all occurrences of your match, so you need to move this return outside of your loop:
def nohsps(input):
count=0
for line in input:
if line.startswith('AJ000012.1'):
count=count+1
return count
EDIT:
Hi, earlier, I posted this question in a way that very lengthy. I am new to this site and did not know about the customs of posting. I will try again and be more specific with my question.
I moved a bit of my code into a tester file and this part returns an error. It seems that my count for blackpegs is not increasing because local variable 'blackpegs' was references before assignment.
blackpegs = 0
def test_guess(code,guess):
for x,y in zip(code,guess):
if x==y:
blackpegs += 1
return blackpegs
First, what does this mean? Secondly, how do I fix it?
You should move the variable definition to within the function definition. I'm guessing you also want the "return" statement to be indented at the same level as the if statement, so that it goes through the for loop rather than exiting after the first instance where x==y.
def test_guess(code,guess):
blackpegs = 0
for x,y in zip(code,guess):
if x==y:
blackpegs += 1
return blackpegs