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.
Related
This question already has answers here:
How to print something a specific number of times based on user input?
(3 answers)
Closed 1 year ago.
The code is supposed to print :) based on the number inputted (an integer 1 to 10). With any positive integer, the code is supposed to print that many smiley faces (ex. if 5 is entered, 5 smiley faces should be printed).
It's required that the code should use += to add onto the end of a string and should also decrement to count down and use a loop.
x = input("enter number 1 to 10: ")
for i in len(x):
print(":) " * x)
I don't think you can multiply int values and str values, and I can't find another way to do this.
First things first, input() function returns a string. You want x to be an integer, use the int() function:
x = int(input("enter number 1 to 10: "))
Second You can either use a for loop or the multiplication operator to print n number of smileys.
# Using for loop to print n smileys :
x = int(input("enter number 1 to 10: "))
for i in range(x):
print(":) ",end="")
# Using multiplication operator :
x = int(input("enter number 1 to 10: "))
print(":) "*x)
# x should be an integer
x = int(input("enter number 1 to 10: "))
# define "s" as an empty string
s = ''
# increment ":)" to "s" x times
for _ in range(x):
s += ':)'
print(s)
You're almost there! In fact, you can multiply string and integer values. This code does what you described:
print(':) '*int(input("Enter number 1 to 10: ")))
If you really want to use a for loop and +=, you could also do this
x, s = input("enter number 1 to 10: "), ''
for i in range(x):
s += ':) '
print(s)
Answer: How to print a string x times based on user input
Credits to: NoobCoder33333
times = input('Enter number from 1 to 10: ')
word = ":-)"
print('\n'.join([word] * int(times)))
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)]))
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.
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
I'm running the following code from the command line (python filename.py) and it wont terminate. I've tried the code outside of a procedure and have tried the procedure in an online interpreter, so I don't think it's the the algorithm. What am I doing wrong?
n = raw_input("Enter a number: ")
def print_multiplication_table(n):
x = 1
while x <= n:
y = 1
while y <= n:
z = x * y
print x, " * ", y, " = ", z
y += 1
x += 1
print_multiplication_table(n)
You should convert the number received from raw_input into an integer. Right now it's being compared as a string.
An easy (but probably bad) way to do this:
n = int(raw_input("Enter a number: "))
There is a problem with the raw_input command. I have a similar code myself (guess we're both following the Udacity course). I tried to add the raw_input line to my code, and it ended up in an infinite loop too.