4Introduction to Programming with Python Module 1 - Target Audience People new to programming Students Career changes IT pros Anyone with the interest in coding, If going into the tech field you need to know at least one coding language. Python is very universal and is a very helpful first language to learn. All slides for the course are on the github page. Main tool being used is visual studio and the python tools. The course is a bit out f date and Visual Studio can now be downloaded from the microsoft store. Python is like a language and needs to be practiced. Why would you get into coding and how to do it. Coding is problem solving. You learn code because of what you want to do with coding. Most fields use tech in some way. Once you learn how to code in one programming language it will be easier to learn another programming language because they share many of the same basic concepts. You can do many things with python. Coding can be used to do a lot of different things. With this course you will learn enough how to solve real world problems and start learning more about python. Visual Studio Files with the ".py” extension contain my python code. These are the Most important files I work on. To run code/launch program use the start button or ctrl and F5 keys. Follow to prompt to shut down the program, or you can use the red square stop button. Using visual studio you can make changes to code while the code is still running. In the top right corner the stop button will only appear when the code is still running. print(‘Hello World’) Best Practices Avoid learning bad habits from the beginning. Develop the good habits now so it follows you in your code. - Comment your code Leaving comments on code will set reminders for yourself to tell you why you did something the way you did down the line. Sometimes code will be confusing so adding comments will also allow you to place notes explaining what the code is doing. Programs can never have too many comments. Self documenting code is helpful for everyone because it gives more information than you can expect. Anything in python that starts with the pound sign or hashtag (#) will be ignored when the code is run, this is how you can add comments. The comments are color coded in Visual Studio in green. Color coding is helpful in identifying mistakes in code. In the top right corner is the quick launch, Here you can look up tools and change information about the tool. Here you can make changes to things like the color coding and the font, you can change default colors here as well. Visual Studio offers a lot of customization. Module 2 Python allows you to use single and double quotes to display text. But is you want to print “It’s a beautiful day in the neighborhood” You would need to use double quotes to enclose the string because of the use of a single quote in the string. If a double quote was used in the string you would use single quotes to enclose it. Stick with using one of the other when writing code to avoid any confusion. When you want to use two lines for one string or words you can use “\n” to tell it to do so. It must be a back slash to work. How to print a string that contains a single quote and a double quote - You can use a plus sign to add two strings and make them appear as a single string. print(‘here is a double quote “‘ + “here is a single quote’”) There are multiple ways to do things. The way we did this with the use of a backslash you can alternatively do it this way” print(“or you can just do this \” does that work”) There are always multiple solutions to the same problem. Using triple quotes to do this would probably not be the best because it isn’t common. Everything you are learning here is going to be consistent with other languages. Always stick with the most conventional way of doing things to avoid initial confusing. There is always more than one way of doing things and if the code works then it works, if it’s clean and easy to read it’s okay. Most of the time differences won't make a difference or wont make a difference in a way that matters. Always choose the option that makes the most sense to you, it’s your code, you do whatever you want. The easiest way to find the answers to things is to just try the options. If i want “\n” in the string this is how you get this to work print(“But what if i want \\news”) Displaying Text You will make mistakes in code, that’s just how things work. Anything can go wrong, there are multiple ways to solve things. You can’t learn if you don’t practice. If you get really stuck walk away and come back, getting other people to look at code can be extremely helpful because they haven’t been looking at it for 24 hours straight. It’s simply just a fresh ste of eyes looking at the documents. The more mistakes you make the better you get at identifying mistakes. These lines of code have mistakes in them, here are the mistakes made. print(Hickory Dickory Dock) - There are no commas in this, VS will not identify the string print(‘it’s a small world’) - The use of a single quote would need double quotes to enclose print(“hi there’) - Mixing the double and single quotes in the same string print(“Hello World!”) - print is misspelled. In Visual studio these mistakes could also be identified by the color coding within the program. You can use “print” to display text and to run a program that can display text. Displaying text can be used to run a program that can display information to a user. This class is to help you become a developer and to become comfortable with the python language. We are walking so we can run. Module 3 Expecting input and intro to Variables Being able to input information is important because users need to be able to give specific information when asked for it. How do we get input from the user, this leads us to ask How do we ask for input from the user. Input is the command you will use to get input from the user. name = input(”What is you name”) This prompts me with the question but didn’t do anything past this. If i wanted to have the user courser in the next line I would use a print statement to ask the question then leave the input blank. Where do we store values? Name is a variable that can store the information inputted. That is what a variable will allow you to do. You won't be able to write a program without variable use. Name=input, Input is going to prompt the user for a values and whatever it get it will put into the placeholder. name = input(”What is you name”) Joshua print(name) These two lines of code are equal to print(“Joshua”) name=input(“What is your name?”) print(“name”) name=”Mary” print(name) The equal size is what tells python to take what it is was given and place it where is specified. Telling it what box to put what is inputted. Variable Rules and working with variables Variable Names - Can not contain spaces - Are case sensitive firstName and firstname would be two different variables - Cannot start with a number Guidelines - Should be descriptive but not too long (favoriteSign not yourFavoriteSigninTheHoroscope) - Use a casing “scheme” cameCasing or PascalCasing Treat everything like it’s case sensitive, because if something isn’t case sensitive you’re fine but if it is then at least you’ve already treated it as such. If something needs to be passed along different languages this will avoid any confusing when going between the two. Variable names can not start with a number, it’s just one of the rules. Systems will expect different things with numbers. At some point you will have a large number of variables and sometimes you’ll forget where you put a certain variable. Always add comments but if you need to explain a line of code, go back and read the code. Make sure you are writing code that can be understood instead. Using meaningful names will avoid confusion. Context is always king, if everyone knows what you are referring to then it’s fine. If it has to be defined than maybething something else is better. Camel casing is usually the way to go. You can combine variables and string variables with the + symbol. firstName-input(“what si your name?’) lastName+input(“what is your last name?”) print(“Hello” +firstName +lastName) Demo animal=input(“what si your favorite animal?”) building=input(“name a famous building”) color=input(“What is your favorite color?”) print(“Hickory Dickory Dock!”) print(“The “+color+” “+animal+” ran up the “+building) VS will always look to the right of an equals sign because it knows that means something is going to be inputted. Visual studio tips Intelesense - Great for lazy coders, helps write code What do these functions do message=’Hello World’ print(messege.find(‘world’)) - telling program to find world print(messege.count(‘o’)) - count how many o print(messege.capitalize()) - Capitalize H in Hello we already had that print(messege.replace(‘Hello”,”hi”)) - Replaces Hello with Hi Running the program 6 - Six characters before it found World 2 - Number of Os in the string Hello World - Result of message = Hello World Hi World - Hello replaced with Hi Press and key to continue… Sometimes Intellisense won't appear, sometimes you need to give python a hint. If you have a variable name and hit the dot to bring up the functions, how can python know what you are working with, you may want to declare the variables beforehand. Each line of code has a mistake Message = hel;lo world - missing quotes 23message = ‘hello world’ - name start with number New Message = ‘hi world’ - name has space in it print(massage.upper) - forgot the parentheses print(masage.lower()) - misspelled message print(message.count()) - forgot to pass value i want to look for in count Go to the internet to look for answers, it’s always okay to look up questions. There will always be someone who has the same issue you dop and also looked for the answer and found it. Or you will get the answer of a question that others after you will have. Solutions are mostly suggested solutions unless stated otherwise. If the code works and it’s clear to read. Module 4 Storing Numbers It’s important to be able to store numbers in my variables Example age=42 print(age) When you store a value with no quotes you are storing a numeric value. width=20 height=5 area=width*hreight * Is the multiplication in python +Addition -subtraction / division **exponent %modulo Math rules - Order of operations () Parenthesis ** exponent */ multiplication and division + - addition and subtraction Formatting Numbers Sometimes you will need to format the numbers when you display the output. F stands for float and D stands for Decimal. Float is used to golf value without decimal places. D is used for whole numbers usually. When you need to figure stuff just copy and paste the error message and you can usually find the answer that way. You aren’t the first person to get this error message. When numbers are decimal values and not a float those are the cases when you don't do math with it you have just given the program a number. When you are able to specify a specific width when displaying information it helps makes the information cleaner and neater. Easier to read. You can also use 0’s to fill in the extras space. print(“my favorite number is {0:d} “.format(42)) - .format is recommended because it carries to other languages print(“may favorite number is %d” % 42) print(“My favorite number is %06d !” % 42) To show multiple numbers with .format Here is an example with multiple numbers print("here are three numbers! the first is {0:d} the second is {1:4d} the third is {2:d}".format(7,8,9)) Sometimes commands are too long to fit on the line. ● You can use a “\” to indicate a command continues on the next line. If you only type in a back slash it will thing the backslash is part of the string. To specify wanting it to continue on the next line use the backslash after a + symbol. When you have a blank space after jumping to a new line of code is called an indentation. Do not delete the space, this shows that the command continues from the previous line. Module 5 Working with dates and time When collecting information, dates are an important piece of information. Python has the ability to understand and manipulate dates and information regarding dates. You can pull in today’s date using the “datetime” class. You can create different types of web apps, all of these will require a library to be able to communicate with the database. There are alot of libraries that contain functionality that help with localization. ● The datetime class allows us to get the current date and time. Using the import statement we can bring up today’s date. Import datetime today=datetime.date print(today) When working in python the color coding will help identify different things when working with code. Variable names cant use reserved terms since python already sees them differently. You can also access different parts of the date. You can see year, month, day listed in the print statements. These are the properties of the date and are used to give you specific information. import datetime currentDate=datetime.date.today() print(currentDate) print(currentDate.year) print(currentDate.month) print(currentDate.day) When you specify a variable in a strongly typed language you must define that and stick with it. With weakly typed languages you don’t have to do this specifically because the language is very forgiving when compared to others. Date Formats - What date does 2/5/2014 represent Depending on where you are this could represent a large number of different dates. When talking about dates there is a lot of information that can come from numbers, you need to makes things clear so you can get the correct information to be able to display something other than the default output for the user. Date information looks difficult but it’s just going to include more code. In python we use strftime to format dates Import datetime currentdate+datetime.date.today() #strftime allows you to specify the date format print(currentDate.strftime(‘%d %b, %y’)) These things seem like constants but memorizing this isn't exactly what is going to make you a developer. You might write a line a code at some point that you will never never need to know how to write ever again. print(currentDate.strftime(‘%d %b, %y’)) will also do the same thing as before. To Display something like “Please Attend out event sunday, july 20 in the year 1997” Import datetime currentDate=datetime. currentDate=datetime.date.today() print(currentDtae.strftime(“please attend out event on %A, %B %d in the year %Y’)) This will print “please attend out event on wednesday March 8th in the year 2023” If we want to work with other languages like spanish in my case. When localizing a date you can always find answers online and it’s easier again than memorizing information like this. Most of what is here is just how people share code and is more of just one way of doing things. You can t use input when asking for this because it will always display a string, this is where strptime will allow you to do the conversion. Import datetime birthday=input(“what is your birthday?”) datetime=datetime.datetime.strptime(birthday, %m/%d/%y”),date() print(“your birthday month is”+birthdate.strftime(‘%B’)) Ctrl+k Ctrl+C COmment Ctrl+K Ctrl+U uncomment Sometimes a user will input a format differently then what you have specified in the program toi avoid this always ask for a specific way for the information to be entered so it can match what you formatted. Remember the use of capital letters and why they are there. Even with the information given to the user, error coding is still best practice. Dates can be stored as strings, you can create a countdown to say how many days until a big event. nextBirthday=\ datetime.datetime.strptime(‘12/20/2014’,’%m/%d/%Y’).date() currentDate=datetime,date,today() difference=nextBirthday-currentDate print(difference.days) “Dateutil” is a useful tool for dates and can be downloaded. If you look for something most of the time you will find it. Working with time Datetime can store times Import datetime currentTime=datetime.datetime.now() print(currentTime) print(currentTime.hour) print(currentTime.minute) print(currentTime.second) Just like with dates you can use strftime() to format the way a time is displayed import datetime currentTime=datetime.datetime.now() print(datetime.datetime.strftime(currentTime, ‘%H:%M’)) Module 7 Making decisions with code If your code is going to solve problems, it has to be able to make decisions as well. If statement - answerer=input(“Would you like express shipping”) things in parentheses are the variable If answer==”yes”: print(“That will be en extra $10”) == is equal to != is not equal to < is less than \ > is greater than <= is less than or equal to >= is greater than or equal to Regardless of what the user inputs statements that aren’t indented will always be shown. Print statements being indented are important syntax for python. Always pay attention to the capitalization. If you have the program changing an input to uppercase with “input.upper()” make sure that what is being changed is also capitalized in the code unless you have already done so. Almost every if statement can be written two ways: If answer==”yes” If not answer==”no” If total < 100: If not total >= 100: Being able to figure out which is best for your use is mainly narrowed down by preference. A boolean variable can be used to remember if a condition is true or false. deposit=input(“how much would you like to deposit?”) If float(deposit)>100: freeToaster=True If freeToaster: print(“enjoy your toaster”) A boolean Variable is one that holds the value true or false, you can code an else statement to only be executed if the condition is not true. Module 8: Complex decisions with code Sometimes there are multiple conditions that affect the outcome of a decision. The “elif” allows you to check for different variables Country-input(“Where are you from?”) if country==”Canada”: print(“hello”) elif country==”Germany”: print(Guten Tag”) elif country==”France”: print(“bonjour”) elif stands for else if. What would happen if someone entered something that was outside of the bounds. Country-input(“Where are you from?”) if country==”Canada”: print(“hello”) elif country==”Germany”: print(Guten Tag”) elif country==”France”: print(“bonjour”) else: print(“Aloha/Ciao/G’day”) In this case if someone enters something different that what you have set without the else statement it will just exit out. You would need to add ana else statement and using this you can add an error message so the user knows they entereds elif demo team=input(“enter your favorite team? “) If team==”Spartans”: print(“R.R.C”) Elif team==”SVC cadets”: print(“congratulations”) else: print(“We love drum corps”) Combining conditions When using the “and” statement both options must be true if not it will not execute Sometimes we want to do something if either condition is true. In this case we will or statements to know if one side or the other is true. When looking for one side or the other to be ture we want to use an or statement. In english you will be asked something an you want to use or instead of and because of how english vs logic works. Demo for or statements team=input(What is your favorite hockey team: ”).upper() sport=input(“Enter your favorite sport: “).upper() If sport==”HOCKEY” and team==”RANGERS”: print(“I Miss good players”) Elif team==”LEAFS” or team==”SENATORS”: print(“Good Luck getting the stanley cup this year) else: Print(“I don’t know what to put here”) You can combine multiple “and/or” is a single if statements Example: If month==”Sep” or month==”Apr”\ or month==”Jun” or moth==”Nov”: print(“There are 30 days this month”) If favMovie==”Star Wars”\ and favBook==”lord of the rings”\ and favEvent==”ComiCon”: print(“You and I should hang out”) Demo For combining and/or If country==”CANADA” and\ pet==”MOOSE” or pet==”BEAVER”: print(“Do you play hockey too?”) There is an order of operations for “and”/”or”. “And are evaluated first. Because of this it will run the first like first because of the order of operations If sport==”HOCKEY” (and team==”SENATORS” or team==”LEAFS”): print(“Good luck getting the cup this year”) The problem here is that the and statement is overriding everything, If we add Parenthesis around the and statement so we need to surround it in parenthesis. Now we a breaking it down into two separate seatments and it will be looked at first. When in doubt always use parenthesis. Write in your code as simple as possible. sportIsHockey=false If sport==”HOCKEY”: sportIsHockey=True teamIsCorrect=True print(“good luck getting the cup this year”) When troubleshooting always try every option. The best way to write is to write as simple as possible. It has to be whatever makes the most sense to you.If it’s outputting the way you want it to then it works. Nesting If statements monday=True FreshCoffee=False If monday: If not FreshCoffee: print(“go buy coffee!”) print(“i hate mondays”) print(“now you can start work”) You have to very careful with how the code is indented, because tat determines which code goes with which codes goes with which if statement Demo for nested if statements team=input(“Enter your favorite hockey team:”) sport=input(“Enter your favorite sport”) print(“Go hockey”) If team==”SENATORS”: print(“Good luck getting the cup this year”) print(“We love hockey!!”) Tabs don't always affect the syntax in other languages but tabs will always affect readability.