Python 3.4.2 IDLE: Error when defining 'denaryInput' - python-3.x

I am just new really to programming and for homework we had to make a denary to binary converter for homework, using a number inputed by the user. When I run this code I get the following error:
if denaryInput < 0:
NameError: name 'denaryInput' is not defined
I am unsure what I am doing wrong and any answers greatly appreciated.
Code used:
"""We are asking the user for a number"""
def getNumber():
denaryInput = int(input("Please enter a number between 0 and 255: "))
"""We are validating the number"""
def validateNumber():
if denaryInput < 0:
print("Error: Number is too small, try again!" + " \n")
return False
elif denaryInput > 255:
print("Error: Number is too big, please try again!" + " \n")
return False
else:
return True
def binaryNumber():
result = []
for number in range(8):
bit = denaryInput % 2
result.append(bit)
denaryInput = denaryInput // 2
result.reverse()
str1 = "".join(str(x)for x in result)
print (str1 + " \n")
"""Now telling the computer to run the code above and in what order of operations"""
def mainProgram():
answer = getNumber()
validNum = validateNumber()
Binary = binaryNumber()
print("The binary equlivent for that number is " + Binary + " \n")
mainProgram()

You need to pass the denaryInput from the getnumber function as part of a call. The validatenumber function needs a value passed into it to actually be validated. These should be different names in each function.
E.g.:
def validateNumber(numIn):
if numIn < 0
Also, you should validate the number from the getnumber function
denaryInput = int(input("Please enter a number between 0 and 255: "))
if validateNumber(denaryInput): #returns true if number valid
Return denaryInput
Finally, binary is a keyword and should NOT appear in your main function.

Related

I'm trying to make a sequence calculator with python, and I would like to restart the code at a certain point but I don't know how to do that [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last year.
I am fairly new to programming and I scrapped some code together to make a sequence calculator using python.
I'm trying to restart it at the "user_continue = input ("Would you like restart [y/n]? ")" part whenever the user would input an invalid answer, but I don't know how to do that, help?
import time
from time import sleep
while True:
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")
???
import time
from time import sleep
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
def takeInputs():
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
takeInputs()
while True:
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
takeInputs()
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")

How to fix issue where python won't call a function from within a loop

At the yes/no loop, the program won't call the function to re-perform a calculation. Instead, it asks to compute another gcd repeatedly instead of calling the specified function.
I've tried re-inputting the whole function into the question loop if the user inputs yes, but that did not work either.
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
GCD = gcd(n,m)
print("The GCD of the two numbers you entered is:" ,GCD)
while True:
a = input("Compute another GCD? Enter y/n:").lower()
if a=="y":
gcd(n,m)
elif a=="n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
Expected results is that it calls the function gcd(n,m) and re-performs a calculation. Actual results is that it asks to perform another calculation without having actually completed a second calculation.
The function is called. The problem is that you don't do anything with its return value.
You will also need to ask the user for new input. In order to not repeat the same code again you can have a function that does that.
Then the whole code becomes:
def get_2_numbers():
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
return n, m
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
a, b = get_2_numbers()
while True:
answer = input("Compute another GCD? Enter y/n:").lower()
if answer == "y":
print(gcd(a, b))
a, b = get_2_numbers()
elif answer == "n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
A small downside is that the user will have to answer y even before the first calculation, but I'll leave that as an exercise to the reader.

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

Python 3.7: How do I check if a user input is in a specific format, like "XdY", then if invalid ask again for input?

I'm trying to write a dice roller as practice. I've tried to look into try, except, while, but neither works as I intend it - before asking if the user wants to continue, I'd want to check if the user input is valid, and if not, return to user_number1. Am I looking at this from the wrong angle? What can I do with this?
Sorry for the possibly stupid question, I'm pretty new to this.
import random
print("Welcome to the dice roller!")
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
if num1 == 1:
result1 = random.randint(num1, num1*num2)
print("Your roll is: " + str(result1) + " (" + str(num1) + "d" + str(num2) + ")" )
else:
dice_number = 1
list_of_results = []
while dice_number <= num1:
result2 = random.randint(num1, num2)
list_of_results.append(result2)
dice_number += 1
print("Your roll is: " + str(sum(list_of_results)) + " (" + str(num1) + "d" + str(num2) + ", " + str(list_of_results)+ ")")
def shouldi():
roller()
usercont = input("Do you want to continue? y/n > ")
while usercont in ["Y", "y"]:
roller()
usercont = input("Do you want to continue? y/n > ")
if usercont in ["N", "n"]:
print("Thank you for using the dice roller. Bye!")
quit()
else:
print("That is not a valid input.")
usercont
Something like below is an alternate approach to using regex. If you're comfortable with regex then I would prefer using that instead of this. This is only an alternate approach.
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
if("d" in user_number1):
if(len(user_number1) == 3):
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
else:
print("Your input not in valid format. Use the format XdX")
You can use regular expressions and write a function that does exactly what you need then you can use it within your roller() function:
import re
def get_number():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = re.match("^(\\d*)d(\\d+)$",user_number1,re.I)
if not user_number_fin: get_number()
if user_number_fin.group(1) =='': num1 = 1
else: num1 = int(user_number_fin.group(1))
num2 = int(user_number_fin.group(2))
if num1>num2:
print("\n\tSorry--side to roll must be less than the number of sides!!")
get_number()
return {'num1':num1,'num2':num2}
This can accept d4 ie taking the default side if not given to be 1, and cannot accept 4d3 ie the side to be rolled must be less than the number of sides present in the dice.

I cant make the program continue to loop if its invalid input is entered

I have this program:
number = int(input('Contact Number:'))
def validatePhoneNumber(number):
count = 0
while True:
while number > 0:
number = number//10
count = count+1
if (count == 10) :
break
elif (count > 10) :
print('Invalid phone number')
return -1
elif (count < 10):
print('Invalid phone number')
return -1
validatePhoneNumber(number)
it will appear like this:
Contact Number:1234
Invalid phone number
>>>
I want it to continue to loop until a 10 digit number is entered then it will stop.
Contact Number:1234567890
>>>
The condition is that If the number is missing or invalid, return ‐1.
Am I missing something inside the program?
Thanks
What about this:
number = input('Contact Number:') # it's a str now, so we can use len(number)
def validatePhoneNumber(number):
while len(number) != 10:
number = input("Please enter a 10-digit contact number: ")
return number
number = validatePhoneNumber(number)
It's a more pythonic approach and therefore easier to understand and debug. Also as other comments pointed out, leading 0s aren't stripped away now.

Resources