Broken binary converter. Index error - python

i have no idea why this is broken. Also dont tell me to use python's built in function because this is designed for some practice not to actually be used. It is binary to decimal that is broken. It has a index error with the variable 'index'
print('Please choose from the list below:')
print('')
print('1) Convert from decimal/denary to binary; ')
print('2) Covert from binary to denary/decimal; ') #Main Menu
print('3) Infomation and settings (coming soon);')
print('4) Exit. ')
print('')
menu_choice = str(input('Enter your choice here: ')) #User inputs choice here
if menu_choice == '1':
dec_binary()
elif menu_choice == '2':
binary_dec()
elif menu_choice == '3':
print('By Callum Suttle')
else:
return 'Thank You'
def dec_binary(): #Module 1: decimal to binary
dec = int(input('Enter a number in decimal up to 255: ')) #Checks The number is an ok size, could be made bigger
while dec > 255:
dec = int(input('Enter a number up to 255, no more: '))
power = int(7) #change 7 to make bigger by 1 digit
convert = []
while power > -1: #until power goes below zero
if dec - pow(2, power) >= 0: #if entered number subtract 2 to the power of var-pow returns posotive number
convert.append(1)
power -=1 # add a 1
dec = dec - pow(2, power) >= 0
else:
convert.append(0)#if not add a zero
power -=1
print('')
print(convert) # print completed number
print('')
binary_decimal_converter() #back to main menu
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) != 7: #checks for correct length
l_bi = str(input('Enter a number in binary up to 7 digits, you may add zeros before: '))
power = 7 #size can be increased by using this
index = 0
while index > 6: #until every power has been checked (in reverse order)
if l_bi[index] == '1': #if the digit is equal to 1
anwser += pow(2, power) #add that amount
power -= 1 #take the power to check next #why is this broken
index += 1 # add another index to check previous
else:
power -= 1 #as above
index += 1 #/\
print('')
print(anwser) #prints result
print('')
binary_decimal_converter() #main menu

this doesn't seem right
index = 0
while index > 6: #until every power has been checked (in reverse order)
...
you never enter this loop, do you?
a better loop would be something like
for i, bit in enumerate(l_bi):
answer += int(bit) * pow(2, 7-i)
also, since you're just practicing, you should find a better way to jump from menu to functions and back. you're doing recursive calls, which is a waste of stack, i.e. your functions actually never finish but just call more and more functions.

Some fixes:
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) > 7: # LOOP UNTIL LENGTH IS LESS THAN 7
l_bi = str(input('Enter... : '))
power = len(l_bi) - 1 # directly set the power based on length
index = 0
while index < len(l_bi): # CORRECT LOOP CONDITION

Related

How do I write a for loop in Python to repeatedly ask the user to enter a number until they enter in a whole number (0, 1, 2, etc)?

I know how to do this with a while loop and know how to use a for-loop in other languages like Java and C++. I want to use a for-loop in place of where I have written the while loop asking for the user input.
# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
# a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
# input value to compute the sum of the following series:
n = -1
while n < 0:
n = int(input("Enter a value to compute: "))
# keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
k = 0
sum = 0
# To hold the sum of the fraction to be displayed
lastTerm = 0
# This variable represents the last term to be added to the fraction sum before the while loop below terminates
if n == 0:
sum = 0
elif n == 1:
sum = 1
else:
while lastTerm != 1 / n:
lastTerm = (n - k) / (k + 1)
sum = sum + (n - k) / (k + 1)
k += 1
print("{:.2f}".format(sum))
# Print the sum to two decimal places
One option is to catch the exception which is thrown when you cannot convert the input to an int, i.e.
while(True):
try:
# read input and try and covert to integer
n = int(input("Enter a value to compute: "))
# if we get here we got an int but it may be negative
if n < 0:
raise ValueError
# if we get here we have a non-negative integer so exit loop
break
# catch any error thrown by int()
except ValueError:
print("Entered value was not a postive whole number")
Alternative, slightly cleaner but I'm not 100% sure isdigit() will cover all cases
while(true):
n = input("Enter a value to compute: ")
if value.isdigit():
break
else:
print("Entered value was not a postive whole number")
How about this? It uses the for loop and sums all the values in the list.
x=[1,2,3,4] #== test list to keep the for loop going
sum_list=[]
for i in x:
j=float(input("Enter a number: "))
if not j.is_integer() or j<0:
sum_list.append(j)
x.append(1) #=== Add element in list to keep the cyclone going
else:
break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))
Use this to check for whole numbers -
if num < 0:
# Not a whole number
elif num >= 0:
# A whole number
for a for loop:
import itertools
for _ in itertools.repeat([]): # An infinite for loop
num = input('Enter number : ')
if num < 0:
# Not a whole number
pass # This will ask again
elif num >= 0:
# A whole number
break # break from for loop to continue the program
Easier Way -
mylist = [1]
for i in mylist : # infinite loop
num = int(input('Enter number : '))
if num < 0:
mylist.append(1)
pass # This will ask again
elif num >= 0:
# A whole number
break

