RUNNING YOUR FIRST PROGRAM
This course assumes you are familiar with some basic commands you would use in Terminal or PowerShell to navigate the folder structure. If you are not, please let me know. There is a cheat sheet here as well https://files.fosswire.com/2007/08/fwunixref.pdf
You can run python scripts in the python shell or scripts stored in a file. Use python shell only for quick tests.
Today we will start with python shell and move to files shortly after we learn a few commands.
Open your Terminal or PowerShell and type python (one more time make sure you are running python3), you should see something similar to the image below
You can run python scripts in the python shell or scripts stored in a file. Use python shell only for quick tests.
Today we will start with python shell and move to files shortly after we learn a few commands.
Open your Terminal or PowerShell and type python (one more time make sure you are running python3), you should see something similar to the image below
VARIABLES AND ASSIGNMENTS
variable type is not specified in Python, in other words Python is a dynamically-typed language, unlike statically-typed languages like Java and C/C++
sometimes that's refereed to as python being weakly-typed language and Java/C strongly-typed
sometimes that's refereed to as python being weakly-typed language and Java/C strongly-typed
>>> x=5 >>> x 5
Python figures out the type of the variable by it's assigned value:
>>> x=5 >>> type(x) <class 'int'> >>> y=4.3 >>> type(y) <class 'float'>
You will not be able to type just the variable name to echo it's value in the python script files, you can only do that in python shell, what you would do in file is print that variable, like so:
>>> x=5 >>> print(x) 5
You can delete a variable
>>> del x >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined
Naming identifiers (variable names) in Python have to subscribe to following set of rules:
- Must begin with _ or a lower or capital case letter (non-English alphabet characters are letters)
- Can contain _ ; lower or upper case letters and numbers
- Case sensitive
- Cannot be one of the Python reserved keywords: and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
valid variable names:
_myvar=10
MyVar=10
_my8peopleTeam=10
_myvar=10
MyVar=10
_my8peopleTeam=10
BOOLEANS
>>> a=True >>> b=False >>> a or b True >>> a and b False >>> not a False
NUMBERS
Integers and Floats are unlimited in size
>>> x=33333333333333333333333333333333333333333333333333333333333333333333333333333 >>> y=4444444444444444444444444444444444444444444444444444444444444444444 >>> z=x*y >>> print(z) 148148148148148148148148148148148148148148148148148148148148148148133333333331851851851851851851851851851851851851851851851851851851851851851852 >>> print(z*z*z) 3251536859218615048519026571152771427119849616420261139054005995020108723263632576334908296499517349997459736828735456993344510491286994868668423309454860498907686836356246507138139511253365848701925516232281661454046638939186099676675303561448966112889295330996291215769953767307829091123101153280455215160290606106792663719961387999796778946298836559466585378245088655184677132550932276583854087283442564649697708682619519382208
Integer types:
- Decimals (Base 10), ex: a = 345
- Octals (Base 8), ex: a=0o11 (prefix 0o identifies octal number)
- Hexadecimals (Base 16), ex: a=0xA10 (prefix 0x or 0X identifies hexadecimal number)
- Binary (Base 2), ex: a=0b11 (prefix 0b identifies binary number)
>>> a=0o11 >>> a 9 >>> a=0xA10 >>> a 2576 >>> a=0b11 >>> a 3
Unlike in previous versions of Python, in Python3 two integer division results in float:
>>> 10/2 5.0
Integer division // floors the result
>>> 20/7 2.857142857142857 >>> 20//7 2
Mod - remainder of a division %
>>> 10%3 1
STRINGS
Strings in Python are sequences of unicode characters, They can be identified by single (') or double (") or triple (''') quotes
There is no char type in Python - char is a string with a length of 1
There is no char type in Python - char is a string with a length of 1
>>> a='Hello' >>> a 'Hello' >>> a="Hello" >>> a 'Hello' >>> a='''Hello ... really ... long ... string''' >>> a 'Hello\nreally\nlong\nstring'
Echoing a string like above, will print all invisible characters along with their escape sequence, print will output the string with invisible characters rendered
>>> str=""" ... another ... very ... long ... string""" >>> print(str) another very long string
Here is the list of escape characters you can use in strings
\n - new line character \t - tab \r - carriage return \\ - single backslash \" - double quote \' - single quote
Multiplying string by number repeats the string that many times
>>> str="Hello" >>> str*6 'HelloHelloHelloHelloHelloHello'
use len() to get a length of a string
you can access a a character in a string using [] (we will cover longer than 1 character substrings later)
>>> a="Hello World" >>> len(a) 11 >>> a[0] 'H' >>> a[11] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range >>> a[-1] 'd' >>> a[-2] 'l'
Strings in Python are immutable, i.e. you cannot change value of a string once it has been created.
! Note that reassigning a variable is not the same as changing a string.
! Note that reassigning a variable is not the same as changing a string.
>>> a[2]="d" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
DATATYPE CONVERSION
Unlike Java, you cannot concatenate String to a number, use str() to convert number to a string
>>> "Hello"+2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str >>> >>> "Hello"+str(2) 'Hello2'
use int() to convert string to an integer
>>> int("10")+3 13
use float() to convert string to a floating point number
>>> float("5.3")+6 11.3
You can similarly use int() and float() to convert numbers to different types.
! Note that int conversion floors the number below
>>> float(5) 5.0 >>> int(4.5) 4 >>> int(4.9) 4
use bool() to convert strings and numbers to boolean types
>>> bool(5) True >>> bool(0) False >>> bool("True") True
RUNNING PYTHON SCRIPT FROM A FILE
1. Use Sublime text editor to create a file and put following code in it
print("Hello World from a python file")
2. Organize a folder for all your python work going forward, I created a python folder on my desktop and save your file in that folder, mine is going to python/lecture1/my_first_script.py
! Note to save yourself from headache avoid spaces and special characters in the faile names
! Note use .py extension for your file
! Note to save yourself from headache avoid spaces and special characters in the faile names
! Note use .py extension for your file
3. In your Terminal or PowerShell, navigate to the folder you created the file in (if you are not comfortable with the command line commands, please let me know ASAP)
4. Run the program using python command, you should see the print output in your terminal
COMMENTS
You can use # for a single line comment or triple quotes/triple double quotes for multi-line comments
#this is a comment print("Hello World from a python file") """and this is a comment written on multiple lines"""
BRANCHING/CONDITIONALS
Python uses indentation to define blocks of code, so indentation takes place of Java's curly braces
a=2 b=3 if a == b: print("equal") elif a > b: print("a is bigger") else: print("b is bigger")
You can put conditions in brackets if you want to:
a=2 b=3 if (a == b): print("equal") elif (a > b): print("a is bigger") else: print("b is bigger")
Following are some of the operators you can use in conditionals with numbers
>>> a=10 >>> b=20 >>> a==b False >>> a!=b True >>> a<>b File "<stdin>", line 1 a<>b ^ SyntaxError: invalid syntax >>> a>b False >>> a<b True >>> a>=b False >>> a<=b True
EXERCISES (for in class practice)
1. given 2 variables, swap the values of the 2 variables
2. given 2 variables, swap the values without using a third variable
3. Guess and then use Python to calculate the result:
a. 1+1+1-1*3
b. type of 12/4
c. type of 12//4
d. 15%4
2. given 2 variables, swap the values without using a third variable
3. Guess and then use Python to calculate the result:
a. 1+1+1-1*3
b. type of 12/4
c. type of 12//4
d. 15%4
HOMEWORK
SUBMIT THROUGH CANVAS:
- Set up a python locally, some instructions are here https://luckypants.weebly.com/python-setup.html (Links to an external site.)
- Create a file script that prints "Hello World" when executed, place it in a homework1 folder
- Create a GitHub account and git repo, use instructions here https://docs.github.com/en/github/getting-started-with-github/quickstart (Links to an external site.)
- There is additional tutorial I put together here
- Upload the python file in a homework1 folder to your github
- Submit your github repo link
QUESTIONS:
You do not need to submit the questions part for this homework assignment, all the questions below will be used to prepare you for the pop quiz next lecture.
1. Which of the following variable assignments are valid?
int x = 5
x = 6
_x=10.5
20people=20
my_33_cows=33
big$exit=105
2. Come up with 3 invalid variable names
3. What are the outputs of:
a. True and False or True
b. True and False or not True
c. True or False or not True
2. Come up with 3 invalid variable names
3. What are the outputs of:
a. True and False or True
b. True and False or not True
c. True or False or not True
4. What is the output of
|
bool("False")
|
5. Which of the following string declarations are valid?
my_string="foo"
my_string='bar'
my_string='foo\tbar'
my_string='''boo le an'''
6. I'm trying to print "Hello World" on 2 lines, such that output looks like this:
Hello
World
But my code just prints the new line character instead, see below, how could I change my code such that it prints the output as expected?
>>> the_string="Hello\nWorld" >>> the_string 'Hello\nWorld'
7. What is printed?
>>> str="hello" >>> len(str)
8. what is printed?
>>> str="Hello" >>> str[-1]
9. What is printed?
>>> str="Hello" >>> str[1]
10. I create digital arts. I want to make my art background using a very long string that consists of only "hello" words, that will look like the picture below. I do not want to type thousands of the letters to make it look like that, is there an easy 2-line way to print that background in the terminal?
11. What is the output?
>>> "Hello"+6
12. Given 2 variables A and B
write conditionals that would:
a. evaluate to True if A is smaller than B
b. evaluate to True if A is equal to B
c. evaluate to True if A is not equal to B
Try the above with different types for A and B - int, bool, string
13. What is the output
bool(5)
14. What is the output
bool(0)
15. I have my python script stored in a file named foo.py and I am in the terminal in the same directory the file is located in, how do I run the python script in the file?
PROGRAMS TO PREPARE FOR THE NEXT LECTURE (NOT MANDATORY):
You can add this program to your git repo
Program 1: Create a variable and assign a number to it in a range from 80 to 100 For the given number, calculate the letter grade 95% - 100% A+ 90% - 95% A 85% - 90% A- 80% - 85% B+