So I am trying to teach myself python and I am having some problems accomplishing this task. I am trying to read in two integers from the keyboard, but the problem is that they can either be read in on the same line or on two different lines.
Example Inputs:
23 45
or
23
45
Each number should go to its own variable.
Im pretty sure I should make use of the strip/split functions, but what else am I missing? I just really dont know how to go about this... Thanks.
Here is what Im working with, but obviously this version takes the numbers one on each line.
def main():
num1 = int(input())
num2 = int(input())
numSum = num1 + num2
numProduct = num1 * num2
print("sum = ",numSum)
print("product = ",numProduct)
main()
the input terminates on new line (more percisely, the sys.stdin flushes on new line), so you get the entire line. To split it use:
inputs = input("Enter something").split() # read input and split it
print inputs
applying to your code, it would look like this:
# helper function to keep the code DRY
def get_numbers(message):
try:
# this is called list comprehension
return [int(x) for x in input(message).split()]
except:
# input can produce errors such as casting non-ints
print("Error while reading numbers")
return []
def main():
# 1: create the list - wait for at least two numbers
nums = []
while len(nums) < 2:
nums.extend(get_numbers("Enter numbers please: "))
# only keep two first numbers, this is called slicing
nums = nums[:2]
# summarize using the built-in standard 'sum' function
numSum = sum(nums)
numProduct = nums[0] * nums[1]
print("sum = ",numSum)
print("product = ",numProduct)
main()
Notes on what's used here:
You can use list comprehension to construct lists from iterable objects.
You can use sum from the standard library functions to summarize lists.
You can slice lists if you only want a part of the list.
Here I have modified your code.
def main():
num1 = int(input("Enter first number : "))
num2 = int(input("\nEnter second number : "))
if(num1<=0 or num2<=0):
print("Enter valid number")
else:
numSum = num1 + num2
numProduct = num1 * num2
print("sum of the given numbers is = ",numSum)
print("product of the given numbers is = ",numProduct)
main()
If you enter invalid number it prints message Enter valid number.
Related
I want to make a code that allows me to check if the number I have entered is really a number and not a different character. Also, if it is a number, add its string to the list.
Something like this:
numbers = []
num1 = input("Enter the first number: ")
try:
check = int(num1)
numbers.append(num1)
print("The number {} has been added.".format(num1))
except ValueError:
print("Please, enter a number")
I have to do the same for several numbers, but the variables are different, like here:
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Is there any way to create a code that does always the same process, but only changing the variable?
If you are trying to continue adding numbers without copying your code block over and over, try this:
#!/usr/bin/env python3
while len(numbers) < 5: #The five can be changed to any value for however many numbers you want in your list.
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Hopefully this is helpful!
Create the list in a function (returning the list). Call the function with the number of integers required.
def get_ints(n):
result = []
while len(result) < n:
try:
v = int(input('Enter a number: '))
result.append(v)
print(f'Number {v} added')
except ValueError:
print('Integers only please')
return result
Thus, if you want a list of 5 numbers then:
list_of_numbers = get_ints(5)
Recently I created a 24 game solver with python
Read this website if you do not know what the 24 game is:
https://www.pagat.com/adders/24.html
Here is the code:
from itertools import permutations, product, chain, zip_longest
from fractions import Fraction as F
solutions = []
def ask4():
num1 = input("Enter First Number: ")
num2 = input("Enter Second Number: ")
num3 = input("Enter Third Number: ")
num4 = input("Enter Fourth Number: ")
digits = [num1, num2, num3, num4]
return list(digits)
def solve(digits, solutions):
digit_length = len(digits)
expr_length = 2 * digit_length - 1
digit_perm = sorted(set(permutations(digits)))
op_comb = list(product('+-*/', repeat=digit_length-1))
brackets = ([()] + [(x,y)
for x in range(0, expr_length, 2)
for y in range(x+4, expr_length+2, 2)
if (x,y) != (0,expr_length+1)]
+ [(0, 3+1, 4+2, 7+3)])
for d in digit_perm:
for ops in op_comb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insert_point, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insert_point, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [(term if not term.startswith('F(') else term[2])
for term in exp]
ans = ' '.join(exp).rstrip()
print("Solution found:", ans)
solutions.extend(ans)
return ans
print("No solution found for:", ' '.join(digits))
def main():
digits = ask4()
solve(digits, solutions)
print(len(solutions))
print("Bye")
main()
Right now, my code only shows one solution for the numbers given, even when there are clearly more solutions.
So if someone knows how to do this please help me
Thanks
You're not allowing the code to finish it's task before all of the solutions have been calculated and listed. Better to save the solutions in a list/array instead of returning it straight away.
Your function is returning as soon as it finds a solution. Delete the return statement. After the loop, you can return the list of all solutions if desired. To check if there were none, see if the length of the list is zero (so you know when to say there are no solutions).
I would also suggest making solutions local to solve, instead of global.
my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))
Lets suppose I want to first input the total number of integers I am going to enter.
N = 5, I must be able to read exactly 5 integers and store it in a list
for i in range(5):
lst = map(int, raw_input().split())
doesn't do the job
In most primitive way, you can do it in following way.
n = int(raw_input())
numbers = map(int, raw_input().split())[:n]
We can help more if you tell us the context in which you are asking the problem. I doubt if you are using it for some competitive programming problem.
Actually, problem in your code is that you are reading a line and making list from it. But you are doing this FIVE times. Also, you can read lot more than five numbers if they are in single line.
Sa far as I understand, you need the following
lst=[]
for n in range(5):
lst.append(int(raw_input("Input a number: ").split()))
print repr(lst)
inp = raw_input # Python 2.x
# inp = input # Python 3.x
def get_n_ints(prompt, n):
while True: # repeat until we get acceptable input
s = inp(prompt)
try:
vals = [int(i) for i in s.split()]
if len(vals) == n:
return vals
else:
print("Please enter exactly {} values".format(n))
except ValueError:
# a string couldn't be converted to int
print("Values need to be integers!")
How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])