While loop python resulting in infinite loop - python

def generate_n_chars(n,s="."):
res=""
count=0
while count < n:
count=count+1
res=res+s
return res
print generate_n_chars(raw_input("Enter the integer value : "),raw_input("Enter the character : "))
I am beginner in python and I don't know why this loop going to infinity. Please someone correct my program

The reason is because the input will be evaluated and set to a string. Therefore, you're comparing two variables of different types. You need to cast your input to an integer.
def generate_n_chars(n,s="."):
res=""
count=0
while count < n:
count=count+1
res=res+s
generate_n_chars(int(raw_input("Enter the integer value : ")),raw_input("Enter the character : "))

def generate_n_chars(n, s = "."):
res = ""
count = 0
while count < n:
count = count + 1
res = res + s
return res
print generate_n_chars(input("Enter the integer value : "), raw_input("Enter the character : "))
Here input("Enter the integer value : ") input instead of raw_input
raw_input() => https://docs.python.org/2/library/functions.html#raw_input
input() => https://docs.python.org/2/library/functions.html#input

Related

Count number of digits using for loop in Python

I want to count number of digits of any digits number without converting the number to string and also using for loop. Can someone suggest how to do this.
num = int(input("Enter any number : "))
temp = num
count = 0
for i in str(temp):
temp = temp // 10
count += 1
print(count)
If you stick to using input, you can't get away the fact that this function prompts a String. As for the for loop, simply count the number of characters in the input string:
num = input("Enter any number : ")
print(len(num))
You don't have to create a temp variable as num already contains the input.
If there should only digits being entered, you can first check that with a pattern, then get the length of the string without using any loop.
import re
inp = input("Enter any number : ")
m = re.match(r"\d+$", inp)
if m:
print(len(m.group()))
else:
print("There we not only digits in the input.")
i = int(input('num : '))
j=0
while i:
j+=1
i//=10
print(j)
Repeats dividing the entered number stored in i by 10 and adds 1 to j (result) Checks From i if it finds it equal to 0 it exits the iteration and prints the result j
i = 103
j = 0
#inside repetition :
i//=10 #i=10
j+=1 #j=1
i!=0 #completion
i//=10 #i=1
j+=1 #j=2
i!=0 #completion
i//=10 #i=0
j+=1 #j=3
i==0 #break
print j #result

Loop and check if integer

I have an exercise:
Write code that asks the user for integers, stops loop when 0 is given.
Lastly, adds all the numbers given and prints them.
So far I manage this:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b + a
print("The total sum of the numbers are {}".format(b))
However, the code needs to check the input and give a message incase it is not an integer.
Found that out while searching online but for the life of me I cannot combine the two tasks.
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum + num
print(total_sum)
break
I suspect you need an if somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b + a
print("The total sum of the numbers are {}".format(b))
If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum + num
if num == 0:
print(total_sum)
break
Since input's return is a string one can use isnumeric no see if the given value is a number or not.
If so, one can convert the string to float and check if the given float is integer using, is_integer.
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b += a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))

PYTHON Problem: Why is my code showing "NONE" when line no. 9 is executed? can anyone assist me?

print("\tWELCOME TO DRY_RUN CLASS ASSAIGNTMENT!\t")
userList = []
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input(print("Enter number",number )))
number = number + 1
userList.append(variable)
else:
print("Number should not be less than or equal to '0'!")
def maxAll():
maxofall = 0
for element in userList:
if element > maxofall:
maxofall = element
print("The maximum number is:", element)
while True:
mainSystem()
askUser = int(input("What do you want to do with the numbers?\n1.Max All\n2.Average\n3.Quit\nYour answer: "))
if askUser == 1:
maxAll()
this is the code i am using right now...
what do i need to fix i am getting an error like this wheni am executing line no. 9
:-
Enter Number whatever the number is
Noneinput starts here
???
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input("Enter number {} : ".format(number) ))
number = number + 1
userList.append(variable)
else:
print("Number should not be less than or equal to '0'!")
Change your function to this.
print() is a function. Which returns nothing (None) in your case.
input() function thinks this None object is worth displaying on console.
Hence None appears on screen before taking any input.
There are a couple of problems:
1)You have a misplaced print() inside input() in your mainSystem() function
2)You probably want to use f-strings to print the right number instead of the string literal 'number'
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input(f"Enter number {number} : "))
number = number + 1
userList.append(variable)

AttributeError: 'str' object has no attribute 'list'

