I want the user to input a number
Give a number : he types "10" -but...
Give a number : he types "I want to type 10"
i want the program to just "count" the integer. Because if he types a string the program will stop
import random
goal = random.randrange(1,10)
n = 1
tries = 0
name = input("Dose to onoma sou ")
print("A game in Python")
while n != 0 :
value = int(input("madepse poio einai to noumero:"))
n = abs(value - goal)
print(value,n)
tries = tries + 1
if n >= 4 :
print("den eisai koda")
elif n > 0 and n <= 3 :
print("eisai koda")
else :
print("to vrikes")
print ("to score sou einai: ",tries)
skoros = str(tries)
score = open('score.txt', 'a')
score.write(name)
score.write(' ')
score.write(skoros)
score.write("\n")
score.close
This will take any input and pull the first number out of it. \d matches any digit 0-9, and + means "one or more".
import re
while True:
user = input('Enter a number: ')
match = re.search(r'\d+',user)
if match:
value = int(match.group(0))
break
else:
print("I didn't see a number in that response.")
print(value)
Well, you could just manually loop through the string and store the position of the number using isdigit().
The following approach expects the number to be the only one in the string (multi digit allowed):
start = None
stop = None
for i in range(len(input)):
c = input[i]
if c.isdigit():
if start == None:
start = i
stop = i
try:
number = int(input[start:stop])
catch:
print("invalid input")
EDIT:
I guess there would be some nice and easy Regex solution, but I'll leave my hands off of it, as I am not too experienced with it...
Related
(I am new to Python so forgive me in advance) I have to write a program that calculates the total of integers from 1 to the user input. So if I input 4, it would add 1+2+3+4. I also added an argument that makes a number that is less than 1 print "invalid number". I am stuck on adding a sentinel that is a letter. Thank you
value = input("Enter a number or press J to terminate: ")
if value < 1:
print("Invalid number")
else:
i = 1
while value > 1:
i = i + value
value = value - 1
print(i)
This is the code that I tried to do:
value = input("Enter a number or J to finish: ")
if value < 1:
print("Invalid number")
while value ! = "J":
i = float(value)
else:
i = 1
while value > 1:
i = i + value
value = value - 1
print(i)
value = input("Enter a number or J to finish: ")
Error when J or any number is inputted, '<' not supported between instances of 'str' and 'int'.
the function input() always stores the input as string data-type
so if you give input as 4 means it will consider the 4 as a string not integer
now with this in mind now try:
value = input("Enter a number or J to finish: ")
if value > 1:
print("BOTH DATA TYPES ARE SAME ")
value = 4
now we are comparing 4 => "string" with 1 => "int", it's not possible to compare "integer" with "string" so the error occurs.
if you want to get input as int then use the following int(input(""))
I hope it'll be helpful, thank you
Beginning of an answer.
value = input("Enter a number or J to finish: ")
while value ! = "J":
i = float(value)
# a placeholder for future code
print(value)
# There is a lot of possible code to achieve the goal.
I have a small problem here, i´m developing a program for children with special care so can they learn the ABC and a basic math with first contact with a PC, this one requests the user to input a string in a loop and counts the times that we insert a word, in my case i provide the letter "a". and sums every letter in the final
So the problem is that my code isn't breaking the loop if we input the "." it doesn't stop and not counting correctly, does it misses a sum ? i cant figure it out what is wrong and not understand why it´s not stopping
thank you for all the help
while True:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
break
print("the count is" +str(count))
when the program is running i input the examples under
> Insert the text :> banana
1 1 1
Insert the text :> after
1
Insert the text :> .
the count is 0
the expected is to sum all the letters at the end, and gives to me when i put a word e returns the number of A´
for example
input banana 3
input after 1
the count is 4
Like Oliver said, you need to put everything in the while loop. However, you also need to break out of the while loop. I would do it with a variable like so.
running = True
while running:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
running = False
print("the count is" + str(count))
The following code should work:
searchLetter = "a"
stopLetter = "."
totalCount = 0
while True:
string = input("Insert the text :> ")
subCount = string.count(searchLetter)
totalCount += subCount
if string.count(stopLetter) != 0:
break
print(subCount)
print("The count is " + str(totalCount))
We're using built-in str.count() function to see how many times a letter appears in a given word or line.
If the stopLetter (in this case .) appears, we instantly break out of the while loop. Otherwise, we keep accepting input.
You need to put all of your code inside the while loop:
while True:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
break
print("the count is" +str(count))
If you are considering counting every alphabet and asking the user to input a letter to find out how many times it appears, you can use a built-in function called Counter from the collections library.
from collections import Counter
while True:
string = input("Insert the text :> " )
if string == ".":
break
dictionary = Counter(string.lower())
answer = input("Press 'y' to start counting!")
while answer.lower() == 'y':
letter = input("What letter do you want to check? ")
print("the count is" , dictionary[letter])
answer = input("Do you wish to continue to check the letter? [y/n]")
The range of answers is all struggling with exit-condition and char-counting, including UI-improvements and case-sensitivity.
Divide and Conquer
I thought it would help to split you project into small isolated and testable functions. This way you can:
find bugs easier next time
easily extend for new features
Solution
def count_char(s, char, stop_char):
count = 0
for letter in s:
if letter == stop_char:
return None
elif letter == char:
count = count + 1
return count
def ask_and_count(letter, stop_char):
s = input("Counting '{letter}'s for your input (enter {stop_char} to quit):")
counted = count_char(s, letter, stop_char)
if counted is None:
return None
print(f"Counted {counted} 'a's.")
return counted
letter = 'a'
stop_char = '.'
runs = 0
while runs >= 0:
# debug-print: print(f"Run #: {runs}")
count = ask_and_count(letter, stop_char)
if count is None:
break # alternatively set runs = -1
{total}")
total += counted
# debug-print: print(f"Run #: {runs} + Counted: {count} = Total:
# Loop exited because user entered stop_char
print(f"Runs: {runs}, Total sum of '{letter}'s counted: {total}.")
This was the console dump for a test-run:
Counting 'a's for your input (enter . to quit): a
Counted 1.
Counting 'a's for your input (enter . to quit): aa
Counted 2.
Counting 'a's for your input (enter . to quit): bcdaaa
Counted 3.
Counting 'a's for your input (enter . to quit): a.a
Counted 2 when finding stop-char. Will quit without adding and display previous total.
Runs: 4. Total sum of 'a's counted: 6.
Useful patterns
defined a lot of functions (learn about def keyword arguments and return)
the exit-condition has now 2 alternatives: break # alternatively set runs = -1
plenty of informal printing done using f-strings (very useful, since Python 3.6)
added features: parameterised chars, run counter, improved UI
How can we check if a user enters the value 0 multiple times in a row?
I have tried below code- here I have tried to define multiple value in list, but if the user enters 000000000 or more, I have to define till 000000000 in list is there any other way to achieve this
list = [0,00,000,0000]
num = int(input("Enter a number: "))
if num in list:
print("Zero")
elif :
print(" None ")
You need to take the input as a string. And you can check if the user has entered a string that will have all zeros in it as follows
def all_zeros(string):
return all(ch == '0' for ch in string)
This worked for me
num = input("Enter: ")
if num.count('0') > 0 and num.startswith('0'):
print("0")
else:
print("none")
Since you asked in this way
How can we check if a user enters the value 0 multiple times in a row?
But, other answers were checking whether more than one 0's are present in the string or not. I assume you want to check continuous zero's only,
num = input("Enter Number: ") # returns string
if "00" in num: #checking substring
print("Found continuous zeros")
else:
print("Entered no continous zeros!")
value = int(num) # convert it to int if needed
It doesn't matter how many zeros in the string, all these [00,000,0000,00000...] belong to the same category.
Output:
>>> num = input("Enter Number: ")
Enter Number: 0008
>>> num
'0008'
>>> "00" in num
True
>>>
num = input("Enter: ")
if num.count("0") > 1 and int(num) == 0:
print("0")
else:
print("none")
don't change num to int it will remove all the trailing zeroes
I am learning Python, and currently I am learning about sentinel loops. I have this piece of code that I need help understanding. What exactly is the while-loop doing? I did some research and I know it is looping through the if-statement (correct me if I am wrong); but is it looping through a specific equation until the user stops inputting their integers? Thank you in advanced.
(Please no hate comments I am still learning as a developer. & this is my first post Thanks)
even = 0 odd = 0
string_value = input("Please enter an int. value: ")
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
if even + odd == 0:
print("No values were found. Try again...") else:
print("Number of evens is: ", str(even)+".")
print("Number of odd is: ", str(odd)+".")
---Updated Code:
def main():
print("Process a series of ints enter at console \n")
count_even = 0
count_odd = 0
num_str = input("Please enter an int. value or press <Enter> to stop: ")
#Process with loop
while num_str !="":
num_int = int(num_str)
if num_int % 2 == 0:
count_even += 1
else:
count_odd += 1
num_str = input("Please enter an int. value: ")
if count_even + count_odd == 0:
print("No values were found. Try again...")
else:
print("Number of evens is: ", str(count_even)+".")
print("Number of odd is: ", str(count_odd)+".")
main()
First thing the while loop does is check if the user input is emptywhile string_value !="", if it is not empty than it will start the loop. The != means not equals and the "" is empty so not equals empty. Next it sets the variable int_value as the integer of the user input(will error if user inputs anything other than whole number). Next it checks if the variable int_value % 2(remainder of division by 2) is 0, so pretty much it checks if the number is divisible by 2, if it is divisible by two it will add 1 to the even variable. Otherwise it will add 1 to the odd variable
It will be very helpful if you go through python doc https://docs.python.org/3/tutorial/index.html
even = 0 odd = 0
The above line even and odd are variables keeping count of even number and odd number.
string_value = input("Please enter an int. value: ")
The above line prompt the user to input an integer
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
The above while loop check firstly, if the input is not empty, int() Return an integer object constructed from a number or string x, or return 0 if no arguments are given https://docs.python.org/3/library/functions.html#int. The if statement takes the modulus of the integer value, and then increases the counter for either odd or even.
Finally, the count of odd and even are printed.
the input() function waits until the user enters a string so unless the user enters an empty string the while loop will keep asking the user for strings in this line:
string_value = input("Please enter an int. value: ")
and check if its an empty string in this line:
while string_value !="":
I'm trying to write a 'while' loop that takes a users input, if it is a number it remembers it, if it is a blank space it breaks. At the end it should print the average of all entered numbers. This is giving me the error 'could not convert string to float: '. What exactly is wrong here? Thanks!
EDIT: I re-wrote it like this and I get the same error about converting, but it seems to be on the final (count += 1) line?
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
print (number / count)
number = number + float(user_number)
count += 1
My guess is that you directly hit enter when you don't want to pass numbers anymore. In that case, comparing with a space is incorrect.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == '':
break
number += float(user_number)
count += 1
print (number / count)
Also a statement after a break is unreachable.
If you want a cleaner alternative, I would recommend appending to a list, and then computing the average. This removes the need for a separate counter. Try this:
numbers = []
while True:
user_number = input('Enter a number: ')
if user_number == '':
break
numbers.append(float(user_number))
print (sum(numbers) / len(numbers))
Additionally, you could remove the need for a break by testing in the head of while, but you'll need to take an additional input outside the loop.
You should change the order, right now you try to convert everything into floats, even blank spaces.
while True:
user_number = input('Enter a number: ')
if not user_number.isdigit():
print (number / count)
break
count += 1
number = number + float(user_number)
Additionally, you should do the print of the average value before the break.
I changed your if condition to break if any input except a number is entered, it should be a bit more general than before.
Change order and it should solve the problem, you should first check is enterned input is string or not then go to number part
#!/usr/bin/python
number = 0.0
count = 0
while True:
user_number = raw_input('Enter a number: ')
if user_number == (' '):
print (number / count)
break
number = number + float(user_number)
count += 1
This should work for you.
lst= []
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
lst.append(int(user_number))
print(int(user_number))
print("Average : " + str(sum(lst)/len(lst)))
This code works correctly.
I think you are giving Other than space as input to break.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
print (number / count)
number = number + float(user_number)
count += 1
or else use below code:
--> Break will be triggered for non-digit input.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if not user_number.isdigit():
break
number = number + float(user_number)
count += 1
print("user_number", number)
print("Count", count)
print (number / count)