hailstone program in python

i have to write a hailstone program in python
you pick a number, if it's even then half it, and if it's odd then multiply it by 3 and add 1 to it. it says to continue this pattern until the number becomes 1.
the program will need methods for the following:
accepting user input
when printing the sequence, the program should loop until the number 1.
print a count for the number of times the loop had to run to make the sequence.
here's a sample run:
prompt (input)
Enter a positive integer (1-1000). To quit, enter -1: 20
20 10 5 16 8 4 2 1
The loop executed 8 times.
Enter a positive integer (1-1000). To quit, enter -1: 30
30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
The loop executed 19 times.
Enter a positive integer (1-1000). To quit, enter -1: -1
Thank you for playing Hailstone.
right now i have this:
count = 0
def hailstone(n):
if n > 0
print(n)
if n > 1:
if n % 2 == 0:
hailstone(n / 2)
else:
hailstone((n * 3) + 1)
count = count + 1
i don't know what to do after this
Try to think in a modular way, make two functions: check_number() and user_call(). Check_number will verify if the current number in the loop is odd or even and the user_call() just wraps it to count how many times the loop did iterate.
I found the exercise in a great book called Automate Boring Stuff with Python, you have to check it out, if you don't know it already.
Here's my code. Try to use what serves you the best.
from sys import exit
def check_number(number):
if number % 2 ==0:
print(number // 2)
return(number // 2)
else:
print(number*3+1)
return number*3+1
def user_call(number):
count = 0
while number != 1:
count += 1
number = check_number(number)
return count
if __name__ == "__main__":
try:
number = int(input('Give a number \n'))
count = user_call(number)
print('count ',count)
except Exception as e:
exit()
you can use global
visit https://www.programiz.com/python-programming/global-keyword to learn more
import sys
res = []
def hailstone(number):
global res
if number > 1:
if number % 2 == 0:
res.append( number // 2 )
hailstone(res[len(res)-1])
else:
res.append(number * 3 + 1)
hailstone(res[len(res)-1])
return res
number = int(input('Enter a positive integer. To quit, enter -1: '))
if number <= 0 or number == 0:
print('Thank you for playing Hailstone.')
sys.exit()
else:
answers = hailstone(number)
for answer in answers:
print(answer)
print('The loop executed {} times.'.format(len(answers) + 1))
I used recursion to solve the problem.
Heres my code:
Edit: All criteria met
count = 0
list_num = []
def input_check():
number = int(input("Enter a positive integer (1-1000). To quit, enter -1: "))
if number >= 1 and number <= 1000:
hailstone_game(number)
elif number == -1:
return
else:
print("Please type in a number between 1-1000")
input_check()
def hailstone_game(number):
global count
while number != 1:
count += 1
list_num.append(number)
if number % 2 == 0:
return hailstone_game(int(number/2))
else:
return hailstone_game(int(number*3+1))
list_num.append(1) # cheap uncreative way to add the one
print(*list_num, sep=" ")
print(f"The loop executed {count} times.")
return
input_check()
Additional stuff that could be done:
- Catching non-integer inputs using try / except
Keep in mind when programming it is a good habit to keep different functions of your code separate, by defining functions for each set of 'commands'. This leads to more readable and easier to maintain code. Of course in this situation it doesn't matter as the code is short.
Your recursive function is missing a base/terminating condition so it goes into an infinite loop.
resultArray = [] #list
def hailstone(n):
if n <= 0: # Base Condition
return
if n > 0:
resultArray.append(n)
if n > 1:
if n % 2 == 0:
hailstone(int(n/2))
else:
hailstone((n * 3) + 1)
# function call
hailstone(20)
print(len(resultArray), resultArray)
Output
8 [20, 10, 5, 16, 8, 4, 2, 1]
Here's a recursive approach for the problem.
count=0
def hailstone(n):
global count
count+=1
if n==1:
print(n)
else:
if n%2==0:
print(n)
hailstone(int(n/2))
else:
print(n)
hailstone(3*n+1)
hailstone(21)
print(f"Loop executed {count} times")

Python: Finding Average of Numbers

My task is to:
"Write a program that will keep asking the user for some numbers.
If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places.
If at any point a 0 is entered, that should not be included in the calculation of the average"
I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0.
This is my current code:
count = 0
sum = 0
number = 1
while number >= 0:
number = int(input())
if number == '\n':
print ('hey')
break
if number > 0:
sum = sum + number
count= count + 1
elif number == 0:
count= count + 1
number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
You're very close! Almost all of it is perfect!
Here is some more pythonic code, that works.
I've put comments explaining changes:
count = 0
sum = 0
# no longer need to say number = 1
while True: # no need to check for input number >= 0 here
number = input()
if number = '': # user just hit enter key, input left blank
print('hey')
break
if number != 0:
sum += int(number) # same as sum = sum + number
count += 1 # same as count = count + 1
# if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}') # same as '... {:.2f} ...'.format(count/sum)
Why your code didn't work:
When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.
I really hope this helps you learn!
Try this:
amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
nums+=int(number)
amount += 1
print(round(nums/amount,2)) # Print out the average rounded to 2 digits
Input:
1
2
3
4
Output:
2.5
Or you can use numpy:
import numpy as np
n = []
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
n.append(int(number))
print(round(np.average(n),2)) # Print out the average rounded to 2 digits
A list can store information of the values, number of values and the order of the values.
Try this:
numbers = []
while True:
num = input('Enter number:')
if num == '':
print('Average is', round(sum(numbers)/len(numbers), 2)) # print
numbers = [] # reset
if num != '0' and num != '': numbers.append(int(num)) # add to list
Benefit of this code, it does not break out and runs continuously.

Computer guessing a user-selected number within a defined range

This is my code for a game in which the computer must guess a user defined number within a given range. This is a challenge from a beginners course/ book.
I'd like to draw your attention to the 'computerGuess()' function. I think there must be a more eloquent way to achieve the same result? What I have looks to me like a botch job!
The purpose of the function is to return the middle item in the list (hence middle number in the range of numbers which the computer chooses from). The 0.5 in the 'index' variable equation I added because otherwise the conversion from float-int occurs, the number would round down.
Thanks.
Code:
# Computer Number Guesser
# By Dave
# The user must pick a number (1-100) and the computer attempts to guess
# it in as few attempts as possible
print("Welcome to the guessing game, where I, the computer, must guess your\
number!\n")
print("You must select a number between 1 and 100.")
number = 0
while number not in range(1, 101):
number = int(input("\nChoose your number: "))
computerNumber = 0
computerGuesses = 0
higherOrLower = ""
lowerNumber = 1
higherNumber = 101
def computerGuess(lowerNumber, higherNumber):
numberList = []
for i in range(lowerNumber, higherNumber):
numberList.append(i)
index = int((len(numberList)/2 + 0.5) -1)
middleValue = numberList[index]
return middleValue
while higherOrLower != "c":
if computerGuesses == 0:
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "l":
higherNumber = computerNumber
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "h":
lowerNumber = computerNumber + 1
computerNumber = computerGuess(lowerNumber, higherNumber)
print("\nThankyou. My guess is {}.".format(computerNumber))
computerGuesses += 1
higherOrLower = input("\nHow did I do? If this is correct, enter\
'c'. If your number is higher, enter 'h'. If it is lower, enter 'l': ")
print("\nHaha! I got it in {} attempt(s)! How great am I?".format\
(computerGuesses))
input("\n\nPress the enter key to exit.")
Like this ?
import math
def computerGuess(lowerNumber, higherNumber):
return int((lowerNumber+higherNumber)/2)

Python: separating less than 25 int and greater than 25 int inputs then working with those numbers

Write a Python program that reads in a series of positive integers and writes out the product of all the integers less than 25 and the sum of all the integers greater than or equal to 25. Use 0 as a sentinel value.
def main():
user_input = 1
while user_input != 0:
user_input = int(input("Enter positive integers, then type 0 when finnished. "))
if (user_input) < 25:
product = 1
product = (user_input) * product
else:
(user_input) >= 25
sum = 0
sum = (user_input) + sum
print('The product off all the integers less than 25 is ', product, "and the sum of all the integers greater than 25 is ", sum, ".")
main()
Here is what I have so far. This is my first python code for my intro to computer science class.
My major roadblocks is that the sentinel value has to be zero and I user_input to multiply by the product which is just zeroing everything out.
Some minor corrections to your code.
Initialise the sentinels outside of the loop or they get reset every time.
Else clause syntax error and changed to an elif
Renamed sum to not clash with python builtin sum
Protected product total from multiply by zero on exit.
Code:
def main():
sum_total, product = 0, 1
user_input = 1
while user_input != 0:
user_input = int(input("Enter positive integers, then type 0 when finnished. "))
if 0 < user_input < 25:
product *= user_input
elif user_input >= 25:
sum_total += user_input
print("The product off all the integers less than 25 is ", product)
print("The sum of all the integers greater than 25 is ", sum_total)
You could always check if the the sentinel value is 0, if so just add the value to it.

Categories