Output is still not iterating - python

My program still not iterating even count += 1 is implemented in the code, its seems that the code for count += is not being read. Please bear with me how I post my question.
NameInput = int(input("number of students to enter: "))
GradeInput = int(input("number of grades per student: "))
students = {}
class Student():
def GetInfo(students):
idnum = 0
count = NameInput
for c in range(count):
idnum += 1
name =(input("Enter Student " + str(idnum) + " Name: "))
if name in students:
print ("Student " + name + " has already been entered, please enter again.")
idnum -= 1
count += 1
else:
students[name] = []
for r in range(GradeInput):
grade =(float(input("Enter Student " + str(idnum) + " Grade: ")))
students[name].append(grade)
def printList(students):
for key in students:
print(key)
def main():
Student.GetInfo(students)
main()

The problem isn't the count += 1 itself. You can add some print statements throughout your code to see the value of count at various points in the execution.
The problem is that you want to change the number of iterations of your loop from within it. You wrote your loop:
for c in range(count):
The value of count is read when this statement is reached. The value is passed to range(), and the object returned is used to control the loop. Changing the value of count after this has no effect on your program because it is never used again.
One way to change your code would be like this:
c = 0
while c < count:
...
c += 1
This approach allows you to add to count in order to cause the loop to run more iterations. It is more code than the simpler for loop, but is more flexible.

Related

I am new to python programming, I need to count the user's names by taking user input who has length more than 5 characters in their names

count users' names:
def counts(a):
count = 0
for j in a:
if len(j) >= 5:
count = count+1
return count
print(count)
b = int(input("How many names do you wanna print? "))
for i in range(b):
a = input("Enter user's name one by one: ")
ans = counts(a)
print("these are the counted number of the user's names who has length more than 5 letters in the names: ",ans)
You arent storing the names as a list so they can be iterated as intended.
a = []
for i in range(b):
a.append(input("Enter user's name one by one: "))
And your indentation is wrong in counts. You're returning in the firstiteration of the loop:
def counts(a):
count = 0
for j in a:
if len(j) >= 5:
count = count+1
print(count)
return count
I hate for loops ! You can do it this way:
def more_than_five(a):
More_than_5 = [True for item in a if len(item)>=5]
Count = sum(More_than_5)
return Count
print(more_than_five(input('enter the names:\n').split()))
You should return the count only after completion the for loop, like this:
def counts(a):
count = 0
for j in a:
if len(j) >= 5:
count = count+1
print(count)
return count
UPD
The rest of the code should be fixed as well.
Try this:
a = []
b=int(input("How many names do you wanna print? "))
for i in range(b):
a.append(input("Enter user's name one by one: "))
ans=counts(a)
print("these are the counted number of the user's names who has length more than 5 letters in the names: ",ans)
this it what i would use:
names=[]
count_to_print=int(input("How many names do you wanna print? "))
counter_long_names=0
for counter in range(count_to_print):
name=input("Enter user's name one by one: ")
names.append(name)
if len(name)>5: # use >= for 5 or more characters
counter_long_names+=1
# names.append(name) #here if you only want to store the long names
print(counter_long_names)
you can leave out all the lines with "names" in the line if you dont want to store the names

How do I assign a boolean from second block of code to the first block of indentation in python?

When I assign the out_of_marks_limit = True in 5th block, I want the first block of if statement to be "True" and I don't want the code to loop or ask the user anymore.
In other programming language indentation is used to make the program look good. But because python only checks the condition of first block to the same indent, I can't assign boolean of 2 block of code to the first block.
This is what I'm trying to say.
I'm an intermediate level programmer and this program is just for practice purpose.
a = int(input("Enter no. of subjects: "))
count = 1
d = 0
out_of_marks_limit = False #I want the out_of_limit to be True
if a <= 10:
if not out_of_marks_limit:
if count <= a:
for c in range(a):
b = float(input("Enter mark of subject " + str(count) + ": "))
if b <= 100: #If this condition went false then it will skip to else statement
d += b
count += 1
if count > a:
cal = round(d/a, 2)
print("Your percentage is " + str(cal) + "%")
else:
out_of_marks_limit = True #So this boolean value should passed to the first line of code
print("Marks enter for individual subject is above 100")
else:
print("Subject limit exceeded")
I expect the output to print("Marks enter for individual subject is above 100"), if out_of_marks_limit is True and don’t want to loop anymore
I think you can use a while loop to check your out_of_marks_limit condition:
a = int(input("Enter no. of subjects: "))
count = 1
d = 0
out_of_marks_limit = False #I want the out_of_limit to be True
while not out_of_marks_limit:
if a <= 10:
if not out_of_marks_limit:
if count <= a:
for c in range(a):
b = float(input("Enter mark of subject " + str(count) + ": "))
if b <= 100: #If this condition went false then it will skip to else statement
d += b
count += 1
if count > a:
cal = round(d/a, 2)
print("Your percentage is " + str(cal) + "%")
else:
out_of_marks_limit = True #So this boolean value should passed to the first line of code
print("Marks enter for individual subject is above 100")
else:
print("Subject limit exceeded")

