How I can get number from user that includes only 5,6? - python

How I can get number from user that only includes 5 and 6?
I try for loop but it's not work,also try convert the input to string,also no work.how to do?
Number = int(input('enter num')
for x in number:
if 4<x<7:
print('ok)
else:
print ('no')

In python 3, input returns a string. You can easily filter the numbers you want with
val = int(''.join(c for c in input('enter num: ') if c in '56'))

Not sure, why do you need a loop there and why you use x. Try this:
number = int(input('enter num')
if number in [5, 6]:
print('ok)
else:
print ('no')

While I'm sure the others might work, this is yet another way to check for a specific number.
#Gets the number from the user
Number = int(input("Enter Num"))
#checks to see if the number is either 5 or 6
if (Number == 5 or Number == 6):
print("ok") #if it is, it prints ok
else:
print("No") #if it isn't, it prints no

It is probably easier if you check for digits 5 and 6 before converting to int.
Number_str = input('enter num')
for x in Number_str:
if not ord('4')<ord(x)<ord('7'):
print ('no')
break
else:
Number = int(Number_str)
print('ok')

Related

Keep asking for numbers and find the average when user enters -1

number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)

How to make it so if any variable in a list is greater than an integer, it will print out something, else it will print out something else?

one = int(input("Type a number"))
two = int(input("Type a second number"))
three = int(input("Type a third number"))
four = int(input("Type fourth number"))
num = [one,two,three,four]
How do I make it so if any variable in num is greater than or equal to 7, it will print ("yes") and else, it will print ("no")? Also I'm not sure if I made a list correctly.
If you use the max() function, you don't need to use any for loops.
num = [1, 9, 2, 6, 10]
if max(num) >= 7:
print("Yes")
else:
print("No")
Good news - that list looks correct!
What you're looking for is two things - a for loop and a conditional.
The for loop will look over each item in the list, and the conditional will check to see if the current number is greater than or equal to 7. If so, it can update some value (here, a boolean that evaluates whether a number was greater than 7) that is checked again later. Here is my solution to your problem!
# Assume all of the stuff from your question goes here.
isGreaterThan = False
for number in num:
if number >= 7:
isGreaterThan = True
break
if isGreaterThan:
print("Yes!")
else:
print("No.")
If you don't get what any part of this does, please ask!
You can use a for loop to go through each item in the list to check whether an item is greater or equal to 7. Then use Booleans to print out the proper output
isGreaterThan = False
for i in num:
if i >= 7:
isGreaterThan = True
break
if isGreaterThan:
print("Yes")
else:
print("No")
for n in num: # loop through all the elements in the list
if(n > 7): # each element is in the "n" variable - cehck if n>7
print("yes") # if yes, then pront it
break # break the loop and stop looking
Here's the shorthand way:
num = [1, 9, 2]
print("Yes" if any(n >= 7 for n in num) else "No")
Alternatively, using the builtin max as suggested by another answer:
print("Yes" if max(num) >= 7 else "No")
For a quick test, I'd encourage you to lower the 2nd element in the list, and check how the output changes.
one = int(input("Type a number"))
two = int(input("Type a second number"))
three = int(input("Type a third number"))
four = int(input("Type fourth number"))
num = [one,two,three,four]
x= 7
for i in num:
if i>x:
print(f"your {i}th number is grater than {i} ")
else:
pass
x = x +1

Python one line for loop input

I don't know how to get input depending on user choice. I.e. 'How many numbers you want to enter?' if answers 5, then my array has 5 spaces for 5 integers in one line separated by space.
num = []
x = int(input())
for i in range(1, x+1):
num.append(input())
Upper code works, however inputs are split by enter (next line). I.e.:
2
145
1278
I want to get:
2
145 1278
I would be grateful for some help.
EDIT:
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
This seems to work. But why I'm getting "Memory limit exceeded" error?
EDIT:
Whichever method I use, I get the same problem.
x = int(input())
y = input()
numbers_list = y.split(" ")[:x]
array = list(map(int, numbers_list))
print(max(array)-min(array)-x+1)
or
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
array = list(map(int, num))
print(max(array)-min(array)-x+1)
or
z = int(input())
array = list(map(int, input().split()))
print(max(array)-min(array)-z+1)
Assuming you want to input the numbers in one line, here is a possible solution. The user has to split the numbers just like you did in your example. If the input format is wrong (e.g. "21 asd 1234") or the number does not match the given length, the user has to enter the values again, until a valid input is made.
x = int(input("How many numbers you want to enter?"))
while True:
attempt = input("Input the numbers seperated with one space")
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)==x:
print(num)
break
else:
print("You have to enter exactly %s numbers! Try again"%x)
except:
print("The given input does not match the format! Try again")
The easiest way to do this would be something like this:
input_list = []
x = int(input("How many numbers do you want to store? "))
for inputs in range(x):
input_number = inputs + 1
input_list.append(int(input(f"Please enter number {input_number}: ")))
print(f"Your numbers are {input_list}")
Is there a reason you want the input to be on one line only? Because you can only limit how many numbers you store (or print) that way, not how many the user inputs. The user can just keep typing.
You can use this without needing x:
num = [int(x) for x in input().split()]
If you want the numbers to be entered on one line, with just spaces, you can do the following:
x = int(input("How many numbers do you want to store? "))
y = input(f"Please enter numbers seperated by a space: ")
numbers_list = y.split(" ")[:x]
print(f"We have a list of {len(numbers_list)} numbers: {numbers_list}")
Even if someone enters more than the amount of promised numbers, it returns the promised amount.
Output:
How many numbers do you want to store? 4
Please enter numbers seperated by a space: 1 4 6 7
We have a list of 4 numbers: ['1', '4', '6', '7']
Try this.
x = int(input())
num = [] # List declared here
while True:
try:
# attempt moved inside while
# in case input is in next line, the next line
# will be read in next iteration of loop.
attempt = input()
# get values in current line
temp = [int(val) for val in attempt.split(" ")]
num = num + temp
if len(num) == x:
break
except:
print('Error2')
Maybe the bot was passing integers with newline instead of spaces, in which case the while loop will never terminate (assuming your bot continuously sends data) because every time, it will just re-write num.
Note - this code will work for both space as well as newline separated inputs

Stuck with this

I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it
print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")
number = input("Input a number")
sum1 = 0
while number >= 1:
sum1 = sum1 + number
if number <= 0:
print (sum1)
Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.
# -*-coding:Utf-8 -*
print ("Keep inputting numbers different than 0 and each one will be added together consecutively.")
print ("Enter a and the total will be displayed on the screen. Have fun.")
sum = 0
x = ""
while type(x) == str:
try:
x = int(input("Value : "))
if x == 0:
break
sum += x
x = ""
except:
x = ""
print ("Please enter a number !")
print ("Result : ", sum)
If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.
Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.

Checking user input to see if it satisfies two conditions

As part of a larger menu-driven program, I'd like to test user input to see if that input:
is an integer AND
if it is an integer, if it is within the range 1 to 12, inclusive.
number = 0
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invlaid input, please try again >>> ")
continue
else:
if not (1<= number <=12):
print("Need a whole number in range 1-12 >>> ")
continue
else:
print("You selected:",number)
break
I'm using Python 3.4.3, and wanted to know if there's a more succinct (fewer lines, better performance, more "Pythonic", e.g.) way to achieve this? Thanks in advance.
You don't need anything bar one if in the try:
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
if 1 <= number <= 12:
print("You selected:", number)
break
print("Need a whole number in range 1-12 >>> ")
except ValueError:
print("Invlaid input, please try again >>> ")
Bad input will mean you go straight to the except, if the input is good and is in your accepted range, the print("You selected:", number) and will be executed then we break or else print("Need a whole number in range 1-12 >>> ") will be executed if is outside the range.
Your code looks pretty good to me. Minor fix-ups (spelling, indentation, unnecessary continues):
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invalid input, please try again >>> ")
else:
if 1 <= number <= 12:
print("You selected: {}".format(number))
break
else:
print("Need a whole number in range 1-12 >>> ")
Use isdigit() to check for non-digit characters. Then you shouldn't need to catch the exception. There's only one if and it uses operator short-circuiting to avoid doing int(blah) if blah contains non-digits.
while True:
num_str = raw_input("Enter a whole number between 1 and 12 >>> ")
if num_str.isdigit() and int(num_str) in range(1,13):
print("You selected:",int(num_str))
break
else:
print("Need a whole number in range 1-12 >>> ")
I don't think you need a whole try/except block. Everything can be fit into a single condition:
number = raw_input("Enter a whole number between 1 and 12 >>> ")
while not (number.isdigit() and type(eval(number)) == int and 1<= eval(number) <=12):
number = raw_input("Enter a whole number between 1 and 12 >>> ")
print("You selected:",number)

Categories