How can I refactor my code using functions? - python

It is a simple maze game I did for school. I have tried different solutions but still cant figure out how. I don't necessarily need a full solution; any tips would help.
x = 1
y = 1
valid_selection = True
while True:
if x == 1 and y == 1:
if valid_selection == True:
print("You can travel: (N)orth.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 1 and y == 2:
if valid_selection == True:
print("You can travel: (N)orth or (E)ast or (S)outh.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
elif choice.lower() == "e":
x += 1
elif choice.lower() == "s":
y -= 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 3 and y == 1:
print("Victory!")
break

You could have your function recieving x and y as parameters, removing the While True and replacing it with its creation, like def MyFunc(x,y), putting the valid_selection variable inside it and removing x and y attributions. And then you call it in the end of the code passing 1 and 1 as your desired parameters, like MyFunc(1,1)

There are many ways to create a function.
First, you need to abstract what your program do. The name of the function have to express this.
Second, you need to know what are the inputs. In your case the input must be x and y, or the proper names to these input.
The answer which your function will return is a important thing to know. The user will see a print or the user of the function will use a number, string or other object to feed other function.
I hope this not confusing.

Related

Python loop continues without stop

import random
given_number = round(float(input("Enter a number;\n")))
loop = True
while loop:
def Possibility(maximum):
count = 0
while count == 0:
x = random.randint(0, maximum)
if x:
print("X is True")
else:
print("X is false")
count += 1
print("Possibility calculated")
answer = input("Do you want to try again? Y/N")
if answer == "N":
loop = False
Possibility(given_number)
When I run the code even if I type N to answer as input program still continues to run any idea why this is happening?
import random
given_number = round(float(input("Enter a number;\n")))
def Possibility(maximum):
count = 0
while count == 0:
x = random.randint(0, maximum)
print(x)
if x:
print("X is True")
return True
else:
print("X is false")
count += 1
print("Possibility calculated")
answer = input("Do you want to try again? Y/N")
if answer == "N":
return False
while Possibility(given_number):
given_number = round(float(input("Enter a number;\n")))
Possibility(given_number)
the issue is, is that the function possibility was in a while loop, which means that the function would not be executed until it ended, which it couldnt, as the end condition was in the function.
this should fix your issue, by making it loop the function itself rather than the definition.
to break out of the loop, you would use the return function, which is an easy way to end the loop in this case.

What makes this while loop an infinite while loop until I use the break command in Python?

I'm trying to understand what's wrong with the following code.
This version, using boolean values, works fine with or without the break:
print("Enter your names for the contest exactly the way you want it spelled.")
list_done = False
while list_done == False:
name = input("Enter your first name: ")
others_there = input("Are there other participants? Type Y or N: ").lower()
if others_there == "y":
list_done == False
print("Call the next participant!")
elif others_there == "n":
list_done = True
print("We're done. We'll contact you soon.")
break
However, when I try using integer values for list_done, the break is required to exit the loop, or else it runs indefinitely. Why is that?
print("Enter your names for the contest exactly the way you want it spelled.")
list_done = 0
while list_done == 0:
name = input("Enter your first name: ")
others_there = input("Are there other participants? Type Y or N: ").lower()
if others_there == "y":
list_done == 0
print("Call the next participant!")
elif others_there == "n":
list_done == 1
print("We're done. We'll contact you soon.")
#break
You confused assignment and comparison. Instruction list_done = False assigns the False value to list_done. When you use list_done == False you just calculate if list_done is equal to False.
So the mistake is about lines with list_done == False, list_done == True, list_done == 0. If you fix == with =, everything will work as you desire.

Asterisk on jupyter(python)

I was making code on python but it showed an asterisk where the number goes on the cell, I tried making a print program to see if it was the code but it still didn't work. Please help, this is the code.
Items = ""
Total = 0
def adding_report(report):
while True:
X = input("please input integer to add or Q to quit")
if X.isdigit() == "True":
X = int(X)
Total = Total + X
if report == "A":
Items = Items + X
elif X == "Q":
print("Your result is")
if report == "A":
print("Items")
print(Items)
print("total")
print(Total)
break
else:
print("invalid input.")
adding_report("T")
You are stuck in an infinite loop.
Moreover, you cannot compare to the string "True", but rather to True only:
if X.isdigit() == True:
Instead of:
if X.isdigit() == "True":
You can also skip the comparison to True altogether
if X.isdigit():

Can you use input to accept both an integer and a string?

I have a small script I have been working on for practice with Python. I am having trouble getting my input to accept a number for an if statement and also accept string as lower case.
I want to tell my script for any input if the user types '99' then close the program. So far it works where I have int(input()), but it won't work where I have input(). What am I doing wrong or is it not something I can do?
Right now my if statement looks like:
if choice1 == 99:
break
Should I just make 99 into a string by quoting it?
Maybe something like this:
if choice1 == "99":
break
Here is the script:
global flip
flip = True
global prun
prun = False
def note_finder(word):
prun = True
while prun == True:
print ('\n','\n','Type one of the following keywords: ','\n','\n', keywords,)
choice2 = input('--> ').lower()
if choice2 == 'exit':
print ('Exiting Function')
prun = False
start_over(input)
elif choice2 == 99: # this is where the scrip doesnt work
break # for some reason it skips this elif
elif choice2 in notes:
print (notes[choice2],'\n')
else:
print ('\n',"Not a Keyword",'\n')
def start_over(word):
flip = True
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
So input() always returns a string. You can see the docs here:
https://docs.python.org/3/library/functions.html#input
What you could do is something like this:
choice2 = input('--> ')
if choice2.isnumeric() and (int(choice2) == 99):
break
this avoids you to type check and catch errors that aren't important.
see below for how isnumeric works with different numeric types:
In [12]: a='1'
In [13]: a.isnumeric()
Out[13]: True
In [14]: a='1.0'
In [15]: a.isnumeric()
Out[15]: False
In [16]: a='a'
In [17]: a.isnumeric()
Out[17]: False

Program stays stuck in while loop but doesn't run program?

this is a crabs simulator. Im having trouble with my while loop. Where it says
while val == True:
Is where the problem happens. It stays in the while loop but nothing happens. If you find anything, I will be most grateful.
Here is the full code. (I have tried to validate everything)
import time
import random
control1 = False
control2 = True
x = True
val = True
z = True
def throw(n):
for i in range(1,n+1):
dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2
time.sleep(2)
return n
while z == True:
if x == True:
while control1 == False:
try:
amount_1 = int(raw_input("Welcome to crabs.\nHow many times would you like to roll:"))
control1 = True
except ValueError:
print ("Enter a valid number.")
throw(amount_1)
x = False
else:
while val == True:
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
val = False
while control2 == True:
try:
amount_2 = int(raw_input("How many times would you like to roll:"))
control2 = False
except ValueError:
print ("Enter a valid number.")
throw(amount_2)
z = True
elif roll_again == "2":
val = False
exit()
else:
val = True
After your first run through the program x and val are both False, but z is still True. As a result, the outer loop just keeps on rolling.
Put this line:
print z, x, val
Underneath that while statement.
You'll see that after you respond to the "Would you like to roll again: " question with "2", both x and val are false. That means that it'll go through every part of your if..else statement and just keep looping back infinitely.
It's stuck in an endless loop after the else branch (of if x) is executed, because you set the value to False. In the next iteration you then say while val == True and since this statement is not False and there is no other statement to consider, you run in an endless loop.
To see what I mean simply add a print statment here:
else:
print val
while val == True:
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
Now, I don't know if you need all those booleans for your actual program, but if I'd to make it work, I'd start eliminating the booleans I don't need. I think you have a too complex structure.
Edit:
Here's a suggestion to make the program simpler.
import time
import random
x = True
z = True
def throw(n):
for i in range(1,n+1):
dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2
time.sleep(2)
return n
def ask(x):
if x:
print "Welcome to crabs."
try:
amount = int(raw_input("How many times would you like to roll:"))
except ValueError:
print ("Enter a valid number.")
throw(amount)
while z:
ask(x)
x = False
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
continue
else:
break

Categories