I'm trying to replace a value entered by a user with a string to make the output cleaner
I thought an if statement would help, but I'm not sure how it would tie in with my intended output
def main() :
number = int(input("Enter your number: "))
base = int(input("Convert to\n" \
" Binary[2] - Octal[8] - Hexadecimal[16]: "))
if base == 2 :
"binary"
elif base == 8 :
"octal"
else:
"hexadecimal"
print("\n"+str(number) +" in "+ str(base) + " is: " + str(convert(number, 10, base)))
def convert(fromNum, fromBase, toBase) :
toNum = 0
power = 0
while fromNum > 0 :
toNum += fromBase ** power * (fromNum % toBase)
fromNum //= toBase
power += 1
return toNum
main()
What I'm trying to get:
if user enters 5 as their number and 2 as conversion. Output would be:
"5 in binary is: 101"
Try
def main() :
number = int(input("Enter your number: "))
base = int(input("Convert to\n" \
" Binary[2] - Octal[8] - Hexadecimal[16]: "))
base_string = "None"
if base == 2 :
base_string = "binary"
elif base == 8 :
base_string = "octal"
else:
base_string = "hexadecimal"
print("\n {} in {} is: {}".format(str(number), base_string, str(convert(number, 10, base))))
def convert(fromNum, fromBase, toBase) :
toNum = 0
power = 0
while fromNum > 0 :
toNum += fromBase ** power * (fromNum % toBase)
fromNum //= toBase
power += 1
return toNum
main()
Your issue was the "binary" part in the if-statement. It has virtually no effect neither on your code nor on your output. You have to store the literal representation ("binary",...) in some variable ("base_string"). Then you can use this variable in your output.
As an aside, it looks like your base conversion won't actually do what you want. You should look at How to convert an integer in any base to a string? to do the conversion properly (hexadecimal has letters A-F in it, those aren't handled by your code, for example).
To accept a name instead of a number, you need to change this line of code:
base = int(input("Convert to\n Binary[2] - Octal[8] - Hexadecimal[16]: "))
What's happening here? input() takes a line from stdin. In the interactive case, this means the user types something (hopefully a number) and then hits enter. We get that string. Then int converts that string to a number.
Your convert expects base to be a number. You want inputs like "binary" to correspond to base = 2. One way to achieve this is with a dict. It can map strings to numbers:
base_name_to_base = {'binary': 2, 'octal': 8, 'hexadecimal': 16}
base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]
Note that base_name_to_base[x] can fail (raise KeyError) if x is not a key in the dict. So you want to handle this (what if the user enters "blah"?):
while True:
try:
base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]
break
except KeyError:
pass
This will loop until we hit the break (which only happens when indexing into base_name_to_base doesn't raise the key error.
Additionally, you may want to handle different cases (ex. "BINARY") or arbitrary whitespace (ex. " binary "). You can do this by calling .lower() and .strip() on the string returned by input().
Related
I'm writing a program that takes a number from input and generates it's palindrome number. My program only prints the first half not the second. I tried reverse, didnt work.I have incluede those lines as comment.
My Code:
def show_palindrome(maximum):
maximum = int(input("Enter Number : "))
for number in range(1, maximum + 1):
temporary = number
reverse = 0
while (temporary > 0):
reminder = temporary % 10
reverse = (reverse * 10) + reminder
temporary = temporary //10
if(number == reverse):
#number2 = number[::-1]
#print(number,number2, end = '')
print(number, end = '')
show_palindrome(3)
My output:
123
The output I need:
12321
I believe you're looking for something like this:
def show_palindrome(maximum = None):
if not maximum:
maximum = input("Enter Number : ")
output = str(maximum)
for number in range(1, int(maximum)):
output = str(int(maximum) - number) + str(output) + str(int(maximum) - number)
return output
print(show_palindrome(3))
this returns 12321 for instance
A couple of things I would do differently in your function:
If you're going to require the input in the def (The way you make it optional is to set it equal to something when you declare it like I have it set to None (maximum=None), then you don't need the input() statement.
Since you already know how long you want it to be ( you require it declared when you initialize the function, it's just 2*maximum - 1) there's really no need to use a while loop.
Other than that good job! Keep it up!
You can try something simpler like this:
def show_palindrome():
num = input("Enter Number : ")
print(num + num[:-1][::-1])
show_palindrome()
Input:
123
12
1
Output:
12321
121
1
Apart from the string slice method (as used by #PApostol), you could also use the reversed method :
def show_palindrome():
value = input("Enter Number : ")
print(value[:-1] + "".join(reversed(value)))
Input:
123
Output:
12321
def palindrome(maximum):
number = ''.join([str(num) for num in range(1, maximum + 1)])
return int(number + number[-2::-1])
print(palindrome(3))
Output:
12321
Your code seems over complicated, and I don't even know what to fix in it. What I can tell is that passing a parameter maximum to overwrite it just after with maximum = int(input("Enter Number : ")) is useless, don't pass the parameter.
So let's back to easy things
Build palindrome using strings method : slicing backwards from index -2, and reverse it with -1 increment
def show_palindrome():
value = input("Enter Number : ")
print(value + value[-2::-1])
Build palindrome using math operations : save the remainder, except the first one
def show_palindrome():
value = input("Enter Number : ")
result = value
value = int(value) // 10 # remove last char which would be redundant
while value > 0:
result += str(value % 10)
value = value // 10
print(result)
show_palindrome()
OK so this is my code, it's a base calculator that will convert base to base with no problem, but once the answer is over 9, I want the number to be represented as a letter, just like in base 16, 10 represent 'a', so I'm stuck on how can I do that just using Ascii tables. Right now the code is running well, if I type 1011,base2, I want to convert to base 16. So the output turns out to be 11, which is correct, but I want it to be 'b'
number = input("what's your number: ")
o_base = int(input("what is your oringal base: "))
base = int(input("what's the base you want to convert: "))
answer = ""
total = 0
for i, d in enumerate(reversed(number)):
total = total + int(d) * o_base ** i
while (total != 0):
answer += str(total % base)
total //= base
print (answer)
Python can first convert your number into a Python integer using int(number, base). Next all you need to do is convert it into you target base. This is often done using divmod() which combines doing a division of two numbers and getting their remainder into one function.
To convert each digit into the correct number or letter, the easiest way is to create an string holding all of your required symbols in order, and then use an index into this to give you the one you need, e.g. digits[0] here will return 0, and digits[10] would return A.
import string
number = input("What's your number: ")
o_base = int(input("What is your original base: "))
base = int(input("What is the base you want to convert to: "))
number = int(number, o_base)
digits = string.digits + string.ascii_uppercase # 0 to 9 + A to Z
output = []
while number:
number, remainder = divmod(number, base)
output.insert(0, digits[remainder])
print(''.join(output))
This example works up to base 36 (i.e. 0 to 9 and A to Z). You could obviously extend digits to give you more symbols for higher bases.
Using a list to create the output avoids doing repetitive string concatenation which is not very efficient.
I'm using python 3.5.2 to make this program. It'supposed to take any decimal number and convert it to binary.
number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2
base2 = srt(number) + str(rem)
print(rem)
#This was to prevent the end text from sticking to the print
input('\nEnter to end')
It returns the correct values, but backwards and in a column and I don't know why.
Some modifications to your code:
number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2 # can be number //= 2, or number >>= 1
base2 += str(rem)
#print(rem) # no need to print
print(base2[::-1])
Or more simple:
base2 = bin(number)[2:]
Your code prints the lowest bit of remaining number on separate lines so that's why you see them in reverse order. You could change your code to store bits to an array and then after the loop print them in reverse order:
number = int(input('Enter a number in base 10: '))
base2 = []
while(number > 0):
base2.append(str(number % 2))
number = number // 2
print(''.join(reversed(base2)))
Python also has built-in method bin than can do the conversion for you:
>>> bin(10)
'0b1010'
As I run my code, the program always returns:
'str' object is not callable in the ninth line and I don't know why.
sum = 0
count = 0
binNum = input('Input your number: \n')
while count != len(binNum):
if binNum(count) == 1:
sum = sum + 2**count
count = count + 1
else:
count = count + 1
if count == len(binNum):
print(sum)
Thank you for your help.
Looks like you're trying to access the countth character of the string binNum, and see if it is the character '1'. In which case, you should use square brackets. And compare it to the character '1', not the digit 1.
if binNum[count] == '1':
By the way, if you're trying to convert a string of ones and zeroes into its equivalent decimal number, you're scanning over the digits backwards. In your algorithm, the leftmost digits contribute the least to the sum, and the rightmost digits contribute the most. You may want to reverse the input string before scanning it.
binNum = input('Input your number: \n')
binNum = binNum[::-1]
You have to change
if binNum(count) == 1:
to
if count == 1:
Also, you could convert input line as:
binNum = str(input('Input your number: \n'))
I must create two functions. One that can tell whether one number is odd or even by returning t/f, and the other will call the first function then return how many even numbers there are.
This is my code so far:
Even = [0,2,4,6,8]
IsEvenInput = int(input("Please enter a number: "))
def IsEvenDigit(a):
if a in Even:
return True
else:
return False
y = IsEvenDigit(IsEvenInput)
print(y)
def CountEven(b):
count = 0
for a in b:
if IsEvenDigit(a):
count+=1
return count
d = input("Please enter more than one number: ")
y = CountEven(d)
print(y)
This keeps outputting 0 and doesn't actually count. What am I doing wrong now?
d = input("Please enter more than one number: ")
This is going to return a string of numbers, perhaps separated by spaces. You'll need to split() the string into the sequence of text digits and then turn those into integers.
There's a general approach to determining whether a number is odd or even using the modulus / remainder operator, %: if the remainder after division by 2 is 0 then the number is even.
Here is another approach:
def is_even(number):
return number % 2 == 0
def even_count(numbers_list):
count = 0
for number in numbers_list:
if is_even(number): count += 1
return count
raw_numbers = input("Please enter more than one number: ")
numbers_list = [int(i) for i in raw_numbers.split()]
count = even_count(numbers_list)
print(count)
This will take care of all other numbers too.
So by calling CountEvent(d) outside the scope of the function CountEven, you aren't using recursion, you're simple calling the function after it's been defined.
Try reducing the amount of code outside of your functions.
#Start by declaring your functions:
def isEven(n):
return n % 2 == 0
def countEven():
count = 0
string_of_numbers = input("Please enter numbers separated by spaces: ")
list_of_number_characters = string_of_numbers.split(' ')
for number in list_of_number_characters:
number_as_int = int(number)
if isEven(number_as_int) == True:
count = count + 1
print("There were " + str(count) + " even numbers found.")
countEven() #Call the function that runs your program
You are counting whether the integers - [0, 2, 4, 6, 8] etc. - are characters in a string - "0", "2", "4", "6", "8" etc. Currently, IsEvenDigit(a) will never be true, because a character in a string will not be in the list of even integers, so the code beneath the if statement will never be executed. You need IsEvenDigit(int(a)) in the CountEven function.
On another topic, a commenter to your post suggested reading PEP 8. Your code is actually formatted pretty well, its just in Python, CamelCase is used just for classes, and words_seperated_by_underscores is used for variables and function names.
Or if you want brevity and unreadability, some code:
main = lambda: sum(map(lambda x: int(x) % 2 == 0, (i for i in input("Enter a number: "))))
main()
It does define 2 (anonymous) functions!
A possible solution:
def is_even(n):
return not n % 2
def count_even(numbers)
return sum(map(is_even, numbers))
nums = input("Enter numbers separated by spaces: ")
nums = map(int, nums.split())
print(count_even(nums))