Python not running my program without any error - python

I need to create a program that will convert Base 10 numbers in Base 2.
Next is the code, it can not run as expected even if it has no error:
E = input('Please enter a number')
Eint= int(E)
for N in range(100,0):
while 2**N > Eint:
N = N-1
print(0)
if B**N <= Eint:
Eint = Eint - 2**N
print(1)
Print('finished')
When I'm running it it will ask me the number but that's all, thank you for your help guys.

From a quick inspection, range(100,0), B, and Print() are three culprits here! If you want to pass through numbers from 0 to 99, then range(100) is what you need. Now, what is B? Print should be written in lower case: print.
After we fix these syntax errors, let us try to revisit the program and understand what it is supposed to do. Have fun :-)
EDIT to fix the code in the question:
E = input('Please enter a number: ')
Eint = int(E)
for N in range(8,-1,-1):
if 2**N > Eint:
print(0, end='')
else:
Eint = Eint - 2**N
print(1, end='')
print()
print('finished')
Please note that Python is a language that uses indentations to denote code blocks. This code will convert a decimal to binary. Now, note that the range start of 8 gives you a hint about the upper bound of the number that the code can translate. Therefore, an if condition must be added after the second statement to ensure we are not attempting to convert a number that is too large. Enjoy!

If it helps check my solution too. Because I guess you don't want to see the result on separate lines, so I create a list for you to see the result in one line.
E = int(input('Please enter a number\n'))
Eint = E
base_two=[]
while E > 0:
a = int(float(E%2))
base_two.append(a)
E = (E-a)/2
base_two.append(0)
string = ""
for j in base_two[::-1]:
string = string+str(j)
print("Binary for", Eint, "is", string)
print('finished')
I was late a little bit :)

Related

How can I stop a program when the user wants to?

So I made a program which asks the user the amount of numbers he wants, which numbers he wants and creates a list. I now want to make it so that if the user puts in the number 0 the program will stop there and print the previous numbers he has put if it's possible (note: I want the 0 to not be printed only the previous numbers he entered). Because this is my first time posting I'm not sure what else information is needed other than what version of Python I'm using (which is 2.7). If there's more information that's needed just ask. Also if it's needed I'll write the code I have written down.
lst = []
x = int(input("Enter number of elements : "))
for i in range(0, x):
num = int(input())
lst.append(num)
print(lst)
Before lst.append(num)
if num == 0:
break
Add a if-else statement:
if num != 0:
lst.append(num)
else:
break

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

Loop is not geting exited in Python

I am trying to write a simple progrm in Python but when my number is getting equal to number the else statement keeps repeating itself. Help
print('Tell me your name Ramesh')
import random
name=input()
print('Howdy, '+name)
print('Guess my number which is in between 1 to 20')
number=input()
mynumber = random.randint(1, 20)
count = 0
while(mynumber!=number):
if (int(number) > mynumber):
print('Howdy, Your number is too high. Plz renter')
number=input()
count=count+1
elif (int(number)< mynumber):
print('Howdy, Your number is too low. Plz renter')
number=input()
count=count+1
else :
print('Howdy you got it in '+ str(count)+' chances. The correct number is '+number)
I've only just started python myself and had the same issue.
Your if statements all convert the entered number to an int however your while doesn't. so it's comparing an int and string. Try:
while(mynumber != int(number))
or change the input to read
number = int(input("blah")).
I like this more even though it will throw an error if you enter text.
You may also need to change the while to read while(mynumber != int(number)) as well as adding in the break within the ELSE. You could also remove the else and just let the loop fall out if the numbers match and then show the success message.

