issues with looping, calling functions to loop - python

I have to write a program that performs Egyptian type of multiplication. I have the math correct(for the most part) But I've searched and searched and searched and can't really pin point down a correct loop.
I need the program to loop the calculation part, ending with it asking if you want to loop it again to put in different numbers. I also need a negative section, to calculate the outcome if using negative numbers, which I am completely drawing a blank to do.
What I've got so far:
import math
def egyptian(positive):
a,b = raw_input('Please input the two numbers separated by a space').split()
a = int(a)
b = int(b)
answer = 0
while b != 0:
if (a%2 != 0):
print "B was odd, we add A to make the product: ", (a)
answer = answer+a
a = a*2
b = b//2
if (b%2 == 0):
a = A*2
b = b//2
print "The product of the two numbers is", (answer)
choice = ""
if choice != "y" or "Y":
choice = raw_input("Do you want to continue?(y/n)")
if choice == "Y" or "y":
goto NO idea what to put here to get it to loop.
if choice != "Y" or "y":
print "Quitting"
I understand the choice part at the bottom is probably way off for what I want it to do.
Any help is greatly appreciated

I don't see where you are calling your egyptian function? But what you can do is you can put all of the code inside of the egyptian function, and then you can have the function call itself to make it loop again.
Also the line choice = "" should be choice = raw_input("Do you want to continue?(y/n)"). You need to ask for the input first, and then once you have their input you add the correct logic to determine if they would like to loop again.
There is another way you could solve this issue, but it's not as good of a solution because it's always better to break your code down into smaller function, but you could also have a loop inside of a loop. The outer loop would decide if you should loop again, the inner loop does the egyptian multiplication code.

Related

how can I reduce my code? A lot of it is repetitive

The code creates a random addition problem and spits out "Congratulations" if correct and "sorry...." if the inputted value is wrong. The while loop repeats this process until the user inserts "N" for the question "continue (Y/N):, at the same time it keeps track of how many questions have been answered, and which ones are correct. The code works fine, my problem is it has repetitive code. I was wondering if there is a way to shrink it.
**I appreciate everyone one's help and advice. I"m a noob that's just learning python **
import random
correct=0
count=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
A first start, would be eliminating the code before the while, by initializing the count variable (which keeps track of the turns), in zero, and allowing the while loop to run the first turn, we just need to have a variable like want_to_play and by default it's True, so the first time we'll be playing, and at the end of the game If I don't input Y or y it will asume I don't want to play any more and set the variable to false, that way I can have all the turns ran by the while loop.
and you'll be getting something like this.:
from random import sample
correct = 0
count = 0 # STartint in turn zero
want_to_play = True # Control Variable
while want_to_play:
count += 1
# First turn this is zero, and adds one.
[num1, num2] = sample(range(0, 101), 2)
# Just another way of getting two random numbers from 1 up to (including) 100.
# Printing could be done in one line.
print(format(num1, '5d') + '\n+' + format(num2, '4d'))
answer = int(input('= '))
# The comparison really doesn't really hurt if you do it this way.
if answer == num1 + num2:
print('Congraulations!')
correct += 1
else:
print('Sorry the correct answer is', sum)
# HERE you ask if you want to play again or not, using a one line if
# you decide.
want_to_play = (True if 'y' == input('Continue (Y/N).lower():')
else False)
else:
print('Your final score is',correct,'/',count)
By initializing the variable c as "Y", the condition is met and the loop can be executed:
import random
correct=0
count=1
c = "Y"
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
c = c.upper()
else:
print('Your final score is',correct,'/',count)
I also added the method upper() to the Y/N input so the user can also type it in lowercase
Try to move as much of the processing as possible into the loop. The first "paragraph" of your code was basically a duplicate of the main-loop. By creating the continuation variable c so that it drops straight into the loop, most of that first block could be removed.
import random
correct=0
count=0
c = 'Y'
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congratulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
The two formula printing statements can also be reduced to a single one:
print(format(num1,'4d'))
print('+',num2)
could be
print( format(num1,'4d') + '+', num2 )
The variable sum could be removed, but it does make the code self-documenting, which is a good thing.

