Why is this function exiting early? - python-3.x

I have what looks to me like a completely normal function. However, for some reason, the function is exiting without executing any of the if/else statements.
def MainFunction():
shapeToSolve = input("What kind of shape are you calculating?")
print(shapeToSolve, "wtf")
if shapeToSolve == "Square":
solveSquare()
elif shapeToSolve == "Circle":
solveCircle()
elif shapeToSolve == "Triangle":
solveTriangle()
Notice the print(shapeToSolve, "wtf") block. I did this to see what's being returned from the function. Despite the fact that I have no other operation happening on shapeToSolve() anywhere else in the program, for some reason this prints "g wtf" to the console.
How is shapeToSolve() getting the letter "g" passed in as its input when the console isn't even allowing input before exiting the function?
Aside from the other functions that are called, this is the only other code in the program:
print("Hello! Welcome to the Geometry Calculator.")
MainFunction()

There isn't any problem. Are you sure you didn't just accidentally type "g" as your input?

Related

I am having trouble understanding the flow of programming

I am new to programming and one of the problems I have run across is structuring. I am learning Python (3) and am practicing by making a few practical programs. An issue I am running in to is how to get the right flow to the program. I find that as I write a function, I realize that I need it to lead to another function, so I end up calling the next function at the end of the function I'm writing. Then I realize that Python will read the code line-by-line, so I have to have the function I will be calling above the one I am actively writing. The effect is that I end up writing the program in reverse. For example:
#Replaces letters in chosen word with X's
def display_word():
selected_word = list(selected_word)
for x in selected_word:
x = "X"
print (x)
#Function that will display the welcome message when program launches
def start_screen():
user_input = input("Hello and welcome to Hang Man! If you would like to
start a game, please enter 'YES' now!")
user_input = user_input.upper()
if user_input == "YES":
display_word()
else:
print ("You're no fun!")
start_screen()
This is a little tid-bit that I have written in a hang-man program I am practicing with. I started out writing the start_screen function, then realized that I will need to call the display_word function within the start_screen function, but to do that, I will have to define the function before it is called, so I have to write the display_word function above the start_screen function, which effectively has me moving in reverse. My question is whether this is the way things go or if there is a better way to do things. It seems like writing the code in reverse is inefficient, but I am unsure if that is just my inexperience talking.
All functions in Python must be defined before they are used. That does not mean that the function has to be listed above the one it is called from.
The functions can be defined in any order. You just have to make sure the executable portions that start your program, like start_screen(), are called below where the function is defined.
In the case of your hangman program, you are perfectly safe to switch the order of the two functions.
In general, if you have all of your executable code following all of your function definitions, you are good to go to keep them in any order you choose!
Example:
This is perfectly ok. You can even switch them!
def fn1():
print('I am function 1')
fn2()
def fn2():
print ('I am function 2')
fn1()
This is bad!
fn1() #not defined yet!
def fn1():
print('I am function 1')
def fn2():
print ('I am function 2')
This is also bad!
def fn1():
print('I am function 1')
fn2() #not defined yet!
fn1()
def fn2():
print ('I am function 2')

return outside function, I don't believe it's indentation (return must be inside a function! can not test with statements)

Update (return must be inside a function! can not test with statements)
Keep getting
File "python", line 49
SyntaxError: 'return' outside function
bank=100
while True:
print('How much would you like to bet?')
bet=input()
bet=int(bet)
if bet not in range(1,bank+1):
print('please enter an amount you have!')
else:
return bet
Not exactly sure what is going on wrong and sorry for poor formatting but doing my best.
Update:
A run of it using repl.it
and the code itself
https://repl.it/Hl0p/0
You need to define a function to return values. Only a function can return values. Your code is a collection of statements and not a function. See how to write function over here.
https://docs.python.org/3/tutorial/controlflow.html#defining-functions

With using String instead of Try/Except prevent crashing- How to?

I am writing a code for the wind chill index for an assignment for college.
The prof wants us to prevent the code from crashing upon user input of blank or letters, without using Try/Except Blocks. (He refers to string methods only).
Instead of crashing it should out put an error message eg. ("invalid input, digits only")
I tried utilizing the string.isdigit and string.isnumeric, but it won't accept the negative degrees as integers.
Any suggestions? (code below)
Would another "if" statement work?
Replace the punctuation:
if temperature.replace('-','').replace('.','').isnumeric():
Use an infinite loop and check that everything seems right.
Whenever there's an error, use the continue statement. And when all checks and conversions are done, use the break statement.
import re
import sys
while True:
print("Temperature")
s = sys.stdin.readline().rstrip('\n')
if re.match("^-?[0-9]+(\\.[0-9]+)?$", s) is None:
print("Doesn't look like a number")
continue
if '.' in s:
print("Number will be truncated to integer.")
temp = int(float(s))
if not (-50 <= temp <= 5):
print("Out of range")
continue
break

Pass statement doesnt alter my program

for i in [1,2,3,4,5]:
if i==3:
pass
print ("Pass when value is",i)
print (i)
for i in [1,2,3,4,5]:
if i==3:
print ("Pass when value is",i)
print (i)
I get the same output for both the codes.
Then what is the use of pass statement here.
pass is used when the syntax requires a statement but you don't want to do anything.
Example:
def foo(bar):
pass # does nothing
pass is a "do nothing" statement. In this case, it's indeed pointless. It was created to come in place on logically empty blocks, which Python does not allow (unlike c or java, for example). E.g.:
try:
doSomething()
catch ExpectedException:
# We expect this, do nothing
pass
catch OtherException:
# Oh no, something bad happened
handleOtherException()

Python error cannot delete function call

In python I tried calling a function in a function - when I finished it says "error cannot delete function call". Why is this happening? Inside the nested function there is a delete used, but that is for a different variable! I tried a few things like printing the function instead but got the same answer.
Here is the code which isn't working:
def BracketStart():
Round2Normal=[]
Round1Loser=[]
if len(List) % 2 == 0:
print("The Current Match Is %s VS %s" %(min(List),max(List)))
starting=input("Start Match? --> ")
if starting=="Yes":
Winner1=input("Who Won? --> ")
if Winner1==min(List):
Round2Normal.append(min(List))
Round1Loser.append(max(List))
del min(List)
del max(List)
min(List) is a function call -- so, yes, you are trying to delete a function call. Perhaps
List.remove(min(List))
is the sort of thing you want to do (though calling a list "List" isn't a good choice and removing elements from a list is a relatively expensive operation).

Resources