We have to find out the average of a list of numbers entered through keyboard
n=0
a=''
while n>=0:
a=input("Enter number: ")
n+=1
if int(a)==0:
break
print(sum(int(a.list()))/int(n))
You are not saving the numbers entered. Try :
n = []
while True:
a=input("Enter number: ")
try: #Checks if entered data is an int
a = int(a)
except:
print('Entered data not an int')
continue
if a == 0:
break
n.append(a)
print(sum(n)/len(n))
Where the list n saves the entered digits as a number
You need to have an actual list where you append the entered values:
lst = []
while True:
a = int(input("Enter number: "))
if a == 0:
break
else:
lst.append(a)
print(sum(lst) / len(lst))
This approach still has not (yet) any error management (a user enters float numbers or any nonsense or zero at the first run, etc.). You'd need to implement this as well.
a needs to be list of objects to use sum, in your case its not. That is why a.list doens't work. In your case you need to take inputs as int (Can be done like: a = int(input("Enter a number")); ) and then take the integer user inputs and append to a list (lets say its name is "ListName")(listName.append(a)), Then you can do this to calculate the average:
average = sum(listName) / len(listName);
def calc_avg():
count = 0
sum = 0
while True:
try:
new = int(input("Enter a number: "))
if new < 0:
print(f'average: {sum/count}')
return
sum += new
count += 1
print(f'sum: {sum}, numbers given: {count}')
except ValueError:
print("That was not a number")
calc_avg()
You can loop, listen to input and update both s (sum) and c (count) variables:
s, c = 0, 0
while c >= 0:
a = int(input("Enter number: "))
if a == 0:
break
else:
s += a
c += 1
avg = s/c
print(avg)

can a condition be in range in python?

can a range have a condition in python? for example, I wanna start at position 0 but I want it to run until my while statement is fulfilled.
total = 0
num = int(input ( "Enter a number: " ))
range[0,while num != 0:]
total += num
I want to be able to save different variables being in a while loop.
The purpose of my program is to print the sum of the numbers you enter unil you put in 0
my code
num = int(input ( "Enter a number: " )) #user input
number_enterd = str() #holds numbers enterd
total = 0 #sum of number
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
number_enterd = num
print( "Total is =", total )
print(number_enterd) #check to see the numbers ive collected
expected output:
enter an integer number (0 to end): 10
1+2+3+4+5+6+7+8+9+10 = 55
as of right now I'm trying to figure out how to store different variables so i can print them before the total is displayed. but since it is in a loop, the variable just keeps getting overwritten until the end.
If you want to store all the numbers you get as input, the simplest way to do that in Python is to just use a list. Here's that concept given your code, with slight modification:
num = int(input ( "Enter a number: " )) #user input
numbers_entered = [] #holds numbers entered
total = 0 #sum of number
while num != 0:
total += num
numbers_entered.append(num)
num = int(input ( "Enter a number: " ))
print("Total is = " + str(total))
print(numbers_entered) #check to see the numbers ive collected
To get any desired formatting of those numbers, just modify that last print statement with a string concatenation similar to the one on the line above it.
I used a boolean to exit out of the loop
def add_now():
a = 0
exit_now = False
while exit_now is False:
user_input = int(input('Enter a number: '))
print("{} + {} = {} ".format(user_input, a, user_input + a))
a += user_input
if user_input == 0:
exit_now = True
print(a)
add_now()
If you want to store all of the values entered and then print them, you may use a list. You code would end like this:
#number_enterd = str() # This is totally unnecessary. This does nothing
num = int(input ( "Enter a number: " ))
total = 0 #sum of number
numsEntered = [] # An empty list to hold the values we will enter
numsEntered.append(num) # Add the first number entered to the list
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
#number_enterd = num # Unnecesary as well, this overwrites what you wrote in line 2
# It doesn't even make the num a string
numsEntered.append(num) #This adds the new num the user just entered into the list
print("Total is =", total )
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
For example, user enters 5,2,1,4,5,7,8,0 as inputs from the num input request.
Your output will be:
>>>Total is = 32
>>>Numbers entered: [5, 2, 1, 4, 5, 7, 8, 0]
Just as a guide, this is how I would do it. Hope it helps:
num = int(raw_input("Enter a number: "))
numsEntered = [] # An empty list to hold the values we will enter
total = 0 #sum of numbers
while True:
numsEntered.append(num) #This adds the num the user just entered into the list
total += num
num = int(raw_input("Enter a number: "))
print("Total is =", total)
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
In this case, the last 0 entered to get out of the loop doesn't show up. At least, I wouldn't want it to show up since it doesn't add anything to the sum.
Hope you like my answer! Have a good day :)

Categories