Closing a program when a condition is met

I am just starting out and can't figure this one out.
I am writing a program to do some simple calculations for me at school.
Different calculations will be accessible through input of simple numbers from 1 to X. Every number will call a function just for that calculation.
My problem is this:
I want that if the user enters an empty string when prompted for a number, the program will ask the user to re enter a number for a certain amount of times before closing. Here's my code:
def pick_procedure():
procedure = raw_input("> ")
if not procedure:
counter = 0
print "Enter a value. "
while counter <4:
counter = counter + 1
main()
if counter == 4:
break
def main():
print "\nStudy helper 1.0.\n"
print """Procedure list:
1.Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
pick_procedure()
main()
No matter how many times an empty string is entered, the program does not close.
How to do it correctly and cleaner?
As you say, you need to reorganise your code:
def pick_procedure(valid_choices):
print "Enter a value. "
for _ in range(4): # prompt for a choice up to 4 times
choice = raw_input("> ")
if choice in valid_choices:
return choice
return None # A valid choice was not entered
def main():
print "\nStudy helper 1.0.\n"
choice = 1
while choice:
print """Procedure list:
1. Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
choice = pick_procedure(["1", "2"])
if choice:
print "Doing choice", choice
main()
The following approach makes use of a while choice loop to keep prompting if a valid choice is entered. If no choice is entered 4 times, the pick_procedure() function returns None causing the while loop to exit cleanly. If a valid choice is entered, it returns that choice.
I also pass the list of valid responses to the function, that way the function can be used for other questions simply by passing a different list of valid responses.
You created a vicious circle.
First time that procedure is false, pick_procedure calls main and then main calls again pick_procedure. It continues recursively.
If you just want to finish the program when an event is fired, you can use sys.exit(0) and your problems are solved.

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

Loop and validation in number guessing game

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)

How to Go Back to an Original Prompt in Python

I am trying to create a basic calculator that takes the first number, takes the operation(+,-,*,/), and second number. If a person puts in a zero for the first number and/or the second number my program is supposed to go back to the number it was at and ask again for a number other than 0. So if a person puts in 0 for number 2 then my program will take the person back to number two. I am also supposed to do the same concept for the operation but have the person start over if they do not put in the operation available to use which includes the ones previously shown in parentheses. Below is the code I have so far. Any help would be appreciated. My class is currently on while loops and breaks among other things, but I am wondering if those two would be beneficial in my code.
#Programming Fundamentals Assignment Unit 5
#Create a basic calculator function
while True:
#Num1 will require user input
num1 = input ("Enter the first number\n")
#Operation will require user input
operation = raw_input("Enter the operation(+,-,*,/)\n")
#Num2 will require user input
num2 = input("Enter the second number\n")
#Now to define how the operation will be used
if operation == "+":
print num1+num2
elif operation == "-":
print num1-num2
elif operation == "*":
print num1*num2
elif operation == "/":
print num1/num2
else:
print "Please enter an operation"
#Exit will end the calculation from going into a loop
exit()
Put loops around your various inputs to ensure proper checking. So for the first number, you could have:
num1 = 0
while num1 == 0:
num1 = input ("Enter the first number\n")
This'll keep asking till they input something that isn't a 0.
For the second issue (starting over if they enter an invalid operation), you want to immediately check if the operation is valid and if it isn't, then you need to re-loop (which is just by skipping the remaining parts of the current loop).
So to easily check if it's valid:
operation not in ["+","-","*","/"]
which will return false if they enter invalid, and then the second part (skipping the rest of the loop) can easily be accomplished with the "continue" keyword.
if operation not in ["+","-","*","/"]:
continue
This will take you back to the beginning of the loop, asking for new number first number.
When you want to stop execution, you'll need to implement "break" which will break out of the inner most loop that it's a part of.

Categories