This code is supposed to turn decimals into binary, i figured out that part but now i need the code to go back to the previous question of asking to type in a integer instead of closing the program when calculations are done.
Here is what i have so far
def binary(n):
if n > 1:
binary(n//2)
print(n % 2,end = '')
dec = int(input("Enter an integer: "))
binary(dec)
input("\n\nPress the enter key to exit.")
Both a for loop and a while loop would help you to achieve the required outcome, depending on how many times you want the statement to loop. If you know the amount of times, use a for loop, however if you are comparing it do a condition, a while loop would probably be best. Find the syntax for for loops in python here
All you need is a simple while loop. It checks to see if the condition is true, and then executes the nested code. Therefore, putting True as the condition will make it an infinite loop.
def binary(n):
if n > 1:
binary(n//2)
string print(n % 2,end = '')
while True:
dec = int(input("Enter an integer: "))
binary(dec)
input("\n\nPress the enter key to exit.")
Related
Sorry if I phrased the question poorly, I am creating a basic game which generates a random number and asks the user to try guessing the number correctly and helps the user in the process.
import random
#print("************* THE PERFECT GUESS *****************")
a = random.randint(1,5)
num = int(input("enter a number : "))
while (num<a):
print("try guessing higher \U0001F615")
num = int(input("enter a number : "))
while (num>a):
print("try guessing lower \U0001F615")
num = int(input("enter a number : "))
if (num == a):
print("yay! You guessed it right,congrats \U0001F60E!")
Here , once I execute the program, it gets stuck in the while loop and the compiler asks me to keep guessing forever. Why is the code stuck in the while loop? Its an entry controlled loop so i thought it would break out of the loop as soon as the condition was false.
Why is the code stuck in the while loop?
Because computers do what tell them to do, not what you want them to do.
Num = new_guess()
While num!=a:
If a<num:
Too_high()
Else:
Too_low()
Num = new_guess()
Sorry for the capitals
For you if you wanted to break put of a loop:
Easiest way:
break
The harder, force stop way:
import sys
sys.exit()
I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.
I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)
I'm having some trouble with breaking out of these loops:
done = False
while not done:
while True:
print("Hello driver. You are travelling at 100km/h. Please enter the current time:")
starttime = input("")
try:
stime = int(starttime)
break
except ValueError:
print("Please enter a number!")
x = len(starttime)
while True:
if x < 4:
print("Your input time is smaller than 4-digits. Please enter a proper time.")
break
if x > 4:
print("Your input time is greater than 4-digits. Please enter a proper time.")
break
else:
break
It recognizes whether the number is < 4 or > 4 but even when the number inputted is 4-digits long it returns to the start of the program rather than continues to the next segment of code, which isn't here.
You obviously want to use the variable done as a flag. So you have to set it just before your last break (when you are done).
...
else:
done = 1
break
The reason it "returns to the beginning of the program" is because you've nested while loops inside a while loop. The break statement is very simple: it ends the (for or while) loop the program is currently executing. This has no bearing on anything outside the scope of that specific loop. Calling break inside your nested loop will inevitably end up at the same point.
If what you want is to end all execution within any particular block of code, regardless of how deeply you're nested (and what you're encountering is a symptom of the issues with deeply-nested code), you should move that code into a separate function. At that point you can use return to end the entire method.
Here's an example:
def breakNestedWhile():
while (True):
while (True):
print("This only prints once.")
return
All of this is secondary to the fact that there's no real reason for you to be doing things the way you are above - it's almost never a good idea to nest while loops, you have two while loops with the same condition, which seems pointless, and you've got a boolean flag, done, which you never bother to use. If you'd actually set done to True in your nested whiles, the parent while loop won't execute after you break.
input() can take an optional prompt string. I've tried to clean up the flow a bit here, I hope it's helpful as a reference.
x = 0
print("Hello driver. You are travelling at 100km/h.")
while x != 4:
starttime = input("Please enter the current time: ")
try:
stime = int(starttime)
x = len(starttime)
if x != 4:
print("You input ({}) digits, 4-digits are required. Please enter a proper time.".format(x))
except ValueError:
print("Please enter a number!")
I have a function below which is part of my big main function, what I want this function to do is that whenever called, I want the function to check if the user input is
a number or not. If it is a number it will return the number and break.
But if it is not a number I want it to loop again and again.when I try to
run it, it gives me unexpected an error:
unexpected eof while parsing
can any body help me what I am missing or how I should rearrange my code? thank you!
def getnumber():
keepgoing==True
while keepgoing:
number = input("input number: ")
result1 = number.isdigit()
if result1 == 1:
return number
break
elif keepgoing==True:
A neater and clearer what to do what you are already doing:
def getnumber():
while True:
number = input("Input number: ")
if number.isdigit():
return number
That's all you need, the extra variables are superfluous and the elif at the end makes no sense. You don't need to check booleans with == True or == 1, you just do if condition:. And nothing happens after return, your break will never be reached.
You don't need the last line:
elif keepgoing==True:
It's waiting for the rest of the file after the :.
Side note, it should be a single = in the first part, and can just be written simpler as well.
def getnumber():
while True:
number = input("input number: ")
result1 = number.isdigit()
if result1:
return number
Since you're inside the while loop, it'll keep executing. Using return will end the while loop, as will breaking and exiting the program. It will wait for input as well each time, though.
While assigning you have used keepgoing == True, I think it should be keepgoing=True
The following solution works on my machine, although I am running Python 2.7
def get_num():
while True: #Loop forever
number_str = raw_input("> Input a number: ") #Get the user input
if number_str.isdigit(): #They entered a number!
return int(number_str) #Cast the string to an integer and return it
I used raw_input rather than input, because raw_input gives you the exact string the user entered, rather than trying to evaluate the text, like input does. (If you pass the 12 to input, you'll get the number 12, but if you pass "12", you'll get the string '12'. And, if you pass my_var, you'll get whatever value was in my_var).
Anyway, you should also know that isdigit() returns whether or not the string has only digits in it and at least one character - that is not the same thing as isNumber(). For instance, "123".isdigit() is True, but "123.0".isdigit() is False. I also simplified your loop logic a bit.