find average value and above average value using def function in python

here is my code so far. I'm not sure whether I do something wrong on the code because the average seems to be wrong. please help me. Thank you
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append(student_score)
results.append(student_name)
print(results)
return results
def calc_average():
total=0
total=total+student_score
average= total/scores
print("the average is ", average)
return
def above_average():
above_average=0
for i in range (scores):
if results [i] > average:
above_average = above_average + 1
print(" the above average score is ", above_average)
return above_average
enter_score()
calc_average()
above_average()
You're making a list results that contains scores and names alternating -- very hard to use. You return that list from enter_score, then completely ignore -- you throw it away! So the other two functions are supposed to work on some magic, or thin air...?
Clearly, the overall flow at the end must instead be:
results = enter_score()
average = calc_average(results)
above_average(results_average)
and calc_average must end with return average.
results is better arranged by replacing the two results.append calls with a single one:
results.append((student_score, student_name))
i.e, make it a list of tuple, not a weird mix of numbers and names.
The other two functions clearly must loop on that list (which they now receive as an argument) to do their respective jobs.
So:
def calc_average(results):
total = 0
for student_score, student_name in results:
total=total+student_score
average= total/float(len(results))
print(average)
return average
and:
def above_average(average, results):
above_average = 0
for student_score, student_name in results:
if student_score > average:
above_average += 1
print(" the number of above average scores is ", above_average)
return above_average
I fixed/ammended your code so that it works:
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append((student_name, student_score))
print(results)
return results
def calc_average(results):
total=0
for student_name, student_score in results:
total=total+student_score
average= total/len(results)
print("the average is ", average)
return average
def above_average(results, average_score):
above_average_no=0
for student_name, student_score in results:
if student_score > average_score:
above_average_no = above_average_no + 1
print(" the above average score is ", above_average_no)
return above_average_no
results = enter_score()
average_score = calc_average(results)
above_average_no = above_average(results, average_score)
I wont provide detailed explanation on what and why things changes. Leave it to you to figure it out. Please note that I tried to make minimal changes to your code. Many things could be improved, such as calculating sum, etc. Hope this helps.

Python is not recognizing my variables, but instead replacing them with zero

