Display number int in Python - python

How to display numbers integer in python ?
For example:
number1 = raw_input('Write one number: ')
number2 = raw_input('Write other number: ')
result = number1 + number2
print "The sum of the numbers is: %d" % result # here, display the result of the operatio n.

You want
result = int(number1) + int(number2)
raw_input returns strings.

raw_input returns strings. If you mean for them to be integers, then use int(x) to convert them to ints.

You have to convert the inputted strings into numbers:
result = int(number1) + int(number2)

Like this;
In [1]: numstr="5"
In [2]: int(numstr)
Out[2]: 5
So in your code result = int(number1) + int(number2)
You'd want to do some input sanitation check though. Users have a bad habit of making mistakes.

Related

entering int or float using input()

I need to enter different values to input(), sometimes integer sometime float. My code is
number1 = input()
number2 = input()
Formula = (number1 + 20) * (10 + number2)
I know that input() returns a string which is why I need to convert the numbers to float or int.
But how can I enter a float or integer without using number1 = int(input()) for example? because my input values are both floats and integers so I need a code that accepts both somehow.
If your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?
You can always just use float:
number1 = float(input())
If you'd like to cast any of your result to integer you always can easily do this
int_res = int(res) # res was float; int_res will be an integer
You could check for the presence of a decimal point in your string to decide if you want to coerce it into a float or an int.
number = input()
if '.' in number:
number = float(number)
else:
number = int(float(number))
number1 = float (input(‘ enter first value ‘) )
number2 = float (input(‘ enter second value ‘) )
Formula = print ( (number1 + 20) * (10 + number2) )

How can I use round() while forcing the digits to be as much as I firstly entered

import random
userask = float(input("enter number: "))
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + str(userask))
Let's say my input is 123.0123
I want the program to force the new value after such operation to have the same number of digits as my initial input, rounding the result.
An example: my input is 102.31, the new value should have two digits and be rounded.
I have read round() docs but could not find something useful for this. how would you do it?
You can try this:
import random
userask = input("enter number: ")
lst = userask.split('.')
digits = 0 if len(lst)==1 else len(lst[1])
userask = float(userask)
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + '{:.{}f}'.format(digits).format(userask))
You can do the following:
import random
import re
inp = input("enter number: ")
if '.' in inp:
num_digits = len(inp.split('.')[1])
else:
num_digits = 0
val = float(inp)
val = val + ((random.randrange(20)*val)/random.randint(3, 100))
if num_digits:
res = round(val, num_digits)
else:
res = int(val)
print("new value is " + str(res))
This code will work also for int's as well for float's, notice that the second if is not mandatory if you don't mind that your output will be printed as float, meaning that for an int it will have a 0 in the decimal place (13 -> 13.0)
Notice
You should always check the input entered to match the desired behaviour of your program, in this case you should probably check that the value entered has the proper "looks" of a number either float or int.
In this case you could do something like:
checker = re.compile('^[0-9]+.?[0-9]*$')
is_valid = bool(checker.match(inp))
and if is_valid isn't True then the value entered is problematic

(Python) Generating Numbers then Printing them on One Line

I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.
This is my code below:
for i in range(10):
number1 = (random.randint(0,20))
number2 = (random.randint(0,20))
print (number1 + number2)
answer = input("Enter your answer: ")
If someone could help me out I would appreciate it, I believe the line
print (number1 + number2)
is the problem, as it is adding them when I just want the random numbers printed in the sum.
Thanks in advance,
Flynn.
Try this,
print number1, '+', number2
Your following line first computes the sum of the two numbers, then prints it
print (number1 + number2)
you have to print a string:
print(str(number1) + " + " + str(number2))
or prefer formating features instead of concatenation:
print("{} + {}".format(number1, number2))
or:
print("%s + %s" % (number1, number2))
Finally, you may want to read some doc:
str.format
string formatting with the % operator
Python tutorial
To convert numbers to a string for concatenation use str().
print str(number1) + ", " + str(number2)
or using natural delimiter
print number1, number2
(The , tells python to output them one after the other with space. str() isn't really necessary in that case.)
This should do the job:
from random import randint
for i in range(10):
num1 = randint(0,20)
num2 = randint(0,20)
answer = input('Sum of %i + %i?: ' % (num1,num2)
Perhaps you know what to do with the rest? (e.g. handling the answer section)

Printing multiple objects without spaces

I'm writing a basic program to convert any 4 digit number in reverse.
I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:
print("This program will display any 4-digit integer in reverse order")
userNum = eval(input("Enter any 4-digit integer: "))
num1 = userNum % 10
userNum2 = userNum // 10
num2 = userNum2 % 10
userNum3 = userNum // 100
num3 = userNum3 % 10
userNum4 = userNum // 1000
num4 = userNum4 % 10
print(num1,num2,num3,num4)
The issue I'm having is the output from the print statement gives me
x x x x
When I would prefer to have
xxxx
Any advice?
If you read the description of the print(), you can see that you can change your last line for:
print(num1,num2,num3,num4, sep='')
Since you just want to convert the input in reverse order. You can take the following approach.
print("This program will display any 4-digit integer in reverse order")
userNum = input("Enter any 4-digit integer: ")
reverse_input = userNum[::-1]
reverse_input = int(reverse_input) # If you want to keep input as an int class
print(reverse_input)
If you want to use your own code then just change the print statement.
print(str(num1) + str(num2) + str(num3) + str(num4))
String concatenation does not add space so you should get desired result.
I used this as a sort of exercise for myself to nail down loops. There are a few loops you can use.
#if using python <3
from __future__ import print_function
x = 3456
z = x
print('While:')
while z > 0:
print(z % 10, end="")
z = z / 10;
print()
print('For:')
for y in xrange(4):
z=x%10
print(z, end="")
x = x / 10
Thanks for asking this question. It encouraged me to go look at python syntax, myself, and I think it's a good exercise.

I don't see how to add two numbers

num1 = bin(input())
num2 = bin(input())
answer = int(num1 ,2) + int(num2,2)
print (bin(answer)) [2:]
input ("press enter to finish")
How do I do it so I can put 2 binary numbers in and add them up, it only lets me put one in and then it just gives me a binary representation of the 1st one.
I really need to know how to do this.
Not quite sure if this is what you are looking for:
#! /usr/bin/python3.2
print (bin(int(input('>> '), 2) + int(input('>> '), 2))[2:])
Example usage:
>> 100
>> 101
1001
This solution assumes you are using Python 2.x. It's not clear if that's the case...
You appear to be using bin() incorrectly. You only need that when converting an integer to a binary string.
You want to use raw_input() instead of input(). The latter will attempt to convert the input to a number automatically, which you don't want.
So:
num1 = int(raw_input(), 2)
num2 = int(raw_input(), 2)
answer = num1 + num2
print bin(answer)[2:]
Guess I would do something like this:
from __future__ import print_function
import sys
if sys.version_info[0]==2: input=raw_input
def get_bin(txt):
while True:
s=input(txt)
try:
return int(s, 2)
except ValueError:
print('"{}" is not a valid binary number'.format(s))
li=[]
for i in range(1,3):
li.append(get_bin('Enter bin number {} >>> '.format(i)))
ans=sum(li)
w=len(bin(ans))
for i, e in enumerate(li):
op='+' if i else ' '
print('{}{:{w}b}'.format(op,e,w=w))
print(' ','='*w)
print(' {:{w}b}'.format(ans,w=w))
On Python 2 or 3, example:
Enter bin number 1 >>> 111111
Enter bin number 2 >>> 11
111111
+ 11
=========
1000010

Categories

Resources