Week 2
disclaimer: I already know python syntax, so any notes I make in this blog will be mainly to do with Maya Python Modules, or more complex Syntax notes.
This Week I got reacquainted with Python my making a version of an outdated sorting algorithm. in doing so I demonstrated the use of subroutines (functions) along with for loops, if statements ( > and == ) along with external modules like time and random. This was not yet covered by the session, but I am sure it will.
Python scripts run downwards, they carry out instructions and subroutines based on the order that commands are demonstrated line by line.
This command pushes text to the command prompt.
print('hello world')
user inputs for running python scripts can be gathered from the use with:
VARIABLE = input("prompt:")
this makes VARIABLE equal to the input string from the user. the user would receive "prompt: " when python runs the program.
python requires you to compile code before running rather than running live. this is because is a high running programming language built on more code.
An example of how this could be used in a program is:
name = input('What is your name? ')
print('Hi there, ' + name)
this program will print out whatever you say your name is.
def add(var1, var2):
return var1 + var2
output = add(2,6)
this program uses a function to add two numbers together. this is rather overcomplicated but it does demonstrate how you can use functions to simplify long code.
the same code can be written in one line for the same result:
print(2 + 6)
the upside to using functions is that the same add function can be used over and over again.
Streamlining potential errors
userInput = True
print('⚠ type each number to sort, pressing enter each time. Then leave field blank and press enter to continue. ⚠')
while userInput == True:
usrAns = input('>>>')
if usrAns == '':
userInput = False
else:
try: #trys to set the input number as an array item, this try statement will catch any failed attempt to convert the string input by the user into an int
usrInt = int(usrAns)
sortArray.append(usrInt)
if len(usrAns) > longNum:
longNum = len(usrAns)
except:
print('ERROR')
this extract from my attached bubble-sort program demonstrates the 'try' exception. this ignores any type errors when the user inputs texts and means the program wont crash due to this error. this is an important part to a program that depends on user input and can mean the difference between success and failure.
Leave a comment
Log in with itch.io to leave a comment.