Here is my code:
change = 0
count = 0
value = 0
answer = 0
def numberTest():
if change == 0:
skip()
else:
value = change
def skip():
count + 1
number = value
# Check if the input is valid
if value != number:
print('PLEASE ENTER A VALID NUMBER!!!')
else:
Even = number % 2
if Even == 0:
print('Substituting even number in: x / 2')
print('%s/2=' % number)
answer = number / 2
else:
print('Substituting odd number in: 3x + 1')
print('3' + number + ' + 1=')
answer = number * 3
answer = answer + 1
answer = str(answer)
print(''+ answer +'')
if answer == 1:
finalValue()
else:
check()
def check():
value = answer
skip()
def loop():
value = int(input('Input a number: '))
change = value
skip()
loop()
def finalValue():
print('The number (' + change + ') returned as 1.')
print('A total of (' + count + ') commands were executed.')
change = change + 1
count = 0
print('')
print('')
print('')
numberTest()
Whenever I start the code, I am asked to enter a number (as expected), but then this happens:
Input a number: 1
Substituting even number in: x / 2
0/2=
0.0
I really do not understand why the program is not working as I expected, but there is one part of the code that I am suspicious of:
value = int(input('Input a number: '))
I also wrote this myself, and I am new to Python, I have only previously worked with batch, so transitioning was quite easy, though I am not very familiar with some of the commands...
EDIT
What I was expecting the program to do was ask for a number, store that number, then run it through a series of tests, but when the number gets to the actual tests, it substitutes "x" for "0", even if I type in a number such as "54656". Maybe, when it asks for the number, when I input the number, it just doesn't store it right, or something is wrong with my code...
You are trying to change global variables without declaring them:
a = 'bad'
def bad_fn():
a = 'good'
bad_fn()
print('bad_fn() is'+a)
def good_fn():
global a
a = 'good'
good_fn()
print('good_fn() is'+a)
results in
bad_fn() is bad
good_fn() is good
In general, using global variables in bad practice. Passing parameters explicitly makes debugging and code reuse much less of a headache. Here is rewritten version of your code which should be easier to understand:
# Test the Collatz conjecture:
# http://en.wikipedia.org/wiki/Collatz_conjecture
import profile
# Python 2/3 compatibility shim
import sys
if sys.hexversion >= 0x3000000:
# Python 3.x
inp = input
rng = range
else:
# Python 2.x
inp = raw_input
rng = xrange
# cache of already-seen values
seen = set([1])
def test(n):
visited = set()
while True:
if n in seen: # Ran into an already-seen chain that goes to 1
seen.update(visited)
return len(visited)
elif n in visited: # Closed loop! this should never happen
print('Loop found at n = {}'.format(n))
return None
else:
visited.add(n)
if n % 2: # n is odd?
n = 3*n + 1
else:
n //= 2
def do_profile(upto=1000000):
prof = profile.Profile()
prof.run('for n in rng(2, {}): test(n)'.format(upto))
prof.print_stats()
def main():
while True:
try:
n = int(inp('Enter a number to test (or x to exit): '))
except ValueError:
break
res = test(n)
if res is None:
print("Well, that's odd...")
else:
print("Chain terminated after {} values were tested".format(res))
if __name__=="__main__":
main()
It took 17.7s on my machine to run do_profile(1000000). It looked at a total of 2,168,611 numbers, the highest of which was 56,991,483,520. No loops were found.
Edit: I have added an inp() shim function; the code should now run in both Python 2 or Python 3.
Edit2: moved the profiling code into the main code listing and added range/xrange to the Python 2/3 shims.
If you want to change a global variable, you need to declare it preceded by global in your function, ie:
value = 0
def changeValue():
global value
value += 1
If you do not need to change the variable, global is not required.

How to stop this loop? And what is the best way to tell user the longest string they have entered?

a = input('number of names: ')
count = 0
while a > 0:
name = raw_input("Please enter filename:")
count =+ 1
if count == a:
break
First and foremost, I'm pretty new to Python. I just started learning Python 10 days ago.
My first question is why doesn't this loop work?
And after performing a loop, I want to tell the user which one is the longest file name and the number of characters it has, but I don't know why.
Thanks everyone :)
You probably intended to write += instead of =+.
count += 1
The statement count =+ 1 is equivalent to count = (+1), i.e. it sets count to 1.
It would also be better to use a more explicit loop:
number_of_names = int(raw_input('Number of names:'))
names = []
for n in range(number_of_names):
name = raw_input('Filename')
names.append(name)
print max(names, key = len)
See it working online: ideone
here is the answer but i think you should spend some time on basics, and 10 days are big enough for this work.
a = input('number of names: ')
count = 0
max = -1
while a > count:
name = raw_input("Please enter filename:")
count += 1
l_max = len(name)
if l_max > max:
max = l_max
if count == a:
print max
break
a = input('number of names: ')
count = 0
largest_str = ""
while count < a:
name = raw_input("Please enter filename:")
count += 1
if len(largest_str) < len(name):
largest_str = name
print largest_str
First of all, your loop is not very good defined. You're now not using the counter to interrupt your loop, the condition
while count < a:
Would make your break-statement obsolete.
Then, be sure to check that a is really of type integer. You may be comparing integers with strings here.
a = input('number of names: ')
longest = ""
for i in xrange(a): #Use for loops where you can, they are more 'pythonic'
name = raw_input("Please enter filename:")
if len(longest) < len(name):
longest = name
print("The longest filename is {} which is {} characters long.".format(longest, len(longest)))

Categories