Numbers Only, Rounding up, and adding - python-3.x

so I am still learning Python so this should be rather easy to answer for some of you experts...
1) How can you make it so only numbers are accepted as an input?
def check_only_digit():
digits = input("Please input a number ")
if digits in "0123456789":
print("Working")
else:
print("Not working")
check_only_digit()
This will print "Working" if the inputted is a number in 0123456789 but only is this order. What I am asking is there any way to make it in any order?
2) How can I make the users digit round UP to the nearest 10?
def round_up():
users_number = input("Please input a number you want rounded ")
answer = round(int(users_number), -1)
print (answer)
round_up()
3) Is there anyway to add a number onto the end of another number? For example for 1+1, instead of equaling 2, can it equal 11?
I would like to thank you all for your responses in advance.

For Answer 1:
def check_Numbers():
number=input("Enter a number: ")
try:
number=int(number)
print("Working")
except(ValueError):
print("Not Working")
For Answer 2:
def rounding_Off():
userNumber=float(input("Enter a floating point number to round off: "))
roundedOff=round(userNumber,-1)
return roundedOff
For Answer 3:
def addNumbers():
number1=input("Enter one number: ")
number2=input("Enter another one: ")
newNumber=number1+number2
return int(newNumber)
#return newNumber <----- This if you want to get your number in string format.

Related

User validation loop for binary input is not recognising input

new to programming, but I'm working on a binary to decimal converter and I'm trying to make sure that the only input is either a '0' or '1' and not alpha, and not empty ''.
I have figured out logic for not empty and not alpha input , but I can't figure out the logic for the last condition - if 1 not in string or 0 not in string. It works if I enter either 1 or zero, but this isn't what i'm looking. I just want to check that there is only 1's or 0's and then proceed with the rest of the program.
I've spent hours on just this today so any help is appreciated. :)
Thanks in advance :)
def convert_to_decimal(binary_number):
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary numbera: ')
while binary.isalpha() or binary == '':
print("Please make sure your number contains digits 0-1 only.a ")
binary = input('Please enter numberb: ')
while binary not in '1' and binary not in '0':
print("Please make sure your number contains digits 0-1 only.x ")
binary = input('Please enter numberc: ')
Here I reworked it a little and its a bit inefficient, but here it is. It is a bit self-explanatory, but basically how it works, is it iterates over the inputString, and checks if each number is a 1 or 0 if not, the continue to ask, otherwise continue.
def isBinary(stringNum):
if len(stringNum) ==0:
return False
for chr in stringNum:
if chr != "0" and chr != "1":
return False
return True
def convert_to_decimal():
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary number: ')
while not isBinary(binary):
binary = input('Please enter binary number: ')
The reason yours doesn't work is you say if not in 1 and not in 0, which is wrong. in in this case returns True if the WHOLE string is in the target("0"). Since "10" isn't completely in 1 or in 0, it will ask you again, so you can see why that wouldn't work.
I hate myself for finding the answer, but it works :)
def convert_to_decimal(binary_number):
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary numbera: ')
while binary.isalpha() or binary == '':
print("Please make sure your number contains digits 0-1 only.a ")
binary = input('Please enter numberb: ')
while not binary.startswith('0') and not binary.startswith('1'):
print("Please make sure your number contains digits 0-1 only.x ")
binary = input('Please enter numberc: ')

finding largest and smallest number in python

I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

compare user's input in a python list

The question is related to Python
I have this list:
a=[1,1,2,3,5,8,13,21,34,55,89]
# I ask the user to enter a number
user_number = input("Enter a number")
What I need is to display the numbers of the list that are smaller than than user_input
Any hint please?
You can for loop through the list.
for numbers in a:
if number < int(user_input)
print(number)

Count iterations in a loop

New to programming. How to count and print iterations(attempts) I had on guessing the random number?` Let's say, I guessed the number from 3-rd attempt.
import random
from time import sleep
str = ("Guess the number between 1 to 100")
print(str.center(80))
sleep(2)
number = random.randint(0, 100)
user_input = []
while user_input != number:
while True:
try:
user_input = int(input("\nEnter a number: "))
if user_input > 100:
print("You exceeded the input parameter, but anyways,")
elif user_input < 0:
print("You exceeded the input parameter, but anyways,")
break
except ValueError:
print("Not valid")
if number > user_input:
print("The number is greater that that you entered ")
elif number < user_input:
print("The number is smaller than that you entered ")
else:
print("Congratulation. You made it!")
There are two questions being asked. First, how do you count the number of iterations? A simple way to do that is by creating a counter variable that increments (increases by 1) every time the while loop runs. Second, how do you print that number? Python has a number of ways to construct strings. One easy way is to simply add two strings together (i.e. concatenate them).
Here's an example:
counter = 0
while your_condition_here:
counter += 1 # Same as counter = counter + 1
### Your code here ###
print('Number of iterations: ' + str(counter))
The value printed will be the number of times the while loop ran. However, you will have to explicitly convert anything that isn't already a string into a string for the concatenation to work.
You can also use formatted strings to construct your print message, which frees you from having to do the conversion to string explicitly, and may help with readability as well. Here is an example:
print('The while loop ran {} times'.format(counter))
Calling the format function on a string allows you replace each instance of {} within the string with an argument.
Edit: Changed to reassignment operator

python code - Wants code to accept certain numbers

coins = input("enter x number of numbers separrated by comma's")
while True:
if coins == 10, 20, 50, 100,:
answer = sum(map(int,coins))
print (answer)
break
else:
print ('coins not accepted try again')
Want the program to only accept numbers 10 20 50 and 100 (if numbers valid must add them together otherwise reject numbers) this code rejects all numbers
coins = input("enter x number of numbers separated by commas")
whitelist = set('10 20 50 100'.split())
while True:
if all(coin in whitelist for coin in coins.split(',')):
answer = sum(map(int,coins))
print (answer)
break
else:
print ('coins not accepted try again')
From the in-comment conversation with #adsmith, it seems that OP wants a filter. To that end, this might work better:
coins = input("enter x number of numbers separated by commas")
whitelist = set('10 20 50 100'.split())
answer = sum(int(coin) for coin in coins.split(',') if coin in whitelist)
print answer
You can try sanitizing your input as it's entered instead of cycling through afterwards. Maybe this:
coins = list()
whitelist = {"10","20","50","100"}
print("Enter any number of coins (10,20,50,100), or anything else to exit")
while True:
in_ = input(">> ")
if in_ in whitelist: coins.append(int(in_))
else: break
# coins is now a list of all valid input, terminated with the first invalid input
answer = sum(coins)

Resources