A number from Multiple Numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an assignment. It was suppose to do the following:
--> Take an integer input(say 100)
--> Add the digits till the sum is a single digit number(1)
My program till now is:
goodvalue1=False
goodvalue2=False
while (goodvalue1==False):
try:
num=input("Please enter a number: ")
except ValueError:
print ("Wrong input. Try again.")
else:
goodvalue1=True
if (goodvalue1==True):
ListOfDigits=list(map(int,str(num)))
sum=10
while(sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
Those booleans are not needed. You can factor the code down to:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
I don't see why you called list(map(int, str(num))); but I think you were intending to put int() around your input. So I added one in above. Now it can catch an error :).
Now, to get one digit, you can use another while loop here:
while num > 9:
num = sum(map(int, str(num)))
Pretty much this creates [1, 0, 0] which sum() then calls on. This repeats until it is no longer a two digit number (or three, four, etc)
So altogether:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
while num > 9: # While it is a two digit number
num = sum(map(int, str(num)))
Just note that for conditional statements, it's never pythonic to do a == True or b == False.
From the PEP:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
My take on this:
inp = None
while inp is None:
try:
inp = int(input('Enter number here: '))
except ValueError:
print('Invalid Input, try again')
summed = sum(map(int, str(inp)))
while summed > 9:
summed = sum(map(int, str(summed)))
print('The result is {}'.format(summed))
For an explanation #Haidro did a good job: https://stackoverflow.com/a/17787707/969534
You're very close. Here's what you need to change:
Sum=sum(ListOfDigits)
while(Sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
In this code, you have a while loop that executes when sum is bigger than 9. So why use another variable Sum (also, it makes for really difficult-to-read code)? Do this instead:
while(sum>9):
sum=sum(ListOfDigits)
ListOfDigits=list(map(int,str(sum)))
This is only to show you what went wrong with your code. I wouldn't recommend using it (look below for what I would do). First, you mix variable-naming conventions, which is a very bad idea, especially when you work in a team (even otherwise, can you imagine looking at your code a month or six months from now?).
Second, you don't ever use goodvalue2; what's it there for?
Third, if goodvalue1 is only ever going to be a bool, then why check if (goodvalue1==True)? if goodvalue1 is clearer and more pythonic.
Please, for the love of all that is good, use some spaces in your code. Eyes get very strained after looking at expressions like ListOfDigits=list(map(int,str(num))) for a while. Try ListOfDigits = list(map(int, str(num))) instead.
Personally, I would do this:
num = None
while num is None:
try:
num = int(raw_input("Enter a number: "))
except ValueError:
num = None
num = sum(int(i) for i in str(num))
while num > 9:
num = sum(int(i) for i in str(num)) # this uses a list comprehension. Look it up, they're very useful and powerful!
RECURSION !
Calculate the sum of the digits. Check if the sum has one digit or multiple digit. If one digit, that is your answer, else, call the function on the sum again.
def oneDigitSum(n):
if n < 10:
return n
else:
return oneDigitSum(sum([int(i) for i in str(n)]))
# [f(elem) for elem in li] = [f(a), f(b), .... ] where li = [a, b, ... ]
# sum returns the total of the numbers in list
while True: # continue this loop for eternity, until it gets break
try:
num=int(input("Please enter a number: "))
print(oneDigitSum(num))
break # printed the sum, now I can break the loop peace fully
except ValueError:
print ("Wrong input. Try again.")
continue # oops, looks like wrong input, lets continue the loop

Python ISBN program

I'm trying to calculate the check digit for an ISBN input on python. so far I have...
def ISBN():
numlist = []
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
**numlist == request
print numlist**
if len(request) != 10:
print "Invalid Input"
ISBN()
ISBN()
The bold bit is where im having trouble, I cant seem to split the 10 digit input into individual numbers in the list (numlist) and then multiply the seperated individual numbers by 11 then the next by 10 then the next by 9 etc...
For the next part of the program, I will need to add these new multiplied numbers in the list together, then i will use the mod(%) function to get the remainder then subtract the number from 11, any assistance with any of my coding or incorrect statements on how to calculate the ISBN would be greatly appreciated.
Thank you.
This code should get you on your way:
listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]
Strings are iterable, so if you iterate them, each element is returned as a single-character string.
int builds an int from a (valid) string.
The notation [a*b for a,b in zip(listofnums, multipliers)] is a list comprehension, a convenient syntax for mapping sequences to new lists.
As to the rest, explore them in your repl. Note that reversed returns a generator: if you want to see what is "in" it, you will need to use tuple or list to force its evaluation. This can be dangerous for infinite generators, for obvious reasons.
I believe list() is what you are looking for.
numlist=list(request)
Here is how I would write the code. I hope I'm interpreting the code correctly.
def ISBN():
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
numlist = list(request)
print numlist
else:
print "Invalid Input"
ISBN()
import itertools
if sum(x * int(d) for x, d in zip(nums, itertools.count(10, -1))) % 11 != 0:
print "no good"

Categories