├── .DS_Store ├── Flyer Version 1.8.pdf ├── Git Extensions - User Manual.pdf ├── Python 101 - Flyer.png ├── Python-Course-Content.md ├── Python-Installation-Guide.md ├── Python-Syllabus.md ├── README.md ├── Week 1 ├── Py101 - Week1-Section1.pdf └── README.md ├── Week 2 ├── Hands_on_Sec_2.py ├── Programming_Concepts_Week_2.md ├── Py101 - Week2 - Section1.pdf ├── exercise_#1.md └── hands_on_week2.py ├── Week 3 ├── Hands_on_conditions.py ├── Hands_on_iteration.py ├── Hands_on_week3_section2.py ├── Programming_Concepts_Week_3.md ├── Py101 - Week3 - Section1.pdf ├── exercise_#2_conditions.md └── exercise_#2_iteration.md ├── Week 4 ├── Functions_Practical_Programming.py ├── GPA_calculation_program_function.py ├── Programming_Concepts_Week_4.md ├── Py101 - Week4.pdf ├── convert_to_celcius.py ├── exercise_#3_Functions.md ├── exercise_#3_Lists.md ├── first_function.py ├── functions_intro_comp_science_using_python.py ├── hands-on02-26.py ├── hands_on_2-25.py ├── list_example_byte_of_python.py ├── list_example_novice_to_professional.py └── save.py └── Week 5 ├── .DS_Store ├── Hands0n2.py ├── Programming Concepts.md └── hands0n1.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/.DS_Store -------------------------------------------------------------------------------- /Flyer Version 1.8.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Flyer Version 1.8.pdf -------------------------------------------------------------------------------- /Git Extensions - User Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Git Extensions - User Manual.pdf -------------------------------------------------------------------------------- /Python 101 - Flyer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Python 101 - Flyer.png -------------------------------------------------------------------------------- /Python-Course-Content.md: -------------------------------------------------------------------------------- 1 | # Python Course Outline 2 | ======================= 3 | 4 | ## Week 1 (4th && 6th Feb) 5 | - General structure of the course 6 | - Introduction to Version Control System 7 | - How to use GitHub 8 | - How to use GitExtensions 9 | - Introductory Videos of Python 10 | - Why Python is Good for beginners? 11 | - What can I do with Python? 12 | 13 | ## Week 2 (11th && 13th Feb) 14 | - Python Syntax 15 | - Variables 16 | - Booleans 17 | - Whitespace and Indentation 18 | - Comments 19 | - Math 20 | - Python Built-in Data Types Introduction 21 | - Numeric Types 22 | - String Fundamentals 23 | 24 | ## Week 3 (18th && 20th Feb) 25 | - Control Statements 26 | - Comparison 27 | - If-Elif-Else 28 | - Iteration using For, while loops 29 | 30 | ## Week 4 (25th && 27th Feb) 31 | - Data Types (Cont'd) 32 | - Lists 33 | - Functions 34 | - List Comprehension 35 | 36 | ## Week 5 (4th && 6th March) 37 | - Data Types (Cont'd) 38 | - Dictionaries 39 | - Tuples 40 | - sets 41 | - Modules 42 | 43 | ## week 6 (11th && 13th March) 44 | - Classes 45 | - Future Python (What to do Further) 46 | 47 | > Last Class -------------------------------------------------------------------------------- /Python-Installation-Guide.md: -------------------------------------------------------------------------------- 1 | # Python Interpreter 3.4 Installation Guide 2 | 3 | Since we will use very basic elements of Python, Python Idle interpreter will be enough for us. For those of you who wants to go deep on Python after this class I would recommend other platforms that you can work on and make your job easier, but as I said, Python Idle will be enough. 4 | 5 | To install the Python interpreter [Click Here](https://www.python.org/downloads/release/python-342/) and choose according to your system. __(Note that x86 stands for 32bit)__ 6 | 7 | After you download and install the file from the website, you will be able to reach the following: 8 | 9 | * Python Interpreter 10 | * Help Files(documentation) 11 | * Command-line access 12 | * Integrated DeveLopment Environment(IDLE) application 13 | * Uninstaller 14 | -------------------------------------------------------------------------------- /Python-Syllabus.md: -------------------------------------------------------------------------------- 1 | # Intro to Python Programming 2 | 3 | [Enes Kemal Ergin](https://github.com/eneskemalergin) 4 | 5 | --- 6 | 7 | ## Course Description 8 | 9 | The purpose of this course is showing how to program using Python Language. Throughout this 6-week course we will learn version control system's logic, how to use GitExtensions and GitHub to learn how to be efficient developer, Python's built-in data types, Python's syntax, control structures, functions, modules, and classes. During the course period we will complete so many hands-on exercises together and weekly challenges. After completing this introductory Python course, you will be ready to go to next step to learn deeper concepts in Python Programming and it's packages, such as;django for web development, pandas for Data science, Matplotlib for Matlab applications, pygame for game development, scipy for scientific applications, numpy for huge numerical applications, and more. 10 | 11 | --- 12 | 13 | ## Course Content 14 | 15 | * Week 1: VCS, GitHub, GitExtensions, Intro to Python 16 | * Week 2: Numeric data types, strings, comparison 17 | * Week 3: Contol structures, comprehension 18 | * Week 4: Lists, functions, list comprehension 19 | * Week 5: Dictionaries, Tuples, Sets, Modules 20 | * Week 6: Classes, What to do further, Wrap-up, Surveys 21 | 22 | --- 23 | 24 | ## Lecture Materials 25 | 26 | We will have weekly lectures in the class, including; me teaching, comprehensive videos about the topic, and hands-on exercises. Also assignments will place weekly to improve the learning progress. 27 | 28 | --- 29 | 30 | ## Anonymity 31 | 32 | As part of this class you will be required to set up a [GitHub account](https://github.com). GitHub is a tool for collaborative code sharing and editing. During this course you will be submitting links to files you publicly place in your GitHub account. If you are concerned about preserving your anonymity you should set up an anonymous GitHub account and be careful not to include any information you do not want made available to peer evaluators. 33 | 34 | 35 | --- 36 | 37 | ## Typos 38 | 39 | * We are prone to a typo or two - please report them and we will try to update the notes accordingly. 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Py101-Spring-15 2 | This Repo contains class material and examples... 3 | -------------------------------------------------------------------------------- /Week 1/Py101 - Week1-Section1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Week 1/Py101 - Week1-Section1.pdf -------------------------------------------------------------------------------- /Week 1/README.md: -------------------------------------------------------------------------------- 1 | # Python 101 Week 1 2 | -------------------- 3 | Please remember the following: 4 | 5 | 1. Setup the Python Environment: https://www.python.org/downloads/release/python-342/ 6 | 2. Setup GitExtensions: http://sourceforge.net/projects/gitextensions/ 7 | 3. Read the Gitextensions manual, if you have time... : You can reach it from Classes Github account 8 | 4. Create a GitHub account: https://github.com/ 9 | 5. Follow me on GitHub with your account: https://github.com/eneskemalergin 10 | 6. Bring Laptops to next week's class 11 | 12 | Here is the Course link in the GitHub: https://github.com/NAU-Python-Class/Py101-Spring-15 13 | 14 | > Next Week We will start coding, please bring your laptops to be able to attend the hands- on practices... 15 | -------------------------------------------------------------------------------- /Week 2/Hands_on_Sec_2.py: -------------------------------------------------------------------------------- 1 | Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> def square(x): 4 | return x * x 5 | 6 | >>> square(5) 7 | 25 8 | >>> ================================ RESTART ================================ 9 | >>> 10 | >>> ================================ RESTART ================================ 11 | >>> 12 | 16 13 | 36 14 | 144 15 | 2388530067169 16 | >>> 17 | >>> variable_name = "Something" 18 | >>> variable_name 19 | 'Something' 20 | >>> enes = "Enes Kemal Ergin" 21 | >>> enes 22 | 'Enes Kemal Ergin' 23 | >>> % 24 | SyntaxError: invalid syntax 25 | >>> name 26 | Traceback (most recent call last): 27 | File "", line 1, in 28 | name 29 | NameError: name 'name' is not defined 30 | >>> name%enes 31 | Traceback (most recent call last): 32 | File "", line 1, in 33 | name%enes 34 | NameError: name 'name' is not defined 35 | >>> name$ 36 | SyntaxError: invalid syntax 37 | >>> name$ = "Enes" 38 | SyntaxError: invalid syntax 39 | >>> for = 13 40 | SyntaxError: invalid syntax 41 | >>> is = "string" 42 | SyntaxError: invalid syntax 43 | >>> foris = "Enes" 44 | >>> foris 45 | 'Enes' 46 | >>> for_ 47 | Traceback (most recent call last): 48 | File "", line 1, in 49 | for_ 50 | NameError: name 'for_' is not defined 51 | >>> for_ = 85 52 | >>> {} 53 | {} 54 | >>> if for_ == 85: {} 55 | 56 | {} 57 | >>> def square(x): 58 | return x * x 59 | SyntaxError: expected an indented block 60 | >>> def square(x): 61 | return x * x 62 | 63 | >>> square(2) 64 | 4 65 | >>> square(10) 66 | 100 67 | >>> square(100) 68 | 10000 69 | >>> square(1000) 70 | 1000000 71 | >>> # commenting 72 | >>> ############### 73 | >>> ================================ RESTART ================================ 74 | >>> 75 | 16 76 | 36 77 | 144 78 | 2388530067169 79 | >>> """ askdjbakdbadmnfbasasdmfnn 80 | ,amsndbfmasndfasdmfmansdbf 81 | kasdhfa 82 | """ 83 | ' askdjbakdbadmnfbasasdmfnn\n,amsndbfmasndfasdmfmansdbf\nkasdhfa\n' 84 | >>> ================================ RESTART ================================ 85 | >>> 86 | 16 87 | 36 88 | 144 89 | 2388530067169 90 | >>> name = "Enes" # This is a line comment 91 | >>> name 92 | 'Enes' 93 | >>> 45 + 80 94 | 125 95 | >>> 45*80 96 | 3600 97 | >>> 45/80 98 | 0.5625 99 | >>> 45 ** 80 100 | 1807178711742921674070014520448341764861809132965859026291312391149387101824891603102409541083128718952366398298181593418121337890625 101 | >>> 45-80 102 | -35 103 | >>> 45//80 104 | 0 105 | >>> 45 %80 106 | 45 107 | >>> 45 % 80 108 | 45 109 | >>> 80 % 45 110 | 35 111 | >>> 81 % 5 112 | 1 113 | >>> 80//45 114 | 1 115 | >>> 80%45 116 | 35 117 | >>> # We have 4 numeric types 118 | >>> 11 119 | 11 120 | >>> 456789123 121 | 456789123 122 | >>> 123 | >>> 11.0 124 | 11.0 125 | >>> type(11.0) 126 | 127 | >>> type(1+4j) 128 | 129 | >>> type(1+4i) 130 | SyntaxError: invalid syntax 131 | >>> type(4j) 132 | 133 | >>> 1+10e 134 | SyntaxError: invalid syntax 135 | >>> 10e - 1 136 | SyntaxError: invalid syntax 137 | >>> 14e-10 138 | 1.4e-09 139 | >>> import math 140 | >>> math.e 141 | 2.718281828459045 142 | >>> pow(2, 10) 143 | 1024 144 | >>> 2 ** 10 145 | 1024 146 | >>> abs(-10) 147 | 10 148 | >>> 14e-1 149 | 1.4 150 | >>> round(10.1) 151 | 10 152 | >>> round(10.6) 153 | 11 154 | >>> int(14.5) 155 | 14 156 | >>> int(14.1) 157 | 14 158 | >>> int(14.6) 159 | 14 160 | >>> float(85) 161 | 85.0 162 | >>> int(1+4e) 163 | SyntaxError: invalid syntax 164 | >>> int(1+4j) 165 | Traceback (most recent call last): 166 | File "", line 1, in 167 | int(1+4j) 168 | TypeError: can't convert complex to int 169 | >>> # Boolean 170 | >>> True 171 | True 172 | >>> False 173 | False 174 | >>> import math 175 | >>> math.sin(0) 176 | 0.0 177 | >>> math.sin(90) 178 | 0.8939966636005579 179 | >>> math.sin(math.radians(90)) 180 | 1.0 181 | >>> math.trunc(1.7) 182 | 1 183 | >>> math.trunc(1.2) 184 | 1 185 | >>> math.ceil(1.2) 186 | 2 187 | >>> math.floor(1.8) 188 | 1 189 | >>> math.sqrt(14) 190 | 3.7416573867739413 191 | >>> "jherkwqjhef" 192 | 'jherkwqjhef' 193 | >>> "456" 194 | '456' 195 | >>> '123', "123" 196 | ('123', '123') 197 | >>> 'Tom''s toy' 198 | 'Toms toy' 199 | >>> 'Tom's toy' 200 | SyntaxError: invalid syntax 201 | >>> "Tom's toy" 202 | "Tom's toy" 203 | >>> 'Tom\'s Toy' 204 | "Tom's Toy" 205 | >>> 206 | >>> s1 = "Tom's Toy" 207 | >>> len(s1) 208 | 9 209 | >>> s1 = "Water" 210 | >>> s2 = "melon" 211 | >>> s1 + s2 212 | 'Watermelon' 213 | >>> s3 = s1 + s2 214 | >>> s3 215 | 'Watermelon' 216 | >>> "Ha" * 5 217 | 'HaHaHaHaHa' 218 | >>> print("--------------------------------------------------------------------------------------") 219 | -------------------------------------------------------------------------------------- 220 | >>> print("-" * 100) 221 | ---------------------------------------------------------------------------------------------------- 222 | >>> s3 223 | 'Watermelon' 224 | >>> s3[0] 225 | 'W' 226 | >>> s3[-1] 227 | 'n' 228 | >>> len(s3) 229 | 10 230 | >>> s3[11] 231 | Traceback (most recent call last): 232 | File "", line 1, in 233 | s3[11] 234 | IndexError: string index out of range 235 | >>> s3[-11] 236 | Traceback (most recent call last): 237 | File "", line 1, in 238 | s3[-11] 239 | IndexError: string index out of range 240 | >>> s3[-4] 241 | 'e' 242 | >>> s3[-10] 243 | 'W' 244 | >>> s3[10] 245 | Traceback (most recent call last): 246 | File "", line 1, in 247 | s3[10] 248 | IndexError: string index out of range 249 | >>> s3[0:4] 250 | 'Wate' 251 | >>> s3[0:5] 252 | 'Water' 253 | >>> s3[5:] 254 | 'melon' 255 | >>> s3[-1:] 256 | 'n' 257 | >>> s3[-6:] 258 | 'rmelon' 259 | >>> s3[:-5] 260 | 'Water' 261 | >>> s3[::2] 262 | 'Wtreo' 263 | >>> s3[::3] 264 | 'Ween' 265 | >>> s3[::-1] 266 | 'nolemretaW' 267 | >>> s3[:] 268 | 'Watermelon' 269 | >>> s3[::1] 270 | 'Watermelon' 271 | >>> s3[2:5:-1] 272 | '' 273 | >>> s3[5:2:-1] 274 | 'mre' 275 | >>> s3[-2: -5:-1] 276 | 'ole' 277 | >>> s3 = s3 + " juice" 278 | >>> s3 279 | 'Watermelon juice' 280 | >>> s3= s3.replace("e", "*") 281 | >>> s3 282 | 'Wat*rm*lon juic*' 283 | >>> s1 = "istanbul" 284 | >>> s1.capitalize() 285 | 'Istanbul' 286 | >>> s3.lower() 287 | 'wat*rm*lon juic*' 288 | >>> dir(str) 289 | ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 290 | >>> dir(math) 291 | ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] 292 | >>> 293 | -------------------------------------------------------------------------------- /Week 2/Programming_Concepts_Week_2.md: -------------------------------------------------------------------------------- 1 | # Programming Concepts - Week 2 2 | 3 | > This file is all about practice. Writing all practices by yourself will improve your understanding in Python. Also I will put here more detailed, and somehow advanced examples, so you can challenge yourself practicing on them. 4 | 5 | --- 6 | 7 | ## Get to know Variables 8 | 9 | The word variable in programming describes a place to store information such as numbers, text, lists of numbers and text, and so 10 | on. Another way of looking at a variable is that it's like a label for something. 11 | 12 | We making a variable using assingment operator "=" 13 | We assigned integer value 100 to variable name called thompson: ``` thompson = 100 ```, it will allow us to use it again and again. 14 | 15 | ```Python 16 | thompson = 100 17 | print(thompson) 18 | 19 | # We can rewrite the variables, they are recyclable 20 | thompson = 200 21 | print(thompson) 22 | 23 | # We can copy values inside of the thompson to enes variable 24 | # right-hand side is the source 25 | # left-hand side is where we assigning tos 26 | enes = thompson 27 | print(enes) 28 | ``` 29 | 30 | * There are some signs that we cannot use when we are naming our variables such as $,%,@,^,etc. 31 | 32 | * Also we cannot use reserved words as they are. 33 | 34 | ```Python 35 | na$me = "Enes Kemal" # Wrong 36 | nam^e = "Enes Kemal" # Wrong 37 | this = 5 # Wrong 38 | is = 10 # Wrong 39 | this_is = 1 # Correct 40 | for = "string" # Wrong 41 | 42 | ``` 43 | 44 | ## Why Spacing is important for Python? 45 | 46 | Python uses indentation(having spaces to indicate it is inside of some statements.) Controls structures, functions, classes, methods, all need some indentation to be specify the hierarchical order. 47 | 48 | In R language you use brackets to specify there is a hierarchy 49 | ```R 50 | square <- function(x){ return(x^2)} 51 | ``` 52 | 53 | But in Python you don't have to specify with brackets 54 | ```Python 55 | def square(x): 56 | return(x**2) 57 | ``` 58 | 59 | Without indentation things will get very complicated, if they did, Python will throw an error at our faces says: ```IndentationError: expected an indented block``` 60 | 61 | ## Comments 62 | Commenting is very important concept in every programming language, it's because it is important for development process. 63 | 64 | When you and your group mates are working on a project, and you are the first part of th project, and you forget to put comments about what are the changes that you put. After some time, you will hear a lot of complaints about you and your lazy head... 65 | 66 | It is also beneficial for yourself. After a while, when you look at one of your codes you could understand everything or nothing. It all depends usign comments. 67 | 68 | ```Python 69 | # This is a line comment 70 | # Python will ignore everything in line after '#' sign, 71 | 72 | ''' 73 | This is multi line comment, which allows you to 74 | write comment on multiple lines. 75 | 76 | ''' 77 | ``` 78 | 79 | ## Basic Math using Python 80 | As we all now we have 4 basic math operators which are: '+', '-', '*', '/'; addition, substraction, multiplication, and divison. You can do kinds of calculation using these operators in Python interpreter. 81 | 82 | ```Python 83 | 1 + 10 84 | # 10 85 | 86 | 7 - 9 87 | # -2 88 | 89 | 3.0 * 4.0 90 | # 12.0 91 | 92 | 5 ** 2 93 | # 25 94 | 95 | 21 / 3 96 | # 7.0 // it is bit different 97 | 98 | ``` 99 | Python version 3.X they implemented division with result of fraction in any case. Because in version 2.X there was a problem when we type 1 / 2. The result was 0. If a developer or scientist was not aware of that and use some fraction resulted division in their experiment or software, it resulted as a disaster. 100 | 101 | Python solved this issue with using two different operators '/' for float-point division, and '//' is integer division 102 | 103 | ```Python 104 | # Python 3.4.2 105 | 106 | 21 / 3 107 | # 7.0 108 | 109 | 21 // 3 110 | # 7 111 | 112 | 21.0 // 7.0 113 | # 3.0 114 | 115 | 21.0 / 4.0 116 | # 5.25 117 | 118 | 21.0 // 4.0 119 | # 5.0 120 | 121 | 1/2 122 | # 0.5 123 | 124 | ``` 125 | 126 | We also have modulus operator "%" which gives us the remainder of a division : 127 | ```Python 128 | 21 % 3 129 | # 0 130 | 131 | 21.0 % 3.0 132 | # 0.0 133 | 134 | 21 % 4 135 | # 1 136 | 137 | 21.0 % 4.0 138 | # 1.0 139 | ``` 140 | ## Numeric Types 141 | ### Integers 142 | Integer are same as we know in general math. They can be both positive and negative without any fraction points. 143 | 144 | They represented as 3, -54, 1239990, and so on. 145 | 146 | In mathematical calculations integer with integer always resulted as integer except in fraction division. It will automatically return as a floating-point number. 147 | 148 | --- 149 | 150 | ### Floating-point Numbers 151 | They are also same as decimal point numbers in math. They have to be number.number form. 152 | ```Python 153 | 13 # integer 154 | 13.0 # float 155 | 4/5 # float 156 | ``` 157 | All calculations of floating point to floating-point will result as floating-point. 158 | 159 | ### Boolean Types 160 | We are seeing them here inside of the numeric types because their value is 1 and 0. What are they? True and False. 161 | 162 | They resulted after comparison statements which we will cover detailed way next week. 163 | 164 | Comparison operators are: 165 | * == is equal 166 | * > is smaller than 167 | * < is greater than 168 | * >= is smaller or equal 169 | * <= is greater or equal 170 | * != is not equal 171 | 172 | ```Python 173 | 2 == 2 174 | # True 175 | 176 | 2 > 3 177 | # False 178 | 179 | 2 < 3 180 | # True 181 | 182 | 2 >= 2 183 | # True 184 | 185 | 2 <= 1 186 | # False 187 | 188 | 2 != 1 189 | # True 190 | ``` 191 | 192 | ### Built-in Functions Using in Numbers 193 | 194 | pow(), abs(), round(), int(), float(), 195 | 196 | ```Python 197 | pow(2,6) # Returns the first numbers second numbers power 198 | # 64 199 | 200 | abs(-27) # Returns the positive of the number 201 | # 27 202 | 203 | round(3.45) 204 | # 3 205 | 206 | round(3.55) 207 | # 4 208 | 209 | # We could round decimal points as well 210 | round(3.333333333, 2) # Adding one more will make it more efficient. 211 | # 3.34 212 | 213 | int(3.45) 214 | # 3 215 | 216 | float(3) 217 | # 3.0 218 | 219 | ``` 220 | We have other built-in numeric tools inside math modules. For now just know, we can call other modules by importing them... 221 | After importing the module we can use math.pi, math.e, math.sin(), math.sqrt(), math.floor(), math.trunc(), math.ceil() 222 | 223 | ```Python 224 | import math # Calling the math library/module 225 | 226 | math.pi 227 | # 3.141592653589793 228 | 229 | math.e 230 | # 2.718281828459045 231 | 232 | math.sin(0) 233 | # 0.0 234 | 235 | math.sqrt(4) 236 | # 2.0 237 | 238 | math.floor(2.567) 239 | # 2 240 | 241 | math.floor(-2.567) 242 | # -3 243 | 244 | math.trunc(2.567) # It drops the decimal digits 245 | # 2 246 | 247 | math.trunc(-2.567) # It drops the decimal digits 248 | # -2 249 | 250 | math.ceil(2.567) 251 | # 3 252 | 253 | math.ceil(-2.567) 254 | # -2 255 | 256 | ``` 257 | 258 | --- 259 | 260 | ### Random library 261 | 262 | ```Python 263 | import random # Calling the random library/module 264 | 265 | random.random() # it will give us random floats between 0 and 1 266 | # 0.050899111154044 267 | 268 | random.randint(1, 10) 269 | # 9 270 | 271 | random.choice(list) 272 | 273 | random.shuffle(list) 274 | ``` 275 | 276 | ## Strings 277 | Strings are very powerful data types, because they have a lot of tools along with them. 278 | 279 | ### string Literals 280 | Strings are fairly easy to use. Perhaps the most complicated thing about them is that there are som many ways to write them in your code: 281 | 282 | * Single quotes: 'spam' 283 | * Double quotes: "spam" 284 | * Triple quotes: '''... spam... ''', """... spam...""" 285 | * There are more but complicated... 286 | 287 | Single and double quotes are same 288 | 289 | ```Python 290 | "knight's" 291 | 292 | 'knight"s' 293 | 294 | title = "Introductory " 'Python' #this called implicit concatenation 295 | ``` 296 | There are some methods, which will make strings powerful 297 | 298 | ```Python 299 | s = "This is example string" 300 | len(s) # Returns the length of the variable s 301 | # 22 302 | 303 | # Concatenation is another powerful tool 304 | 305 | 'abc' + 'def' 306 | # abcdef 307 | 308 | repeat_string = 'Ni!' * 4 # Concatenate 4 times... 309 | repeat_string 310 | # 'Ni!Ni!Ni!Ni!' 311 | 312 | # For example if we want to put 80 dashes to make our code stylis 313 | print('-----------....more....-------------') # The hard way 314 | print('-' * 80) # the easy way. You love Python right? 315 | 316 | my_job = 'scientist' # Create string variable called my_job 317 | 318 | "k" in my_job # is there any k in the string 319 | # False 320 | 321 | "t" in my_job # is there any t in the string 322 | # True 323 | 324 | "tist" in my_job # is there any tist in the string 325 | # True 326 | ``` 327 | --- 328 | 329 | ### String Indexing and Slicing 330 | Because strings are defined as ordered collections of characters, we can access their components by position. In Python, characters in a string are fetched by indexing-providing the numeric offset of the desired component in square brackets after the string. You get back the one-character string at the specified position. 331 | 332 | As in the C language, Python offsets start at 0 and end at one less than the length of the string. Unlike C, however, Python also lets you fetch items from sequences such as strings using negative offsets. Technically, a negative offset is added to the length of a 333 | string to derive a positive offset. You can also think of negative offsets as counting backward from the end. 334 | 335 | ```Pyhton 336 | s = 'spam' 337 | s[0] # Show the first character in the string 338 | # 's' 339 | s[-2] # Show the character before the last one in the string 340 | # 'a' 341 | 342 | s[1:3] # slicing 343 | # 'pa' 344 | s[1:] # Takes every character before second element with second 345 | # 'pam' 346 | s[:-1] # Takes every element until the las one s[:3] same 347 | # 'spa' 348 | 349 | s2 = 'endoplasmic reticulum' 350 | s2[1:10:2] # it takes the character from 1 to 9 with skipping items 351 | # 'nolsi' 352 | 353 | "hello"[::-1] # easy way to reverse the order... 354 | ``` 355 | --- 356 | 357 | ### Changing strings 1 358 | 359 | Strings are immutable sequence, means that you cannot change a string in place. If you do this: 360 | ```Python 361 | S = "spam" 362 | s[0] = "x" 363 | # TypeError: "str" object does not support item assignment 364 | 365 | ``` 366 | it will yell at you with an error. 367 | 368 | But we can make a new one with reassigning 369 | ```Python 370 | s = "spam" 371 | s = s + "SPAM!" 372 | s 373 | # "spamSPAM!" 374 | 375 | s = s[:4] + "Burger" + s[-1] 376 | s 377 | # "spamBurger!" 378 | 379 | s = s.replace("spam", "chicken") 380 | s 381 | "chickenBurger!" 382 | 383 | ``` 384 | There are other methods for string. You can look at them by typing ```dir(str)``` 385 | 386 | ### Changing Strings 2 387 | 388 | ```Python 389 | s = 'spammy' 390 | s = s[:3] + 'xx' + s[5:] 391 | s 392 | # "spaxxy" 393 | 394 | s = "spammy" 395 | s = s.replace("mm", "xx") 396 | s 397 | # "spaxxy" 398 | 399 | 'aa$bb$cc$dd'.replace('$', 'SPAM') 400 | # 'aaSPAMbbSPAMccSPAMdd' 401 | 402 | line = "The knights who say Ni!\n" 403 | line.rstrip() 404 | 'The knights who say Ni!' 405 | 406 | line.upper() 407 | # 'THE KNIGHTS WHO SAY NI!\n' 408 | 409 | line.isalpha() 410 | # False 411 | 412 | line.endswith('Ni!\n') 413 | # True 414 | 415 | line.startswith('The') 416 | # True 417 | 418 | ``` 419 | 420 | Thank you for your time, have a great learning! 421 | -------------------------------------------------------------------------------- /Week 2/Py101 - Week2 - Section1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Week 2/Py101 - Week2 - Section1.pdf -------------------------------------------------------------------------------- /Week 2/exercise_#1.md: -------------------------------------------------------------------------------- 1 | # Exercise #1 2 | 3 | ## Part 1 ~ Types 4 | Find the types of all following. 5 | 6 | > Hint: You may want to use ``` type() ``` function to make sure your answers are correct. 7 | 8 | 1. ``` 85.4 ``` 9 | 10 | 2. ``` -409 ``` 11 | 12 | 3. ``` True ``` 13 | 14 | 4. ``` None ``` 15 | 16 | 5. ``` -13.0 ``` 17 | 18 | 19 | ## Part 2 ~ Basic Math 20 | Find the correct results of each calculation 21 | 22 | 1. ``` 12 + 5 - 2 ``` 23 | 24 | 2. ``` 4 * 9.0 ``` 25 | 26 | 3. ``` --16 ``` 27 | 28 | 4. ``` 9 / 3 ``` 29 | 30 | 5. ``` 10 // 3 ``` 31 | 32 | 6. ``` 10.0 // 4.0 ``` 33 | 34 | 7. ``` (2 + 5) * 4 ``` 35 | 36 | 8. ``` 2 + 5 * 4 ``` 37 | 38 | 9. ``` 4 ** 3 + 16 ``` 39 | 40 | 10. ``` 2.1 ** 2.0 ``` 41 | 42 | 11 ``` 2.2 * 4.0 ``` 43 | 44 | 45 | ## Part 3 ~ Booleans and Comparison 46 | Find the correct result of each comparison 47 | 48 | 1. ``` 9 > 1 ``` 49 | 50 | 2. ``` 3.0 > 3.001 ``` 51 | 52 | 3. ``` 2 > 2 ``` 53 | 54 | 4. ``` 2 > +2 ``` 55 | 56 | 5. ``` 3 + 3 == 9 ``` 57 | 58 | 6. ``` True or False ``` 59 | 60 | 7. ``` True ``` 61 | 62 | 8. ``` not False ``` 63 | 64 | 9. ``` 3 > 4 or (2 < 3 and 9 > 10) ``` 65 | 66 | 10. ``` not(4 > 3 and 100 > 6) ``` 67 | 68 | ## Part 4 ~ Calculations and Types 69 | For following exercise find both types of results and results. 70 | 71 | 1. ``` 2 + 7.0 ``` 72 | 73 | 2. ``` 1 / 2 ``` 74 | 75 | 3. ``` 1 // 2 ``` 76 | 77 | 4. ``` 1/2 == 1//2 ``` 78 | 79 | 5. ``` round(3.4) ``` 80 | 81 | 6. ``` int(98.7) ``` 82 | 83 | 7. ``` 2.0 + 4.0 ``` 84 | 85 | 8. ``` 5*2 == 5.0 * 2.0 ``` 86 | 87 | 88 | ## Part 5 ~ Strings 89 | Find the correct results of following strings 90 | 91 | 1. ``` "N" + "AU" ``` 92 | 93 | 2. ``` ("Go" * "3") + "Stallions!" ``` 94 | 95 | 3. ``` ("Go" * 3) + "Stallions!" ``` 96 | 97 | 4. ``` "Stallions"[2] ``` 98 | 99 | 5. ``` "Stallions"[5:] ``` 100 | 101 | 6. ``` "Stallions"[:5] ``` 102 | 103 | ## Part 6 ~ More on Strings 104 | Find the correct solutions of following questions. Use the variables that I have defined: 105 | ```Python 106 | str1 = "Python is " 107 | str2 = "so " 108 | str3 = "much fun!" 109 | ``` 110 | 111 | > Hint: If I were you, I would consider the spaces too... 112 | 113 | 1. ``` print(str1) ``` 114 | 115 | 2. ``` str1[0] ``` 116 | 117 | 3. ``` str1[-1] ``` 118 | 119 | 4. ``` len(str1) ``` 120 | 121 | 5. ```str1[len(str1)] ``` 122 | 123 | 6. ``` str1 + str2 + str3 ``` 124 | 125 | 7. ``` "t" in str3 ``` 126 | 127 | 8. ``` "t" in str1 ``` 128 | 129 | 9. ``` str3[1:3] ``` 130 | 131 | 10. ``` str2[:-1] ``` 132 | 133 | 11. ``` str4[1:10] ``` 134 | 135 | 12. ``` (str1 + str2 + str3)[::-1] ``` 136 | 137 | ## Part 7 ~ String Methods 138 | Find the correct results of following questions about string methods. Using already defined variables: 139 | ```Python 140 | str1 = "here comes the best part" 141 | str2 = "methods of strings" 142 | ``` 143 | 144 | 1. ``` str1.upper() ``` 145 | 146 | 2. ``` str1 ``` 147 | 148 | 3. ``` str1.isupper() ``` 149 | 150 | 4. ``` str2.islower() ``` 151 | 152 | 5. 153 | ```Python 154 | str2 = str2.capitalize() 155 | str2 156 | ``` 157 | 158 | 6. ```str2 = swapcase() ``` 159 | 160 | 7. ``` str1.index("e") ``` 161 | 162 | 8. ``` str1.index("n") ``` 163 | 164 | 9. ``` str1.find(e) ``` 165 | 166 | 10. ``` str2.find("!") ``` 167 | 168 | 11. ``` str1.count("e") ``` 169 | 170 | 12. 171 | ```Python 172 | str1 = str1.replace("e", "x") 173 | str1 174 | ``` 175 | 176 | 13. ``` str2.replace("of" , "with") ``` 177 | 178 | 179 | 180 | 181 | -------------------------------------------------------------------------------- /Week 2/hands_on_week2.py: -------------------------------------------------------------------------------- 1 | Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> # Python 101 4 | >>> 100 5 | 100 6 | >>> enes = 100 7 | >>> enes 8 | 100 9 | >>> enes = 80 10 | >>> enes 11 | 80 12 | >>> Python_class = enes 13 | >>> Python_class 14 | 80 15 | >>> # right hand side is always the source for copying. 16 | >>> print(enes) 17 | 80 18 | >>> print(Python_class) 19 | 80 20 | >>> Python_class == enes 21 | True 22 | >>> Python_class != enes 23 | False 24 | >>> # We cannot use @,#,$,%,^ 25 | >>> nam$e 26 | SyntaxError: invalid syntax 27 | >>> name^enes 28 | Traceback (most recent call last): 29 | File "", line 1, in 30 | name^enes 31 | NameError: name 'name' is not defined 32 | >>> # It understand name and enes as a variable name and look for a value 33 | >>> name%enes 34 | Traceback (most recent call last): 35 | File "", line 1, in 36 | name%enes 37 | NameError: name 'name' is not defined 38 | >>> name = 100 39 | >>> name%enes 40 | 20 41 | >>> # We are trying to make a variable not math... 42 | >>> # We cannot use reserved words. 43 | >>> this = 100 44 | >>> this 45 | 100 46 | >>> is = 100 47 | SyntaxError: invalid syntax 48 | >>> # this is not reserved so, it wont cause any error 49 | >>> # But is caused trouble for us.. 50 | >>> for = 100 51 | SyntaxError: invalid syntax 52 | >>> for_this_is = 100 53 | >>> 54 | >>> # Indentation is very crucial 55 | >>> if enes == 80: 56 | # Do something 57 | pass 58 | 59 | >>> if enes == 80: 60 | print(True) 61 | SyntaxError: expected an indented block 62 | >>> # For most of the syntax we use indentation 63 | >>> # IT is line comment 64 | >>> ''' 65 | aasdsdkjgl hasgh 66 | skdfjh las 67 | sadfkh sad 68 | askludfh 69 | asdfuhl;sa 70 | ''' 71 | '\naasdsdkjgl hasgh\nskdfjh las\nsadfkh sad\naskludfh\nasdfuhl;sa\n' 72 | >>> 10+10 73 | 20 74 | >>> 205+12 75 | 217 76 | >>> 154-54 77 | 100 78 | >>> 1854-47 79 | 1807 80 | >>> 12*8 81 | 96 82 | >>> 95 83 | 95 84 | >>> 95*8 85 | 760 86 | >>> 10+54*87-54 87 | 4654 88 | >>> (10+54)*(87-54) 89 | 2112 90 | >>> 12/4 91 | 3.0 92 | >>> 1/2 # version 2.X 93 | 0.5 94 | >>> # It is not 0.5 95 | >>> # it is 0 96 | >>> 1.0/2.0 97 | 0.5 98 | >>> 1//2 99 | 0 100 | >>> 1.0/2.0 101 | 0.5 102 | >>> 1.0//2.0 103 | 0.0 104 | >>> # Floating point division / 105 | >>> # Integer division // 106 | >>> 21/3 107 | 7.0 108 | >>> 45/9 109 | 5.0 110 | >>> 45/8 111 | 5.625 112 | >>> 45//8 113 | 5 114 | >>> 45.0//8.0 115 | 5.0 116 | >>> 117 | >>> 21%3 118 | 0 119 | >>> 21 % 5 120 | 1 121 | >>> 234 %5 122 | 4 123 | >>> (234 // 5) + (234 % 5) 124 | 50 125 | >>> 21.0 % 3.0 126 | 0.0 127 | >>> print("=" * 45) 128 | ============================================= 129 | >>> # Numeric Types 130 | >>> type() # Which shows the type of an input 131 | Traceback (most recent call last): 132 | File "", line 1, in 133 | type() # Which shows the type of an input 134 | TypeError: type() takes 1 or 3 arguments 135 | >>> type(3) 136 | 137 | >>> type(-10) 138 | 139 | >>> type(10000000000000000000) 140 | 141 | >>> type(0) 142 | 143 | >>> 1/2 144 | 0.5 145 | >>> type(1/2) 146 | 147 | >>> import math 148 | >>> type(math.pi) 149 | 150 | >>> type(1.90123) 151 | 152 | >>> type(-10000000.90123) 153 | 154 | >>> type(math.e) 155 | 156 | >>> # Every calculation includes at least 1 float makes the result float 157 | >>> (1+ 2.0) * 56 / (15-4) 158 | 159 | SyntaxError: unexpected indent 160 | >>> (1+ 2.0) * 56 / (15-4) 161 | 15.272727272727273 162 | >>> # Every calculation includes at least 1 float makes the result float 163 | >>> (1+ 2.0) * 56 // (15-4) 164 | 15.0 165 | >>> # We have only one float 166 | >>> True 167 | True 168 | >>> False 169 | False 170 | >>> 171 | >>> # ==, >, <, != 172 | >>> 2 == 2 173 | True 174 | >>> 5 != 5 175 | False 176 | >>> # Built-in functions 177 | >>> pow(3,2) # 3^2 178 | 9 179 | >>> abs(-10) 180 | 10 181 | >>> round(3.55) 182 | 4 183 | >>> round(3.45) 184 | 3 185 | >>> int(3.56) 186 | 3 187 | >>> int(3.12) 188 | 3 189 | >>> # Int function drops the fraction to make it integer. 190 | >>> float(3) 191 | 3.0 192 | >>> float(1230) 193 | 1230.0 194 | >>> import math 195 | >>> math.sin(0) 196 | 0.0 197 | >>> math.sin(90) 198 | 0.8939966636005579 199 | >>> math.sin(90) 200 | 0.8939966636005579 201 | >>> # Because of weird rounding in floating-operations 202 | >>> math.pi 203 | 3.141592653589793 204 | >>> math.e 205 | 2.718281828459045 206 | >>> math.sqrt(16) 207 | 4.0 208 | >>> math.sqrt(12) 209 | 3.4641016151377544 210 | >>> math.floor(2.567) 211 | 2 212 | >>> math.floor(-2.567) 213 | -3 214 | >>> math.trunc(2.567) 215 | 2 216 | >>> math.trunc(-2.567) 217 | -2 218 | >>> # trunc ust drops the decimal digits 219 | >>> 220 | >>> 221 | >>> 222 | >>> 223 | >>> 224 | >>> String 225 | Traceback (most recent call last): 226 | File "", line 1, in 227 | String 228 | NameError: name 'String' is not defined 229 | >>> # String 230 | >>> 'Enes Kemal' 231 | 'Enes Kemal' 232 | >>> "Enes Kemal " 233 | 'Enes Kemal ' 234 | >>> """ askjdhas 235 | asdldjhf 236 | akkdfhj 237 | kajddhf """ 238 | ' askjdhas\nasdldjhf\nakkdfhj\nkajddhf ' 239 | >>> "Tom's toy" 240 | "Tom's toy" 241 | >>> 'Tom"s toy' 242 | 'Tom"s toy' 243 | >>> "Tom's toy" 244 | "Tom's toy" 245 | >>> s = "NAU Python Class" 246 | >>> len(s) 247 | 16 248 | >>> "water" + "melon" 249 | 'watermelon' 250 | >>> "Ha" * 5 251 | 'HaHaHaHaHa' 252 | >>> print("----------------------------------------------------------------------------------") 253 | ---------------------------------------------------------------------------------- 254 | >>> print("-" * 100) 255 | ---------------------------------------------------------------------------------------------------- 256 | >>> my_hobby = "hacking" 257 | >>> h in my_hobby 258 | Traceback (most recent call last): 259 | File "", line 1, in 260 | h in my_hobby 261 | NameError: name 'h' is not defined 262 | >>> "h" in my_hobby 263 | True 264 | >>> "z" in my_hobby 265 | False 266 | >>> "king" in my_hobby 267 | True 268 | >>> # indexing 269 | >>> s = "NAU Python Clas" 270 | >>> s = "NAU Python Class" 271 | >>> s[0] 272 | 'N' 273 | >>> s[-1] 274 | 's' 275 | >>> s[3] 276 | ' ' 277 | >>> # Slicing 278 | >>> # you can extract words 279 | >>> s[:3] 280 | 'NAU' 281 | >>> # : colon is from-to operator 282 | >>> # if we have one more it will be skipping 283 | >>> s[1:10: 2] 284 | 'A yhn' 285 | >>> s[1:10:1] 286 | 'AU Python' 287 | >>> s[1:10:-1] 288 | '' 289 | >>> s[:-1] 290 | 'NAU Python Clas' 291 | >>> s[::-1] 292 | 'ssalC nohtyP UAN' 293 | >>> 294 | >>> # Strings are immutable 295 | >>> s = s + " Spring 15" 296 | >>> print(s) 297 | NAU Python Class Spring 15 298 | >>> # We kind changed it 299 | >>> s[:4] + "Burger" + s[-1] 300 | 'NAU Burger5' 301 | >>> s = s.replace("5", "#1") 302 | >>> print(s) 303 | NAU Python Class Spring 1#1 304 | >>> dir(str) 305 | ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 306 | >>> 307 | -------------------------------------------------------------------------------- /Week 3/Hands_on_conditions.py: -------------------------------------------------------------------------------- 1 | Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> # Let's remember the booleans 4 | >>> TRUE 5 | Traceback (most recent call last): 6 | File "", line 1, in 7 | TRUE 8 | NameError: name 'TRUE' is not defined 9 | >>> True 10 | True 11 | >>> False 12 | False 13 | >>> not True 14 | False 15 | >>> not False 16 | True 17 | >>> # We can also use logic to result complicated relations 18 | >>> True and True # I know it is not that complicated 19 | True 20 | >>> False or True 21 | True 22 | >>> (False or True) and (False and False) or (True and False) 23 | False 24 | >>> # Comparison operations result boolean 25 | >>> 78 < 9 26 | False 27 | >>> 12 > 9 28 | True 29 | >>> 12 >= 12 30 | True 31 | >>> 67.0 == 67 32 | True 33 | >>> 67.3 == 67 34 | False 35 | >>> # We can combine more numbers into logical concepts 36 | >>> (123 != 14) and (14 and 15 == 14) 37 | False 38 | >>> # Those comparisons work in strings as well 39 | >>> "NAU" > "nau" 40 | False 41 | >>> # It uses ASCII table to obtain numbers correlated with character 42 | >>> "z" == "Z" 43 | False 44 | >>> # They are not equal 45 | >>> if "a" == "a": 46 | print("yes they are equal") 47 | 48 | 49 | yes they are equal 50 | >>> x = 10 51 | >>> if x > 0: 52 | print("It is positive!") 53 | 54 | 55 | It is positive! 56 | >>> if x <= 0: 57 | print("It is not positive!") 58 | 59 | 60 | >>> # As you can see nothing printed, because condition was not resulted True 61 | >>> # To avoid these answerless situations we uses default case called else 62 | >>> if x > 0: 63 | print("It is positive!") 64 | else : 65 | print("It is not positive!") 66 | 67 | 68 | It is positive! 69 | >>> # Lets change x and see the else working 70 | >>> x = -1 71 | >>> if x > 0: 72 | print("It is positive!") 73 | else : 74 | print("It is not positive!") 75 | 76 | 77 | It is not positive! 78 | >>> # We can increase the situations using elif 79 | >>> if x > 0: 80 | print("It is positive!") 81 | elif x == 0: 82 | print("It is zero!") 83 | else : 84 | print("It is not positive!") 85 | 86 | 87 | It is not positive! 88 | >>> x = 0 89 | >>> if x > 0: 90 | print("It is positive!") 91 | elif x == 0: 92 | print("It is zero!") 93 | else : 94 | print("It is not positive!") 95 | 96 | 97 | It is zero! 98 | >>> # You can increase the number of elifs inside the conditionals 99 | >>> number = 2 100 | >>> if type(number) == int: 101 | if number > 0: 102 | print("It is a positive integer number!") 103 | elif number == 0: 104 | print("It is zero") 105 | else: 106 | print("It is a negative integer number!") 107 | else: 108 | print("This number is not an integer!") 109 | 110 | 111 | It is a positive integer number! 112 | >>> number = 2.0 113 | >>> if type(number) == int: 114 | if number > 0: 115 | print("It is a positive integer number!") 116 | elif number == 0: 117 | print("It is zero") 118 | else: 119 | print("It is a negative integer number!") 120 | else: 121 | print("This number is not an integer!") 122 | 123 | 124 | This number is not an integer! 125 | >>> 126 | -------------------------------------------------------------------------------- /Week 3/Hands_on_iteration.py: -------------------------------------------------------------------------------- 1 | Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> # looping with Python 4 | >>> ## While loop 5 | >>> # They are called indefinite loops 6 | >>> x = x + 1 7 | Traceback (most recent call last): 8 | File "", line 1, in 9 | x = x + 1 10 | NameError: name 'x' is not defined 11 | >>> x = 1 12 | >>> x +=1 13 | >>> x 14 | 2 15 | >>> # We call this an initialization 16 | >>> x += 1 # is same as x = x + 1 17 | >>> x -=1 18 | >>> x-=1 19 | >>> x 20 | 1 21 | >>> n = 5 22 | >>> while n >0: 23 | print(n) 24 | n -= 1 25 | 26 | 27 | 5 28 | 4 29 | 3 30 | 2 31 | 1 32 | >>> n = 10 33 | >>> while True: # which makes it always true and always run... 34 | print(n, end = " ") 35 | n = n - 1 36 | print("Done!") 37 | SyntaxError: invalid syntax 38 | >>> while True: # which makes it always true and always run... 39 | print(n, end = " ") 40 | n = n - 1 41 | 42 | 43 | 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -292 -293 -294 -295 -296 -297 -298 -299 -300 -301 -302 -303 -304 -305 -306 -307 -308 -309 -310 -311 -312 -313 -314 -315 -316 -317 -318 -319 -320 -321 -322 -323 -324 -325 -326 -327 -328 -329 -330Traceback (most recent call last): 44 | File "", line 2, in 45 | print(n, end = " ") 46 | File "C:\Python34\lib\idlelib\PyShell.py", line 1352, in write 47 | return self.shell.write(s, self.tags) 48 | KeyboardInterrupt 49 | >>> # Control+C stopts the infinite looping,,, 50 | >>> while True: 51 | line = input(">") 52 | if line == "done" 53 | 54 | SyntaxError: invalid syntax 55 | >>> while True: 56 | line = input(">") 57 | if line == "done": 58 | break 59 | print(line) 60 | 61 | 62 | >s 63 | s 64 | >s 65 | s 66 | >asd 67 | asd 68 | >asd 69 | asd 70 | >afg 71 | afg 72 | >2 + 2 73 | 2 + 2 74 | >done 75 | >>> import time 76 | >>> i = 1 77 | >>> while True: 78 | print("Welcome", i, " times. To stop press [CTRL+C]") 79 | i += 1 80 | time.sleep(2) # It just delays for 2 second 81 | 82 | 83 | Welcome 1 times. To stop press [CTRL+C] 84 | Welcome 2 times. To stop press [CTRL+C] 85 | Welcome 3 times. To stop press [CTRL+C] 86 | Welcome 4 times. To stop press [CTRL+C] 87 | Welcome 5 times. To stop press [CTRL+C] 88 | Traceback (most recent call last): 89 | File "", line 4, in 90 | time.sleep(2) # It just delays for 2 second 91 | KeyboardInterrupt 92 | >>> while True: 93 | line = input(">") 94 | if line[0] == "#": 95 | continue 96 | if line == "done": 97 | break 98 | 99 | 100 | >123 101 | >123 102 | >123 103 | >123 104 | >123 105 | >123 106 | >123 107 | >123 108 | >123 109 | >123 110 | >123 111 | >BEcause I forget to put print() :) 112 | >done 113 | >>> while True: 114 | line = input(">") 115 | if line[0] == "#": 116 | continue 117 | if line == "done": 118 | break 119 | print(line) 120 | 121 | 122 | >123 123 | 123 124 | >123 125 | 123 126 | >123 127 | 123 128 | ># Enes Kemal 129 | >enes kemal 130 | enes kemal 131 | >done 132 | >>> for i in "Python": 133 | print(i, end = "-") 134 | 135 | 136 | P-y-t-h-o-n- 137 | >>> for i in "Python": 138 | print(i) 139 | 140 | 141 | P 142 | y 143 | t 144 | h 145 | o 146 | n 147 | >>> 148 | -------------------------------------------------------------------------------- /Week 3/Hands_on_week3_section2.py: -------------------------------------------------------------------------------- 1 | Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> True 4 | True 5 | >>> False 6 | False 7 | >>> if something == 0: 8 | print(" ") 9 | 10 | 11 | Traceback (most recent call last): 12 | File "", line 1, in 13 | if something == 0: 14 | NameError: name 'something' is not defined 15 | >>> something = 10 16 | >>> if something == 0: 17 | print(" ") 18 | 19 | 20 | >>> False or True 21 | True 22 | >>> 78 < 90 23 | True 24 | >>> 78 > 90 25 | False 26 | >>> "NAU" == "nau" 27 | False 28 | >>> "NAU" != "nau" 29 | True 30 | >>> not True 31 | False 32 | >>> not False 33 | True 34 | >>> "NAU" > "nau" 35 | False 36 | >>> int("n") 37 | Traceback (most recent call last): 38 | File "", line 1, in 39 | int("n") 40 | ValueError: invalid literal for int() with base 10: 'n' 41 | >>> 67.0 == 67 42 | True 43 | >>> 67.2 == 67 44 | False 45 | >>> ord("N") 46 | 78 47 | >>> ord("n") 48 | 110 49 | >>> # if-elif-else 50 | >>> x = 10 51 | >>> if x > 1: 52 | print("Bigger than 1") 53 | 54 | 55 | Bigger than 1 56 | >>> if x > 11: 57 | print("Bigger than 11") 58 | else: 59 | print("Smaller than 11") 60 | 61 | 62 | Smaller than 11 63 | >>> x = -1 64 | 65 | SyntaxError: unexpected indent 66 | >>> x = -1 67 | >>> if x > 0: 68 | print("Positive number") 69 | elif: 70 | 71 | SyntaxError: invalid syntax 72 | >>> if x > 0: 73 | print("Positive number") 74 | elif x == 0: 75 | print("Zero") 76 | else: 77 | print("Negative number") 78 | 79 | 80 | Negative number 81 | >>> if x > 0: 82 | print("Positive number") 83 | elif x < 0: 84 | print("Negative Number") 85 | else: 86 | print("Zero") 87 | 88 | 89 | Negative Number 90 | >>> x = 0 91 | >>> if x > 0: 92 | print("Positive number") 93 | elif x < 0: 94 | print("Negative Number") 95 | else: 96 | print("Zero") 97 | 98 | 99 | Zero 100 | >>> x = 1.9 101 | >>> if type(x) == int: 102 | if x > 0 : 103 | print("Positive Number:)' 104 | 105 | SyntaxError: EOL while scanning string literal 106 | >>> if type(x) == int: 107 | if x > 0 : 108 | print("Positive Number:) 109 | 110 | SyntaxError: EOL while scanning string literal 111 | >>> if type(x) == int: 112 | if x > 0 : 113 | print("Positive Number"): 114 | 115 | SyntaxError: invalid syntax 116 | >>> if type(x) == int: 117 | if x > 0 : 118 | print("Positive Number") 119 | elif x == 0: 120 | print("Zero") 121 | else: 122 | print("Negative Number") 123 | 124 | 125 | >>> if type(x) == int: 126 | if x > 0 : 127 | print("Positive Number") 128 | elif x == 0: 129 | print("Zero") 130 | else: 131 | print("Negative Number") 132 | else: 133 | print("Not integer number") 134 | 135 | 136 | Not integer number 137 | >>> x = 0 138 | >>> # increment variable 139 | >>> x = x + 1 140 | >>> x += 1 141 | >>> x 142 | 2 143 | >>> x = x - 1 144 | >>> x 145 | 1 146 | >>> x -= 1 147 | >>> x = x * 2 148 | >>> x 149 | 0 150 | >>> x = 10 151 | >>> x = x *2 152 | >>> x 153 | 20 154 | >>> x *= 2 155 | >>> x 156 | 40 157 | >>> x /= 2 158 | >>> n = 5 159 | >>> while n > 0: 160 | print(n) 161 | n -= 1 162 | 163 | 164 | 5 165 | 4 166 | 3 167 | 2 168 | 1 169 | >>> n = 10 170 | >>> while True: 171 | print(n, end = " ") 172 | n -= 1 173 | 174 | 175 | 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 176 | -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -292 -293 -294 -295 -296 -297 -298 -299 -300 -301 -302 -303 -304 -305 -306 -307 -308 -309 -310 -311 -312 -313 -314 -315 -316 -317 -318 -319 -320 -321 -322 -323 -324 -325 -326 -327 -328 -329 -330 -331 -332 -333 -334 -335 -336 -337 -338 -339 -340 -341 -342 -343 -344 -345 -346 -347 -348 -349 -350 -351 -352 -353 -354 -355 -356 -357 -358 -359 -360 -361 -362 -363 -364 -365 -366 -367 -368 -369 -370 -371 -372 -373 -374 -375 -376 -377 -378 -379 -380 -381 -382 -383 -384 -385 -386 -387 -388 -389 -390 -391 -392 -393 -394 -395 -396 -397 -398 -399 -400 -401 -402 -403 -404 -405 -406 -407 -408 -409 -410 -411 -412 -413 -414 -415 -416 -417 -418 -419 -420 -421 -422 -423 -424 -425 -426 -427 -428 -429 -430 -431 -432 -433 -434 -435 -436 -437 -438 -439 -440 -441 -442 -443 -444 -445 -446 -447 -448 -449 -450 -451 -452 -453 -454 -455 -456 -457 -458 -459 -460 -461 -462 -463 -464 -465 -466 -467 -468 -469 -470 -471 -472 -473 -474 -475 -476 -477 -478 -479 -480 -481 -482 -483 -484 -485 -486 -487 -488 -489 -490 -491 -492 -493 -494 -495 -496 -497Traceback (most recent call last): 177 | File "", line 2, in 178 | print(n, end = " ") 179 | File "C:\Python34\lib\idlelib\PyShell.py", line 1352, in write 180 | return self.shell.write(s, self.tags) 181 | KeyboardInterrupt 182 | >>> while True: 183 | line = input(">") 184 | if line == "done" 185 | 186 | SyntaxError: invalid syntax 187 | >>> while True: 188 | line = input(">") 189 | if line == "done": 190 | print(line) 191 | 192 | SyntaxError: expected an indented block 193 | >>> 194 | >>> while True: 195 | line = input(">") 196 | if line == "done": 197 | print(line) 198 | 199 | SyntaxError: expected an indented block 200 | >>> while True: 201 | line = input(">") 202 | if line == "done": 203 | break 204 | print(line) 205 | 206 | 207 | > "Enes " 208 | "Enes " 209 | >123 210 | 123 211 | >akfjh 212 | akfjh 213 | >ksudhf 214 | ksudhf 215 | >sadidl 216 | sadidl 217 | >sdfi 218 | sdfi 219 | >done 220 | >>> while True: 221 | line = input("Write Something: ") 222 | if line == "done": 223 | break 224 | print(line) 225 | 226 | 227 | Write Something: 123 228 | 123 229 | Write Something: 134 230 | 134 231 | Write Something: 2135 232 | 2135 233 | Write Something: 1 234 | 12 235 | Write Something: 35sldkjf 236 | 35sldkjf 237 | Write Something: sadlgk4 238 | sadlgk4 239 | Write Something: done 240 | >>> import time 241 | >>> n = 1 242 | >>> while True: 243 | print("Welcome", n, " times.") 244 | i += 1 245 | time.sleep(2) 246 | 247 | 248 | Welcome 1 times. 249 | Traceback (most recent call last): 250 | File "", line 3, in 251 | i += 1 252 | NameError: name 'i' is not defined 253 | >>> while True: 254 | print("Welcome", n, " times.") 255 | n += 1 256 | time.sleep(2) 257 | 258 | 259 | Welcome 1 times. 260 | Welcome 2 times. 261 | Welcome 3 times. 262 | Welcome 4 times. 263 | Welcome 5 times. 264 | Welcome 6 times. 265 | Welcome 7 times. 266 | Welcome 8 times. 267 | Welcome 9 times. 268 | Welcome 10 times. 269 | Welcome 11 times. 270 | Welcome 12 times. 271 | Welcome 13 times. 272 | Welcome 14 times. 273 | Welcome 15 times. 274 | Welcome 16 times. 275 | Welcome 17 times. 276 | Welcome 18 times. 277 | Welcome 19 times. 278 | Welcome 20 times. 279 | Welcome 21 times. 280 | Welcome 22 times. 281 | Welcome 23 times. 282 | Welcome 24 times. 283 | Welcome 25 times. 284 | Welcome 26 times. 285 | Welcome 27 times. 286 | Welcome 28 times. 287 | Welcome 29 times. 288 | Welcome 30 times. 289 | Welcome 31 times. 290 | Welcome 32 times. 291 | Welcome 33 times. 292 | Welcome 34 times. 293 | Welcome 35 times. 294 | Welcome 36 times. 295 | Traceback (most recent call last): 296 | File "", line 4, in 297 | time.sleep(2) 298 | KeyboardInterrupt 299 | >>> while True: 300 | line = input("Write Something") 301 | if line[0] == "#": 302 | continue 303 | if line == "done": 304 | break 305 | print(line) 306 | 307 | 308 | Write Something 1234 309 | 1234 310 | Write Something123 311 | 123 312 | Write Something# aksdjhjkahsdfasdkgj 313 | Write Somethingdone 314 | >>> for i in "Python": 315 | print(i) 316 | 317 | 318 | P 319 | y 320 | t 321 | h 322 | o 323 | n 324 | >>> for i in range(10): 325 | print("*") 326 | 327 | 328 | * 329 | * 330 | * 331 | * 332 | * 333 | * 334 | * 335 | * 336 | * 337 | * 338 | >>> for i in range(10): 339 | for j in range(5): 340 | print("*") 341 | 342 | 343 | * 344 | * 345 | * 346 | * 347 | * 348 | * 349 | * 350 | * 351 | * 352 | * 353 | * 354 | * 355 | * 356 | * 357 | * 358 | * 359 | * 360 | * 361 | * 362 | * 363 | * 364 | * 365 | * 366 | * 367 | * 368 | * 369 | * 370 | * 371 | * 372 | * 373 | * 374 | * 375 | * 376 | * 377 | * 378 | * 379 | * 380 | * 381 | * 382 | * 383 | * 384 | * 385 | * 386 | * 387 | * 388 | * 389 | * 390 | * 391 | * 392 | * 393 | >>> i = 1 394 | >>> for i in range(10): 395 | print(i) 396 | i += 1 397 | 398 | 399 | 0 400 | 1 401 | 2 402 | 3 403 | 4 404 | 5 405 | 6 406 | 7 407 | 8 408 | 9 409 | >>> for a in range(10): 410 | print(a) 411 | 412 | 413 | 0 414 | 1 415 | 2 416 | 3 417 | 4 418 | 5 419 | 6 420 | 7 421 | 8 422 | 9 423 | >>> list_ = [1,2,3,4,5,6] 424 | >>> for i in list_: 425 | print(i) 426 | 427 | 428 | 1 429 | 2 430 | 3 431 | 4 432 | 5 433 | 6 434 | >>> for i in list_: 435 | print(i, end = " ") 436 | 437 | 438 | 1 2 3 4 5 6 439 | >>> for i in list_: 440 | if list_[i] == 1: 441 | continue 442 | print(i) 443 | 444 | 445 | 1 446 | 2 447 | 3 448 | 4 449 | 5 450 | Traceback (most recent call last): 451 | File "", line 2, in 452 | if list_[i] == 1: 453 | IndexError: list index out of range 454 | >>> for i in list_: 455 | if i == 1: 456 | continue 457 | print(i) 458 | 459 | 460 | 2 461 | 3 462 | 4 463 | 5 464 | 6 465 | >>> 466 | -------------------------------------------------------------------------------- /Week 3/Programming_Concepts_Week_3.md: -------------------------------------------------------------------------------- 1 | # Programming Concepts - Week 3 2 | 3 | > This file is all about practice. Writing all practices by yourself will improve your understanding in Python. Also I will put here more detailed, and somehow advanced examples, so you can challenge yourself practicing on them. 4 | 5 | --- 6 | 7 | ## Boolean Operators 8 | There are only three basic Boolean operators: and, or, and not. not operator has the highes precedence, followed by and, followed by or. 9 | not operator works as a negation 10 | ```Python 11 | not True 12 | # False 13 | 14 | not False 15 | # True 16 | ``` 17 | 18 | It is like logic, all about 1s, and 0s. Trues, Falses. 19 | 20 | - and operator 21 | 22 | ```Python 23 | True and True 24 | # True 25 | 26 | False and False 27 | # False 28 | 29 | True and False 30 | # False 31 | 32 | False and True 33 | # False 34 | 35 | ``` 36 | 37 | - or operator 38 | 39 | ```Python 40 | True or True 41 | # True 42 | 43 | False or False 44 | # False 45 | 46 | True or False 47 | # True 48 | 49 | False or True 50 | # True 51 | ``` 52 | 53 | 54 | Following concept is very deep and if you want to deal with machines for future also important. 55 | 56 | ### Building and Exclusive Or Expression 57 | If you want an exclusive or, you need to build a Boolean expression for it. We'll walk through the development of this expression. 58 | 59 | Let's say you have two Boolean variables, b1 and b2, and you want an expression that evaluates to True if and only if exactly one of them is True. Evaluation of b1 and not b2 will produce True if b1 is True and b2 is False. Similarly, evaluation of b2 and not b1 will produce True if b2 is True and b1 is False. 60 | 61 | It isn't possible for both of these expressions to produce True. Also, if b1 and b2 are both True or both False, both expressions will evaluate to False. We can, therefore, combine the two expressions with an or: 62 | 63 | ```Python 64 | b1 = False 65 | b2 = False 66 | (b1 and not b2) or (b2 and not b1) 67 | # False 68 | 69 | b1 = False 70 | b2 = True 71 | (b1 and not b2) or (b2 and not b1) 72 | # True 73 | 74 | b1 = True 75 | b2 = False 76 | (b1 and not b2) or (b2 and not b1) 77 | # True 78 | 79 | b1 = True 80 | b2 = True 81 | (b1 and not b2) or (b2 and not b1) 82 | # False 83 | ``` 84 | --- 85 | 86 | But usually we don't use boolean operators and boolean expressions as it is. We use them to represent our daily problems solutions. 87 | 88 | ```Python 89 | cold = True 90 | windy = False 91 | (not cold) and windy 92 | # False 93 | 94 | not(cold and windy) 95 | # True 96 | ``` 97 | 98 | ## Comparison Operators 99 | Typically, we don't use boolean operators and boolean expressions as it is. Comparison operators and ther usage will result boolean results. 100 | ```Python 101 | > # Greater than 102 | < # Less than 103 | >= # Greater than or equal to 104 | <= # Less than or equal to 105 | == # Equal to 106 | != # Not equal to 107 | ``` 108 | 109 | All relational operators are binary operators: they compare two values and produce True or False as appropriate. 110 | 111 | ```Python 112 | 45 > 34 113 | # True 114 | 115 | 45 > 79 116 | # False 117 | 118 | 45 < 79 119 | # True 120 | 121 | 45 < 34 122 | # False 123 | ``` 124 | We can compare integers to floating-point numbers with any of the relational operators. Integers are automatically converted to floating point when we do this, 125 | 126 | ```Python 127 | 23.1 >= 23 128 | # True 129 | 130 | 23.1 <= 23 131 | # False 132 | ``` 133 | 134 | The same holds for "equal to" and "not equal to": 135 | ```Python 136 | 67.3 == 87 137 | # False 138 | 139 | 67.3 == 67 140 | # False 141 | 142 | 67.0 == 67 143 | # True 144 | 145 | 67.2 != 67 146 | # True 147 | ``` 148 | 149 | ### Combining Comparisons 150 | There are some rule when we combine them. 151 | * Arithmetic operators have higher precedence than relational operators. For example, + and / are evaluated before < or >. 152 | * Relational operators have higher precedence than Boolean operators. For example, comparisons are evaluated before and, or, and not. 153 | * All relational operators have the same precedence. 154 | 155 | ```Python 156 | x = 5 157 | y = 10 158 | z = 20 159 | 160 | (x < y) and (y < z) 161 | # True 162 | 163 | x = 3 164 | (1 < x) and (x <= 5) 165 | # True 166 | 167 | x = 7 168 | (1 < x) and (x <= 5) 169 | # False 170 | ``` 171 | We can also chain the comparisons: 172 | 173 | ```Python 174 | x = 3 175 | 1 < x <= 5 176 | # True 177 | 178 | 3 < 5 != True 179 | # True 180 | 181 | 3 < 5 != False 182 | # True 183 | ``` 184 | --- 185 | 186 | ### Comparing Strings 187 | It's possible to compare strings just as you would compare numbers. The characters in strings are represented by integers: a capital A, for example, is represented by 65, while a space is 32, and a lowercase z is 172. This encoding is called ASCII, which stands for "American Standard Code for Information Interchange." 188 | 189 | > One of its quirks is that all the uppercase letters 190 | come before all the lowercase letters, so a capital Z is less than a small a. 191 | 192 | One of the most common reasons to compare two strings is to decide which one comes first alphabetically. It may be very useful for some problems that you will face during this class... 193 | 194 | ```Python 195 | 'A' < 'a' 196 | # True 197 | 198 | 'A' > 'z' 199 | # False 200 | 201 | 'abc' < 'abd' 202 | # True 203 | 204 | 'abc' < 'abcd' 205 | # True 206 | ``` 207 | 208 | --- 209 | 210 | ## Chosing which statements to Execute 211 | An if statement lets you change how your program behaves based on a condition. The general form of an if statement is as follows: 212 | 213 | > if <>: 214 | <> 215 | 216 | The condition is an expression, such as color != "neon green" or x < y, as we seen before. 217 | 218 | * if must be indented! 219 | 220 | __Remainder:__ Python uses four spaces to indent. 221 | 222 | If the condition is true, the statements in the block are executed; otherwise, they are not. As with functions, the block of statements must be indented to show that it belongs to the if statement. If you don't indent properly, Python might raise an error, or worse, might happily execute the code that you wrote but do something you didn't intend because some statements were not indented properly. We'll briefly explore both problems in this chapter. 223 | 224 | Here is a table of solution categories based on pH level: 225 | 226 | * 0-4 Strong Acid 227 | * 5-6 Weak Acid 228 | * 7 Neutral 229 | * 8-9 Weak Base 230 | * 10-14 Strong Base 231 | 232 | > Before we start to exercise on if-else statements there is one important built-in function to mentioned 233 | 234 | --- 235 | 236 | ### Asking input from a user 237 | input() function takes an input from the user. you can use this function in various ways. 238 | 239 | ```Python 240 | input("Give me a string:") 241 | string 242 | # 'string' 243 | ``` 244 | 245 | input() function does not automatically return to an integer 246 | ```Python 247 | input("Give me an integer: ") 248 | 1 249 | # '1' 250 | ``` 251 | As you can see it retured to '1' which is also string. To make the result integer or float we need to use one more function either eval(input()) or int(input()), float(input()) 252 | ```Python 253 | eval(input("What is the temperature outside in celcius: ")) 254 | 25 255 | # 25 256 | 257 | # To check if it is integer or string... 258 | type(eval(input())) 259 | 25 260 | # 261 | 262 | int(input("What is the temperature outside in celcius: ")) 263 | 25 264 | # 25 265 | 266 | ## For floats eval() also work or float() 267 | eval(input("What is the temperature outside in fahrenheit: ")) 268 | 75.2 269 | # 75.2 270 | 271 | float(input("What is the temperature outside in fahrenheit: ")) 272 | 75.2 273 | # 75.2 274 | ``` 275 | 276 | --- 277 | Now we can come back to our main topic... 278 | 279 | 280 | We can use an if statement to print a message only when the pH level given by the program's user is acidic: 281 | 282 | ```Python 283 | ph = float(input('Enter the pH level: ')) 284 | Enter the pH level: 6.0 285 | if ph < 7.0: 286 | print(ph, "is acidic.") 287 | 288 | # 6.0 is acidic 289 | ``` 290 | 291 | ```Python 292 | ph = float(input('Enter the pH level: ')) 293 | Enter the pH level: 8.0 294 | if ph < 7.0: 295 | print(ph, "is acidic".) 296 | 297 | print("You should be careful with that!") 298 | # You should be careful with that! 299 | ``` 300 | 301 | ```Python 302 | ph = float(input('Enter the pH level: ')) 303 | Enter the pH level: 8.5 304 | if ph < 7.0: 305 | print(ph, "is acidic.") 306 | if ph > 7.0: 307 | print(ph, "is basic.") 308 | 309 | # 8.5 is basic 310 | ``` 311 | --- 312 | 313 | ### Two way selection 314 | Instead of using conditional statements like that we use if-else way. We need to merge the two cases in the example above and make them if- else 315 | 316 | ```Python 317 | ph = float(input('Enter the pH level: ')) 318 | Enter the pH level: 8.5 319 | if ph < 7.0: 320 | print(ph, "is acidic.") 321 | else: 322 | print(ph, "is basic.") 323 | 324 | # 8.5 is basic 325 | ``` 326 | As you can see example above, we don't have to put a condition in else brach, because it automatically takes all case left from the if brach. 327 | 328 | But there is something missing, we know from chemistry that 7.0 is neutral but in our case, let's see what will print out if we put 7.0 329 | ```Pyhthon 330 | ph = float(input('Enter the pH level: ')) 331 | Enter the pH level: 7.0 332 | if ph < 7.0: 333 | print(ph, "is acidic.") 334 | else: 335 | print(ph, "is basic.") 336 | 337 | # 7.0 is basic 338 | ``` 339 | Okay! this is definetly wrong. 340 | 341 | ### Multi-way selection 342 | We can increase the number of branches by using elif statements. 343 | ```Python 344 | ph = float(input('Enter the pH level: ')) 345 | Enter the pH level: 7.0 346 | if ph < 7.0: 347 | print(ph, "is acidic.") 348 | elif ph == 7.0: 349 | print(ph, "is neutral.") 350 | else: 351 | print(ph, "is basic.") 352 | 353 | # 7.0 is neutral 354 | ``` 355 | Know we got the wanted result. let's work on something interesting like compound finding... 356 | ```Python 357 | compound = input('Enter the compound: ') 358 | Enter the compound: H2SO4 359 | if compound == "H20": 360 | print("Water") 361 | elif compound == "NH3": 362 | print("Ammonia") 363 | elif compound == "CH4": 364 | print("Methane") 365 | elif compound == "H2SO4": 366 | print("Sulfuric Acid") 367 | else: 368 | print("Unknown-Compound") 369 | 370 | # Sulfuric Acid 371 | ``` 372 | --- 373 | 374 | ### Nested If statements 375 | An if statement's block can contain any type of Python statement, which implies that it can include other if statements. An if statement inside another is called a nested if statement. 376 | 377 | ```Python 378 | value = input('Enter the pH level: ') 379 | if len(value) > 0: 380 | ph = float(value) 381 | if ph < 7.0: 382 | print(ph, "is acidic.") 383 | elif ph > 7.0: 384 | print(ph, "is basic.") 385 | else: 386 | print(ph, "is neutral.") 387 | else: 388 | print("No pH value was given!") 389 | ``` 390 | In the case above, we ask the user to provide a pH value, which we'll initially receive as __a string.__ The first, or outer, _if_ statement checks whether the user typed something, which determines whether we examine the value of _pH_ with the __inner__ _if_ statement. (If the user didn't enter a number, then function call _float(value)_ will produce a _ValueError._) 391 | 392 | --- 393 | 394 | ## Executing Statements Repeatedly 395 | 396 | ### While Statement 397 | Python's while statement is the most general iteration construct in the language. In simple terms, it repeatedly executes a block of (normally indented) statements as long as a test at the top keeps evaluating to a true value. It is called a "loop" because control keeps looping back to the start of the statement until the test becomes false. When the test becomes false, control passes to to another statement which follows the while loop. 398 | 399 | > while test: # Loop test 400 | statements # Loop body 401 | else: # Optional else 402 | statements # Run if didn't exit loop with break 403 | We don't usually use else for while loop, but I would like to put it the definition to make everything clear about while. 404 | 405 | Let's write a little program to count number from value x to y... 406 | ```Python 407 | x = 0 408 | y = 10 409 | while x < y : # it does not count y, <= counts y 410 | print(a, end = " ") 411 | a = a + 1 412 | ``` 413 | end argument in print function just adds them in one line, other wise they will be printed in different line each time. 414 | 415 | This is an example of an infinite loop, it goes to infinity unless you interrupt. Ctrl-C key combination to forcibly terminate one 416 | ```Python 417 | while True: 418 | print("Ctrl-C to stop infinite loop!") 419 | # This example will looping until you stop the loop with ctrl-c 420 | ``` 421 | --- 422 | There are some statements which have purpose in only loop structure. 423 | 424 | #### break 425 | It jumps out of the closes enclosing loop(it passes the entire loop statement). The break statement causes an immediate exit from a loop. Because the code that follows it in the loop is not executed if the break is reached, you can also sometimes avoid nesting by including a break. 426 | 427 | This piece of code actually count up to 10 with using infinite loop and break statement 428 | ```Python 429 | count = 1 430 | while True: 431 | print(count) 432 | count = count + 1 433 | if count == 10: 434 | break 435 | ``` 436 | This one is keep asking name and age until we put stop to name 437 | ```Python 438 | while True: 439 | name = input('Enter name:') 440 | if name == 'stop': break 441 | age = input('Enter age: ') 442 | print('Hello', name, '=>', int(age) ** 2) 443 | ``` 444 | 445 | --- 446 | 447 | #### continue 448 | The continue statement causes an immediate jump to the top of a loop. 449 | 450 | This example uses continue to skip odd numbers. This code prints all even numbers less than 10 and greater than or equal to 0. 451 | ```Python 452 | x = 10 453 | while x: 454 | x = x - 1 455 | if x % 2 != 0: continue ## If number is odd skip printing. 456 | print(x, end = " ") 457 | ``` 458 | --- 459 | 460 | #### pass 461 | the pass statement is a no-operation placeholder that is used when the syntax requires a statement, but you have nothing useful to say. It is often used to code an empty body for a compound statement. 462 | 463 | ```Python 464 | while True: 465 | pass ## It does nothing but it also keep program inside the loop 466 | ## To interrupt remember Ctrl-C 467 | ``` 468 | --- 469 | 470 | #### loop else 471 | When combined with the loop else clause, the break statement can often eliminate the need for the search status flags 472 | 473 | For instance, the following piece of code determines whether a positive integer y is prime by searching for factors greater than 1: 474 | ```Python 475 | x = y // 2 476 | while x > 1: 477 | if y % x == 0: 478 | print(y, 'has factor', x) 479 | break 480 | x = x - 1 481 | else: 482 | print(y , 'is prime') 483 | ``` 484 | Because the loop else clause is unique to Python, it tends to perplex some newcomers In general terms, the loop else simply provides explicit syntax for a common coding scenario-it is a coding structure that lets us catch the "other" way out of a loop, without setting and checking flags or conditions. 485 | 486 | --- 487 | 488 | ### for loops 489 | The for loop is a generic iterator in Python: it can step through the items in any ordered sequence or other iterable object. 490 | 491 | > for target in object: # Assign object items to target 492 | statements # Repeated loop body: use target 493 | else: # Optional else part 494 | statements # If we didn't hit a 'break' 495 | 496 | Note that for loop has great usage in lists but since we did not mentioned list yet, we will work on list iteration later on when we see lists. 497 | 498 | ```Python 499 | s = "lumberjack" 500 | for i in S: 501 | print(i, end = " ") # Iteration over a string. 502 | # l u m b e r j a c k 503 | ``` 504 | i represents just a name of a variable, which will be assigned objects each iteration. You can name it x, y, z, k ... 505 | 506 | Don't worry, if you did not understand the concept totally, because for now we did not cover everything about iteration. To finish it completely we need to finish other built-in data types as well. Study the exercises well you will get used to python's syntax. 507 | 508 | Thank you for your time, have a great learning! 509 | -------------------------------------------------------------------------------- /Week 3/Py101 - Week3 - Section1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Week 3/Py101 - Week3 - Section1.pdf -------------------------------------------------------------------------------- /Week 3/exercise_#2_conditions.md: -------------------------------------------------------------------------------- 1 | # Exercise #2 ~ Conditional Statements 2 | 3 | ## Part 1 4 | Find the correct results for following questions. If no result printed write __blank__. If an error appear just write an __error__. 5 | > You might want to use python interpreter to see things clearly. 6 | 7 | 1. 8 | ```Python 9 | if 8 > 7: 10 | print("Yep") 11 | ``` 12 | 2. 13 | ```Python 14 | if 6 > 7: 15 | print("Yep") 16 | else: 17 | print("Nope") 18 | ``` 19 | 3. 20 | ```Python 21 | var = 'Panda' 22 | if var == "panda": 23 | print("Cute!") 24 | elif var == "Panda": 25 | print("Regal!") 26 | else: 27 | print("Ugly...") 28 | ``` 29 | 4. 30 | ```Python 31 | temp = 120 32 | if temp > 85: 33 | print("Hot") 34 | elif temp > 100: 35 | print("REALLY HOT!") 36 | elif temp > 60: 37 | print("Comfortable") 38 | else: 39 | print("Cold") 40 | ``` 41 | 5. 42 | ```Python 43 | temp = 50 44 | if temp > 85: 45 | print("Hot") 46 | elif temp > 100: 47 | print("REALLY HOT!") 48 | elif temp > 60: 49 | print("Comfortable") 50 | else: 51 | print("Cold") 52 | ``` 53 | 6. 54 | ```Python 55 | money = 2000 56 | if money > 1000: 57 | print("I am rich!!") 58 | else: 59 | print("I'm not rich!!") 60 | print("But I might be later...") 61 | ``` 62 | --- 63 | 64 | ## Part 2 ~ Assignments 65 | 66 | 1. Write a piece of Python code that prints out the string 'hello world' if the value of an integer variable, happy, is strictly greater than 2. 67 | 68 | 2. Create an if statement that checks whether a number of Twinkies (in the variable twinkies) is less than 100 or greater than 500. Your program should print the message "Too few or too many" if the condition is true. 69 | 70 | 3. Create an if statement that checks whether the amount of money contained in the variable money is between 100 and 500 or between 1,000 and 5,000. 71 | 72 | 4. Create an _if_ statement that prints the string "That's too many" 73 | if the variable _ninjas_ contains a number that's less than 50, prints 74 | "It'll be a struggle, but I can take 'em" if it's less than 30, and 75 | prints "I can fight those ninjas!" if it's less than 10. 76 | 77 | 5. You want an automatic wildlife camera to switch on if the light level is less than 0.01 lux or if the temperature is above freezing, but not if both conditions are true. (You should assume that function ``` turn_camera_on ``` has already been defined.) 78 | Your first attempt to write this is as follows: 79 | ```Python 80 | if (light < 0.01) or (temperature > 0.0): 81 | if not ((light < 0.01) and (temperature > 0.0)): 82 | turn_camera_on() 83 | ``` 84 | A friend says that this is an exclusive or and that you could write it more simply as follows: 85 | ```Python 86 | if (light < 0.01) != (temperature > 0.0): 87 | turn_camera_on() 88 | ``` 89 | Is your friend right? If so, explain why. If not, give values for light and temperature that will produce different results for the two fragments of code. 90 | 91 | 6. Variable _x_ refers to a number. Write an expression that evaluates to _True_ if _x_ and its absolute value are equal and evaluates to _False_ otherwise. Assign the resulting value to a variable named _result_. 92 | 93 | 7. Assume we want to print a strong warning message if a pH value is below 3.0 and otherwise simply report on the acidity. We try this if statement: 94 | ```Python 95 | ph = 2 96 | if ph < 7.0: 97 | print(ph, "is acidic.") 98 | elif ph < 3.0: 99 | print(ph, "is VERY acidic! Be careful.") 100 | # 2 is acidic 101 | ``` 102 | This prints the wrong message when a pH of 2 is entered. What is the 103 | problem, and how can you fix it? 104 | 105 | -------------------------------------------------------------------------------- /Week 3/exercise_#2_iteration.md: -------------------------------------------------------------------------------- 1 | # Exercise #2 ~ Iteration 2 | --- 3 | 4 | ### Note for Success: 5 | > If you want to learn the concepts clearly, put comments around your code. Examine my GitHub account the see how comment using makes the difference. Try to examine the exercises above, they are very similar to each other. Please note their differences and see why they differ. This approach will help you to understand the concepts more... 6 | 7 | ## Part 1 8 | Find the correct results for following questions. If no result printed write __blank__. If an error appear just write an __error__. If result won't stop evaluating write __infinite__. 9 | 10 | 1. 11 | ```Python 12 | total = 0 13 | while sum < 5: 14 | print(sum) 15 | total = total + 1 16 | ``` 17 | 2. 18 | ```Python 19 | sum = 0 20 | current = 1 21 | n = eval(input()) 22 | while current <= n: 23 | sum = sum + current 24 | current = current + 1 25 | ``` 26 | 3. 27 | ```Python 28 | sum = 0 29 | current = 1 30 | n = eval(input()) 31 | while current <= n: 32 | sum = sum + current 33 | current = current + 1 34 | print(sum) 35 | ``` 36 | 4. 37 | ```Python 38 | sum = 0 39 | current = 1 40 | n = eval(input()) 41 | while current <= n: 42 | sum = sum + current 43 | current = current + 1 44 | print(sum) 45 | ``` 46 | 5. 47 | ```Python 48 | while True: 49 | print("Looooooping....") 50 | ``` 51 | 6. 52 | ```Python 53 | n = 10 54 | sum = 0 55 | current = 1 56 | while current <= n: 57 | sum = sum + current 58 | n = n - 1 59 | print(sum) 60 | ``` 61 | 7. 62 | ```Python 63 | n = 10 64 | sum = 0 65 | current = 1 66 | while current <= n: 67 | sum = sum + current 68 | print(sum) 69 | ``` 70 | --- 71 | 72 | ## Part 2 73 | 74 | 1. Write a code which has the following attributes: 75 | 76 | - Takes two random single digit integer; number1 and number2 77 | - Ask user to put the answer of subtraction of number1 and number2 78 | - Use looping concept to repeatedly ask if user puts wrong answer 79 | 80 | __Sample output:__ 81 | What is 4 - 3? _4_ 82 | Wrong answer. Try again. What is 4 - 3? _5_ 83 | Wrong answer. Try again. What is 4 - 3? _1_ 84 | You got it! 85 | 86 | 2. Write a Guessing Number code, here are the instructions: 87 | 88 | - Get a random number 89 | - Ask a guess of a number until user finds the random number: "Enter a guess: " 90 | - use some hints: 91 | - If guess is higher then the number: "Your guess is too high!" 92 | - If guess is lower then the number: "Your guess is too low!" 93 | - If user find the number: "You have found it!" 94 | 95 | --- 96 | 97 | ## Part 3 98 | Find the correct results for following questions. If no result printed write __blank__. If an error appear just write an __error__. If result won't stop evaluating write __infinite__. 99 | 100 | 1. 101 | ```Python 102 | LetterNum = 1 103 | for Letter in "Howdy!": 104 | if Letter == "w": 105 | continue 106 | print("Encountered w, not processed.") 107 | print("Letter ", LetterNum, " is ", Letter) 108 | LetterNum += 1 109 | ``` 110 | 111 | 2. 112 | ```Python 113 | Value = input("Type less than 6 characters: ") 114 | LetterNum = 1 115 | for Letter in Value: 116 | print("Letter ", LetterNum, " is ", Letter) 117 | LetterNum += 1 118 | if LetterNum > 6: 119 | print("The string is too long!") 120 | break 121 | ``` 122 | 123 | 3. 124 | ```Python 125 | LetterNum = 1 126 | for Letter in "Howdy!": 127 | if Letter == "w": 128 | pass 129 | print("Encountered w, not processed.") 130 | print("Letter ", LetterNum, " is ", Letter) 131 | LetterNum += 1 132 | ``` 133 | 134 | 4. 135 | ```Python 136 | Value = input("Type less than 6 characters: ") 137 | LetterNum = 1 138 | 139 | for Letter in Value: 140 | print("Letter ", LetterNum, " is ", Letter) 141 | LetterNum+=1 142 | else: 143 | print("The string is blank.") 144 | ``` 145 | 146 | 5. 147 | ```Python 148 | number = 0 149 | sum = 0 150 | for count in range(5): 151 | number = eval(input("Enter an integer: ")) 152 | sum += number 153 | print("sum is", sum) 154 | print("count is", count) 155 | ``` 156 | 157 | 6. 158 | ```Python 159 | sum = 0 160 | for i in range(1001): 161 | sum = sum + i 162 | ``` 163 | 164 | 7. 165 | ```Python 166 | school = 'North American University' 167 | numVowels = 0 168 | numCons = 0 169 | 170 | for char in school: 171 | if char == 'a' or char == 'e' or char == 'i' \ 172 | or char == 'o' or char == 'u': 173 | numVowels += 1 174 | elif char == 'o' or char == 'M': 175 | print(char) 176 | else: 177 | numCons -= 1 178 | 179 | print('numVowels is: ' + str(numVowels)) 180 | print('numCons is: ' + str(numCons)) 181 | ``` 182 | --- 183 | 184 | ## Part 4 185 | 186 | 1. Convert the following into code that uses a for loop 187 | print 2
188 | print 4
189 | print 6
190 | print 8
191 | print 10
192 | print Goodbye!
193 | 194 | 2. Convert the following into code that uses a for loop. 195 | 196 | print Hello!
197 | print 10
198 | print 8
199 | print 6
200 | print 4
201 | print 2
202 | 203 | 3. Write a multiplication table using for loop, 9x9 (Force your imagination...) 204 | Output: 205 | Multiplication Table 206 | 207 |      1 2 3 4 5 6 7 8 9
208 | ------------------------------
209 | 1 | 1 2 3 4 5 6 7 8 9
210 | 2 | 2 4 6 8 10 12 14 16 18
211 | 3 | 3 6 9 12 15 18 21 24 27
212 | 4 | 4 8 12 16 20 24 28 32 36
213 | 5 | 5 10 15 20 25 30 35 40 45
214 | 6 | 6 12 18 24 30 36 42 48 54
215 | 7 | 7 14 21 28 35 42 49 56 63
216 | 8 | 8 16 24 32 40 48 56 64 72
217 | 9 | 9 18 27 36 45 54 63 72 81
218 | -------------------------------------------------------------------------------- /Week 4/Functions_Practical_Programming.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 22 04:16:01 2015 4 | 5 | @author: Enes Kemal Ergin 6 | 7 | Functions by Practical Programming 8 | """ 9 | def convert_to_celcius(fahrenheit): 10 | return (fahrenheit - 32) * 5 /9 11 | 12 | # Test 13 | print(convert_to_celcius(80)) 14 | 15 | # Quadratic equation solver in a*x^2+b*x+c 16 | def quadratic(a,b,c,x): 17 | first = a * x ** 2 18 | second = b * x 19 | third = c 20 | return first + second + third 21 | 22 | # Tests 23 | print(quadratic(2,3,4,0.5)) 24 | print(quadratic(2,3,4,1.5)) 25 | -------------------------------------------------------------------------------- /Week 4/GPA_calculation_program_function.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 22 03:40:53 2015 4 | 5 | @author: Enes Kemal Ergin 6 | 7 | Function GPA calculation Program 8 | """ 9 | 10 | # Let's Create a GPA calculator. 11 | def convertGrade(grade): 12 | if grade == 'F': 13 | return 0 14 | else: 15 | return 4 - (ord(grade) - ord('A')) 16 | 17 | def getGrades(): 18 | semester_info = [] 19 | more_grades = True 20 | empty_str = "" 21 | while more_grades: 22 | course_grade = input("Enter grade:") 23 | while course_grade not in ("A", "B", "C", "D", "F", empty_str): 24 | course_grade = input("Enter letter grade received: ") 25 | if course_grade == empty_str: 26 | more_grades = False 27 | else: 28 | num_credits = int(input("Enter number of credits: ")) 29 | semester_info.append([num_credits, course_grade]) 30 | 31 | def calculateGPA(sem_grades_info, cumm_gpa_info): 32 | sem_quality_pts = 0 33 | sem_credits = 0 34 | current_cumm_gpa, total_credits = cumm_gpa_info 35 | 36 | for k in range(len(sem_grades_info)): 37 | num_credits, letter_grade = sem_grades_info[k] 38 | 39 | sem_quality_pts = sem_quality_pts + num_credits * convertGrade(letter_grade) 40 | 41 | sem_credits = sem_credits + num_credits 42 | 43 | sem_gpa = sem_quality_pts / sem_credits 44 | new_cumm_gpa = (current_cumm_gpa * total_credits + sem_gpa * sem_credits) / (total_credits + sem_credits) 45 | return (sem_gpa, new_cumm_gpa) 46 | 47 | # Program Greeting 48 | print("This program calculates new semester and cummulative GPAs\n") 49 | 50 | # get current GPA info 51 | total_credits = int(input("Enter total number of earned credits: ")) 52 | cumm_gpa = float(input("Enter your current cummulative GPA: ")) 53 | cumm_gpa_info = (cumm_gpa, total_credits) 54 | 55 | # get current semester grade info 56 | print() 57 | semester_grades = getGrades() 58 | 59 | # Calculate semester gpa and new cummulative gpa 60 | semester_gpa, cumm_gpa = calculateGPA(semester_grades, cumm_gpa_info) 61 | 62 | # Display semester gpa and new cummulative gpa 63 | print("\nYour semester GPA is", format(semester_gpa, ".2f")) 64 | print("Your new cummulative GPA is", format(cumm_gpa, ".2f")) 65 | 66 | """ This program calculates semester and cumulative GPAs 67 | 68 | Enter total number of earned credits: 30 69 | Enter your current cumulative GPA: 3.25 70 | 71 | Enter Grade: A 72 | Enter number of Credits: 4 73 | Enter Grade: A 74 | Enter number of Credits: 3 75 | Enter Grade: B 76 | Enter number of Credits: 3 77 | Enter Grade: B 78 | Enter number of Credits: 3 79 | Enter Grade: A 80 | Enter number of Credits: 3 81 | Enter Grade: 82 | 83 | Your semester GPA is 3.62 84 | Your new cumulative GPA is 3.38 85 | """ -------------------------------------------------------------------------------- /Week 4/Programming_Concepts_Week_4.md: -------------------------------------------------------------------------------- 1 | # Programming Concepts - Week 4 2 | 3 | > This file is all about practice. Writing all practices by yourself will improve your understanding in Python. Also I will put here more detailed, and somehow advanced examples, so you can challenge yourself practicing on them. 4 | 5 | --- 6 | 7 | ## List Basics 8 | Concept of a list inside the Python is pretty similar to list in real life.We read off (access) items on our to-do list, add items, cross off (delete) items, and so forth. list is a linear data structure , meaning that its elements have a linear ordering. 9 | 10 | * Each item in the list is identifi ed by its index value . 11 | * It is customary in programming languages to begin numbering sequences of items with an index value of 0 rather than 1. (Except R language) 12 | 13 | ```Python 14 | ## Following examples are all types of creating lists 15 | list1 = list() # Creates an empty list 16 | list2 = list([2,3,4]) # Creates a list with elements 2,3,4 17 | list3 = list(["red", "green", "blue"]) # Creates a list with strings 18 | list4 = list(range(3,6)) # Creates a list with elements 3,4,5 19 | list5 = list("abcs") # Creats a list with characters a,b,c,d 20 | 21 | ## These are also creates lists 22 | ## I prefer to use this versions... 23 | list1 = [] 24 | list2 = [2,3,4] 25 | list3 = ["red", "green"] 26 | 27 | ## Lists can have different types of object in one list. 28 | 29 | list4 = [2, "three", True] 30 | ``` 31 | 32 | > Here is the list of Common operations of list. 33 | 34 | Operation | Description 35 | ---------- | -------------- 36 | x in s | True if element x is in sequence s. 37 | x not in s | True if element x is not in sequence s. 38 | s1 + s2 | Concatenates two sequences s1 and s2. 39 | s * n, n * s n| copies of sequence s concatenated. 40 | s[i] | ith element in sequence s. 41 | s[i : j] | Slice of sequence s from index i to j - 1. 42 | len(s) | Length of sequence s, i.e., the number of elements in s. 43 | min(s) | Smallest element in sequence s. 44 | max(s) | Largest element in sequence s. 45 | sum(s) | Sum of all numbers in sequence s. 46 | for loop | Traverses elements from left to right in a for loop. 47 | <, <=, >, >=, =, != | Compares two sequences. 48 | 49 | --- 50 | 51 | ### Functions for Lists 52 | There are some functions which are very useful when you are dealing with lists.You can use the __len__ function to return the number of elements in the list, the __max/min__ functions to return the elements with the greatest and lowest values in the list, and the __sum__ function to return the sum of all elements in the list. You can also use the __shuffle__ function in the _random_ module to shuffle the elements randomly in the list. 53 | 54 | ```Python 55 | list1 = [2, 3, 4, 1, 32] 56 | len(list) # Returns the size/length of the list 57 | # 5 58 | 59 | max(list1) # Returns the max element in the list 60 | # 32 61 | 62 | min(list1) # Returns the min element in the list 63 | # 1 64 | 65 | sum(list) # Takes the summation of all elements in the list. 66 | # 42 67 | 68 | import random # We will need this lib to use shuffle() 69 | random.shuffle(list1) # Shuffle the elements in list 70 | list1 71 | # [4,1, 2, 32, 3] 72 | ``` 73 | 74 | ### Index Operator [] 75 | An element in a list can be accessed through the index operator, using the syntax: myList[index]. myList[index] can be used as variable and for variables can be added together: ```myList[2] = myList[0] + myList[1]``` 76 | 77 | Using For loop reach every element in the list easily 78 | ```Python 79 | for i in range(len(myList) - 1): # Don't forget to put - 1 because of indexation and scope of the loop rules... 80 | myList[i] = i 81 | 82 | ## OR Same for While 83 | i = 0 84 | while i < len(myList): 85 | print(myList[i]) 86 | i += 1 87 | ``` 88 | 89 | Python Also uses negative numbers as a indexes to reference positions relative to the end of the list. 90 | 91 | ```Python 92 | list1 = [2, 3, 5, 2, 33, 21] 93 | list1[-1] 94 | # 21 95 | 96 | list1[-3] 97 | # 2 98 | ``` 99 | list[-1] is actually same as list1[-1 + len(list1)], which give s the last element in the list. 100 | 101 | ### List Slicing [start: end] 102 | The slicing operator returns a slice of the list using the syntax list[start : end]. The slice is a sublist from index start to index end - 1. Here are some examples: 103 | 104 | ```Python 105 | list1 = [2, 3, 5, 7, 9, 1] 106 | list1[2 : 4] 107 | # [5, 7] 108 | 109 | list1 = [2, 3, 5, 2, 33, 21] 110 | list1[ : 2] 111 | # [2, 3] 112 | 113 | list1[3 : ] 114 | # [2, 33, 21] 115 | 116 | list1 = [2, 3, 5, 2, 33, 21] 117 | list1[1 : -3] 118 | # [3, 5] 119 | 120 | list1[-4 : -2] 121 | # [3, 5] 122 | ``` 123 | > If start >= end, list[start : end] returns an empty list. If end specifies a position beyond the end of the list, Python will use the length of the list for end instead. 124 | 125 | ### The +/* and in/not in operators 126 | We can use concatenation operator (+), and repetition operator (*) for lists. 127 | ```Python 128 | list1 = [2, 3] 129 | list2 = [1, 9] 130 | list3 = list1 + list2 131 | list3 132 | # [2, 3, 1, 9] 133 | 134 | list4 = 3 * list1 135 | list4 136 | # [2, 3, 2, 3, 2, 3] 137 | 138 | list1 = [2, 3, 5, 2, 33, 21] 139 | 2 in list1 140 | # True 141 | 142 | 2 not in list1 143 | # False 144 | ``` 145 | 146 | ### range() function 147 | The standard way of using the ```range``` function is to give it a number to stop at, and ```range``` will give a list of values that start at 0 and go through the stop value minus 1. For example, calling ```range(stop)``` yields the following: 148 | ```Pyhon 149 | range(5) 150 | # [0,1,2,3,4] 151 | ``` 152 | However, we can call ```range``` with some additional, optional parameters - a value to start at, and a step size. You can specify a start value by calling ```range(start, stop)```, like this: 153 | ```Pyhton 154 | range(2, 5) 155 | # [2, 3, 4] 156 | ``` 157 | To specify a step size, you must specify a start value - the call is ```range(start, stop, stepSize)```, like this: 158 | ```Python 159 | range(2, 10, 2) 160 | # [2, 4, 6, 8] 161 | ``` 162 | 163 | ### Traversing Elements in a for loop 164 | The elements in a Python list are iterable. Python supports a convenient for loop, which enables you to traverse the list sequentially without using an index variable. 165 | ```Python 166 | ## "For each element i in myList, print it." 167 | for i in myList: 168 | print(i) 169 | ``` 170 | This version shows the elements at odd numbered positions. 171 | ```Python 172 | for i in range(0, len(myList), 2): 173 | print(myList[i]) 174 | ``` 175 | More examples on range function: 176 | ```Python 177 | >>> range(10) 178 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 179 | >>> range(1, 11) 180 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 181 | >>> range(0, 30, 5) 182 | [0, 5, 10, 15, 20, 25] 183 | >>> range(0, 10, 3) 184 | [0, 3, 6, 9] 185 | >>> range(0, -10, -1) 186 | [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] 187 | >>> range(0) 188 | [] 189 | >>> range(1, 0) 190 | [] 191 | ``` 192 | 193 | ### sum() function 194 | The function ```sum``` is a built-in function that takes one list as an argument and returns the sum of that list. The items in the list must be numeric types. Some examples: 195 | ```Python 196 | >>> sum([1, 9, 10]) 197 | 20 198 | >>> sum([4.5, 7, 0.331]) 199 | 11.831 200 | >>> sum(['a', 'b', 'c']) 201 | Traceback (most recent call last): 202 | File "", line 1, in 203 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 204 | ``` 205 | 206 | ### List Comprehensions 207 | List comprehensions provide a concise way to create a sequential list of elements. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The list comprehension produces a list with the results from evaluating the expression. 208 | 209 | ```Python 210 | list1 = [x for x in range(5)] # Returns a list of 0, 1, 2, 3, 4 211 | list1 212 | # [0, 1, 2, 3, 4] 213 | 214 | list2 = [0.5 * x for x in list1] 215 | list2 216 | # [0.0, 0.5, 1.0, 1.5, 2.0] 217 | 218 | list3 = [x for x in list2 if x < 1.5] 219 | list3 220 | # [0.0, 0.5, 1.0] 221 | ``` 222 | 223 | ### List Methods 224 | Once you have the list created, you can use list class's methods to manipulate the list.The list class contains methods for manipulating a list: 225 | 226 | Method Names | Description 227 | --------------------- ----------------------- 228 | append(x: object): None | Adds an element x to the end of the list. 229 | count(x: object): int | Returns the number of times element x appears in the list. 230 | extend(l: list): None | Appends all the elements in l to the list. 231 | index(x: object): int | Returns the index of the first occurrence of element x in the list. 232 | insert(index: int, x: object):None | Inserts an element x at a given index. Note that the first element in the list has index 0. 233 | pop(i): object | Removes the element at the given position and returns it. The parameter i is optional. If it is not specified, list.pop() removes and returns the last element in the list. 234 | remove(x: object): None | Removes the first occurrence of element x from the list. 235 | reverse(): None | Reverses the elements in the list. 236 | sort(): None | Sorts the elements in the list in ascending order. 237 | 238 | 239 | Examples of using; append, count, extend, index, and insert methods: 240 | ```Python 241 | list1 = [2,3,4,1, 32, 4] 242 | list.append(19) 243 | list1 244 | # [2,3,4,1,32,4,19] 245 | 246 | list1.count(4) # Return the count for number 4 247 | # 2 248 | 249 | list2 = [99, 54] 250 | list1.extend(list2) 251 | list1 252 | # [2, 3, 4, 1, 32, 4, 19, 99, 54] 253 | 254 | list1.index(4) # Return the index of number 4 255 | # 2 256 | 257 | list1.insert(1, 25) # Insert 25 at position index 1 258 | list1 259 | # [2, 25, 3, 4, 1, 32, 4, 19, 99, 54] 260 | ``` 261 | Examples of Using; insert, pop, remove, reverse, and sort methods: 262 | ```Python 263 | list1 = [2, 25, 3, 4, 1, 32, 4, 19, 99, 54] 264 | list1.pop(2) # Removes the element in the index 2 265 | 3 # Which is this one. 266 | 267 | list1 268 | # [2, 25, 4, 1, 32, 4, 19, 99, 54] 269 | 270 | list1.pop() 271 | # 54 272 | list1 273 | # [2, 25, 4, 1, 32, 4, 19, 99] 274 | 275 | list.remove(32) # Remove number 32 276 | list1 277 | # [2, 25, 4, 1, 4, 19, 99] 278 | 279 | list1.reverse() # Reverse the list 280 | list1 281 | # [99, 19, 4, 1, 4, 25, 2] 282 | 283 | list1.sort() # Sort the list 284 | list1 285 | # [1, 2, 4, 4, 19, 25, 99] 286 | ``` 287 | 288 | ### Splitting a String into a List 289 | This is an intermediate topic but also the essential one for text handling operations. The str class contains the split method, which is useful for splitting items in a string into a list. For example, the following statement: ``` items = "Jane John Peter Susan".split()``` splits the string Jane John Peter Susan into the list ['Jane', 'John', 'Peter', 'Susan']. 290 | 291 | * In the case above the items are delimited by spaces in the string. 292 | * You can use a nonspace delimeter ``` items = "02/08/15".split("/")``` splits the string 02/08/15 into the list ["02", "08", "15"] 293 | 294 | ### Inputting Lists 295 | You may often need code that reads data from the console into a list. You can enter one data item per line and append it to a list in a loop. For example, the following code reads ten numbers one per line into a list. 296 | ```Python 297 | lst = [] # Creates an empty list 298 | print("Enter 10 numbers: ") 299 | for i in range(10): 300 | lst.append(eval(input())) 301 | ``` 302 | Sometimes it is more convenient to enter the data in one line separated by spaces. You can use the string's split method to extract data from a line of input. For example, the following code reads ten numbers separated by spaces from one line into a list. 303 | ```Python 304 | # Reads numbers as a string from the console 305 | s = input("Enter 10 numbers separated by spaces from one line: ") 306 | items = s.split() # Extracts items from the string 307 | lst = [eval(x) for x in items] # Converts items to numbers 308 | ``` 309 | 310 | --- 311 | 312 | ## Functions 313 | Functions can be used to define reusable code and organize and simplify code.Suppose that you need to find the sum of integers from 1 to 10, 20 to 37, and 35 to 49. If you create a program to add these three sets of numbers, your code might look like this: 314 | 315 | ```Python 316 | sum = 0 317 | for i in range(1, 11): 318 | sum += i 319 | print("Sum from 1 to 10 is", sum) 320 | 321 | sum = 0 322 | for i in range(20, 38): 323 | sum += i 324 | print("Sum from 20 to 37 is", sum) 325 | 326 | sum = 0 327 | for i in range(35, 50): 328 | sum += i 329 | print("Sum from 35 to 49 is", sum) 330 | ``` 331 | It is pretty devastating, and think about it for more than 3. Let's try to write it in more usable way, using functions... 332 | ```Python 333 | # Defining a sum function 334 | def sum(n1, n2): 335 | result = 0 336 | for i in range(n1, n2 + 1): 337 | result += i 338 | return result 339 | 340 | # Defining main function invoke sum. 341 | def main(): 342 | print("Sum from 1 to 10 is", sum(1, 10)) 343 | print("Sum from 20 to 37 is", sum(20, 37)) 344 | print("Sum from 35 to 49 is", sum(35, 49)) 345 | 346 | main() # Calls the main function... 347 | ``` 348 | A function is a collection of statements grouped together that performs an operation. 349 | 350 | ### Defining a Function 351 | Function syntax is made of function's name, parameters, and body. The syntax fo defining a function is as follows: 352 | ```Python 353 | def functionName(list of parameters): 354 | # Function Body 355 | ``` 356 | Let's look at the function for finding max number: 357 | ```Python 358 | def max(num1, num2): # Function headers with 2 formal parameters. 359 | # Function body Starts from here 360 | if num1 > num2: 361 | result = num1 362 | else: 363 | result = num2 364 | return result # Return Value... 365 | 366 | # Invoke a function 367 | z = max(x, y) # X and Y are actual parameters(arguments) 368 | 369 | ``` 370 | 371 | --- 372 | 373 | ### Function with/without Return Values 374 | There can be some functions without return values, we call them void functions, but they have some side effects on the code... 375 | ```Python 376 | def printGrade(score): 377 | if score >= 90.0: 378 | print('A') 379 | elif score >= 80.0: 380 | print('B') 381 | elif score >= 70.0: 382 | print('C') 383 | elif score >= 60.0: 384 | print('D') 385 | else: 386 | print('F') 387 | 388 | def main(): 389 | score = eval(input("Enter a score: ")) 390 | print("The grade is ", end = " ") 391 | printGrade(score) 392 | 393 | main() # Call the main function 394 | ``` 395 | The code above does not have a return value, but we used it to call it into another function... What if we would like to have it with returns... 396 | ```Python 397 | def getGrade(score): 398 | if score >= 90.0: 399 | return 'A' 400 | elif score >= 80.0: 401 | return 'B' 402 | elif score >= 70.0: 403 | return 'C' 404 | elif score >= 60.0: 405 | return 'D' 406 | else: 407 | return 'F' 408 | 409 | def main(): 410 | score = eval(input("Enter a score: ")) 411 | print("The grade is", getGrade(score)) 412 | 413 | main() 414 | ``` 415 | The getGrade function returns a character, and it can be invoked and used just like a character. The printGrade function does not return a value, and it must be invoked as a statement. 416 | 417 | > Technically, every function in Python returns a value whether you use return or not. If a function does not return a value, by default, it returns a special value None. For this reason, a function that does not return a value is also called a None function. The None value can be assigned to a variable to indicate that the variable does not reference any object. For example, if you run the following program: 418 | ```Python 419 | def sum(number1, number2): 420 | total = number1 + number2 421 | print(sum(1,2)) 422 | ``` 423 | you will see the output is None, because the sum function does not have a return statement. By default, it returns None. 424 | 425 | --- 426 | 427 | Thank you for your time, have a great learning! 428 | 429 | 430 | -------------------------------------------------------------------------------- /Week 4/Py101 - Week4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Week 4/Py101 - Week4.pdf -------------------------------------------------------------------------------- /Week 4/convert_to_celcius.py: -------------------------------------------------------------------------------- 1 | def convert_to_celcius(fahrenheit): 2 | return (fahrenheit - 32) * 5 /9 3 | 4 | -------------------------------------------------------------------------------- /Week 4/exercise_#3_Functions.md: -------------------------------------------------------------------------------- 1 | # Exercise #3 ~ Functions 2 | 3 | ## Part 1 4 | Below is a transcript of a session with the Python shell. Provide the type and value of the expressions being evaluated. If evaluating an expression would cause an error, write 'error'. If the result is a function, write 'function'. As always, try to do this problem by hand before turning to your interpreter. Provide a type of result and result itself. __Assume this function already defined.__ 5 | ```Python 6 | def a(x, y, z): 7 | if x: 8 | return y 9 | else: 10 | return z 11 | 12 | def b(q, r): 13 | return a(q>r, q, r) 14 | ``` 15 | 1. ```a(False, 2, 3``` 16 | 2. ```b(3, 2)``` 17 | 3. ```a(3>2, a, b)``` 18 | 4. ```b(a, b)``` 19 | 20 | ## Part 2 21 | 22 | 1. Write a python function, ```square```, that takes in one number and returs the square of that number. This function takes in one number and returns one number. 23 | 24 | 2. Write a Python function, ```evalQuadratic(a, b, c, x)```, that returns the value of the quadratic ```a*x^2 + b*x + c```. This function takes in four numbers and returns a single number. 25 | 26 | 3. Write a Python function, ```clip(lo, x, hi)``` that returns ```lo``` if ```x``` is less than ```lo```; ```hi``` if ```x``` is greater than ```hi```; and ```x``` otherwise. For this problem, you can assume that ```lo < hi```. Don't use any conditional statements for this problem. Instead, use the built in Python functions ```min``` and ```max```. You may wish to read the [documentation on min](http://docs.python.org/library/functions.html#min) and the [documentation on max](http://docs.python.org/library/functions.html#max), and play around with these functions a bit in your interpreter, before beginning this problem. This function takes in three numbers and returns a single number. 27 | 28 | 4. Write a Python function, ```fourthPower```, that takes in one number and returns that value raised to the fourth power. You should use the ```square``` procedure that you defined in question 1. This function takes in one number and returns one number. 29 | 30 | 5. Write a Python function, ```odd```, that takes in one number and returns ```True``` when the number is odd and ```False``` otherwise.You should use the ```%```(mod) operator, not ```if```.This function takes in one number and returns a boolean. 31 | 32 | 6. Define a function ```isVowel(char)``` that returns True if ```char``` is a vowel ('a', 'e', 'i', 'o', or 'u'), and False otherwise. You can assume that ```char``` is a single letter of any case (ie, 'A' and 'a' are both valid). Do not use the keyword ```in```. Your function should take in a single string and return a boolean. 33 | 34 | 7. Define a function ```isVowel2(char)``` that returns True if ```char``` is a vowel ('a', 'e', 'i', 'o', or 'u'), and False otherwise. You can assume that ```char``` is a single letter of any case (ie, 'A' and 'a' are both valid). This function is similar to the previous problem - but this time, do use the keyword ```in```. Your function should take in a single string and return a boolean. 35 | 36 | 37 | ## Part 3 38 | Provide a type of result and result itself. 39 | 1. 40 | ```Python 41 | a = 10 42 | def f(x): 43 | return x + a 44 | a = 3 45 | f(1) 46 | ``` 47 | 2. 48 | ```Python 49 | x = 12 50 | def g(x): 51 | x = x + 1 52 | def h(y): 53 | return x + y 54 | return h(6) 55 | g(x) 56 | ``` 57 | 3. 58 | ```Python 59 | def foo(x): 60 | def bar(x): 61 | return x + 1 62 | return bar(x * 2) 63 | 64 | foo(3) 65 | ``` 66 | 4. 67 | ```Python 68 | def foo (x): 69 | def bar (z): 70 | return z + x 71 | return bar(3) 72 | 73 | foo(2) 74 | ``` 75 | -------------------------------------------------------------------------------- /Week 4/exercise_#3_Lists.md: -------------------------------------------------------------------------------- 1 | # Exercise #3 ~ Lists and List Comprehension 2 | 3 | ## Part 1 4 | Find the correct results for following questions. If no result printed write __blank__. If an error appear just write an __error__. 5 | > You might want to use python interpreter to see things clearly. 6 | 7 | Find corresponding results of following using this variable ```Python x = [1, 2, [3, 'John', 4], 'Hi'] ``` 8 | 9 | 1. ``` x[0]``` 10 | 2. ``` x[2]``` 11 | 3. ``` x[-1]``` 12 | 4. ``` x[0:1]``` 13 | 5. ``` x[2][2]``` 14 | 6. ``` 2 in x``` 15 | 7. ``` 3 in x``` 16 | 8. 17 | ```Python 18 | x[0] = 8 19 | x 20 | ``` 21 | ## Part 2 22 | Find corresponding results of following using this variable ```Python x = [1, 2, [3, 'John', 4], 'Hi'] ``` 23 | 24 | 1. ```rrange(3)``` 25 | 2. ```range(3,10)``` 26 | 3. ```range(3,10,3)``` 27 | 4. ```range(3,10.5,0.5)``` 28 | 5. ```range(10,3)``` 29 | 6. ```range(10,3,-1)``` 30 | 7. ```range(len(x))``` 31 | 8. ```sum(range(len(x)))``` 32 | 33 | ## Part 3 34 | For this part careful that ever question link to eachother. 35 | 36 | 1. 37 | ```Python 38 | aList = range(1, 6) 39 | bList = aList 40 | aList[2] = 'hello' 41 | aList == bList 42 | ``` 43 | 2. 44 | ```Python 45 | aList is bList 46 | ``` 47 | 3. 48 | ```Python 49 | aList 50 | ``` 51 | 4. 52 | ```Python 53 | bList 54 | ``` 55 | 5. 56 | ```Python 57 | cList = range(6, 1, -1) 58 | dList = [] 59 | for num in cList: 60 | dList.append(num) 61 | cList == dList 62 | ``` 63 | 6. 64 | ```Python 65 | cList is dList 66 | ``` 67 | 7. 68 | ```Python 69 | cList[2] = 20 70 | cList 71 | ``` 72 | 8. 73 | ```Python 74 | dList 75 | ``` 76 | 77 | ## Part 4 78 | Use the following list to guide you through this part. 79 | ```Python 80 | >>> listA = [1, 4, 3, 0] 81 | >>> listB = ['x', 'z', 't', 'q'] 82 | ``` 83 | 1. ```listA.sort``` 84 | 2. ```listA.sort()``` 85 | 3. ```listA``` 86 | 4. ```listA.insert(0,100)``` 87 | 5. ```listA.remove(3)``` 88 | 6. ```listA.append(7)``` 89 | 7. ```listA``` 90 | 8. ```listA + listB``` 91 | 9. 92 | ```Python 93 | listB.sort() 94 | listB.pop() 95 | ``` 96 | 10. ```listB.count("a")``` 97 | 11. ```listB.remove("a")``` 98 | 12. ```listA.extend([4,1,6,3,4])``` 99 | 13. ```listA.count(4)``` 100 | 14. ```listA.index(1)``` 101 | 15. ```listA.pop(4)``` 102 | 16. ```listA.reverse()``` 103 | 17. ```listA``` 104 | 105 | -------------------------------------------------------------------------------- /Week 4/first_function.py: -------------------------------------------------------------------------------- 1 | def function_name(): 2 | print("Hello World!") 3 | 4 | def function2(i, j): 5 | return i+j 6 | 7 | def average(a,b,c,d): 8 | return (a+b+c+d)/4 9 | 10 | def list_average(list): 11 | return (sum(list)/len(list)) 12 | 13 | def convert_to_celcius(fahrenheit): 14 | return (fahrenheit - 32)*5/9 15 | 16 | def covert_to_fahrenheit(celcius): 17 | return (fahrenheit * 9)/5 + 32 18 | 19 | def quadratic(a,b,c,x): 20 | first = a * x ** 2 21 | second = b * x 22 | third = c 23 | return first + second + third 24 | -------------------------------------------------------------------------------- /Week 4/functions_intro_comp_science_using_python.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 22 03:32:00 2015 4 | 5 | @author: Enes Kemal Ergin 6 | 7 | Functions from Introduction to Computer Science Using Python 8 | """ 9 | 10 | def average(n1,n2,n3): 11 | return (n1+n2+n3)/ 3.0 12 | 13 | # Tests 14 | average(40,10,25) 15 | average(10,25,40) 16 | average(40,25,10) 17 | 18 | def addup(first, last): 19 | if first > last: 20 | sum = -1 21 | else: 22 | sum = 0 23 | for i in range(first, last + 1): 24 | sum = sum + 1 25 | return sum 26 | 27 | # Tests 28 | addup(1,10) 29 | addup(first = 1, last = 10) 30 | addup(last = 10, first = 1) 31 | 32 | 33 | def addup2(first, last, incr = 1): 34 | if first > last: 35 | sum = -1 36 | else: 37 | sum = 0 38 | for i in range(first, last + 1, incr): 39 | sum = sum + 1 40 | return sum 41 | 42 | # Tests 43 | addup(1,10) 44 | addup(1,10,2) 45 | addup(first = 1, last = 10) 46 | addup(incr = 2, first = 1, last = 10) 47 | -------------------------------------------------------------------------------- /Week 4/hands-on02-26.py: -------------------------------------------------------------------------------- 1 | Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> my_list = list("Hello World") 4 | >>> my_list 5 | ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] 6 | >>> x = [] 7 | >>> x 8 | [] 9 | >>> x [1,2,3] 10 | Traceback (most recent call last): 11 | File "", line 1, in 12 | x [1,2,3] 13 | TypeError: list indices must be integers, not tuple 14 | >>> x = [1,2,3] 15 | >>> x 16 | [1, 2, 3] 17 | >>> y = ["enes", 12, 12.0, 1+4j, True] 18 | >>> y 19 | ['enes', 12, 12.0, (1+4j), True] 20 | >>> x[1] = "string" 21 | >>> x 22 | [1, 'string', 3] 23 | >>> x = [1,2,3,4,5,6] 24 | >>> del x[2] 25 | >>> x 26 | [1, 2, 4, 5, 6] 27 | >>> name = list("Perl") 28 | >>> name 29 | ['P', 'e', 'r', 'l'] 30 | >>> name[2:] = list("ar") 31 | >>> print(name) 32 | ['P', 'e', 'a', 'r'] 33 | >>> print(x) 34 | [1, 2, 4, 5, 6] 35 | >>> x. 36 | SyntaxError: invalid syntax 37 | >>> x.append(3) 38 | >>> x 39 | [1, 2, 4, 5, 6, 3] 40 | >>> x.append(3,2) 41 | Traceback (most recent call last): 42 | File "", line 1, in 43 | x.append(3,2) 44 | TypeError: append() takes exactly one argument (2 given) 45 | >>> x = [[1,2],1,1,[2,1,[1,2]]] 46 | >>> x 47 | [[1, 2], 1, 1, [2, 1, [1, 2]]] 48 | >>> x.count(1) 49 | 2 50 | >>> lst = [123,23456, 987, 234, 2345678890] 51 | >>> len(lst) 52 | 5 53 | >>> max(lst) 54 | 2345678890 55 | >>> min(lst) 56 | 123 57 | >>> sum(lst) 58 | 2345703690 59 | >>> sorted(lst) 60 | [123, 234, 987, 23456, 2345678890] 61 | >>> a = [1,2,3] 62 | >>> b = [4,5,6] 63 | >>> print(a+b) 64 | [1, 2, 3, 4, 5, 6] 65 | >>> a.extend(b) 66 | >>> a 67 | [1, 2, 3, 4, 5, 6] 68 | >>> ================================ RESTART ================================ 69 | >>> 70 | >>> function_name() 71 | Hello World! 72 | >>> ================================ RESTART ================================ 73 | >>> 74 | >>> function2() 75 | Traceback (most recent call last): 76 | File "", line 1, in 77 | function2() 78 | TypeError: function2() missing 2 required positional arguments: 'i' and 'j' 79 | >>> function2(1,2) 80 | 3 81 | >>> ================================ RESTART ================================ 82 | >>> 83 | >>> ================================ RESTART ================================ 84 | >>> 85 | >>> average(1,2,3,4) 86 | 2.5 87 | >>> ================================ RESTART ================================ 88 | >>> 89 | >>> average([1,2,3,4]) 90 | Traceback (most recent call last): 91 | File "", line 1, in 92 | average([1,2,3,4]) 93 | TypeError: average() missing 3 required positional arguments: 'b', 'c', and 'd' 94 | >>> list_average([1,2,3,4]) 95 | 2.5 96 | >>> ================================ RESTART ================================ 97 | >>> 98 | >>> convert_to_celcius(75) 99 | 23.88888888888889 100 | >>> convert_to_celcius(80) 101 | 26.666666666666668 102 | >>> ================================ RESTART ================================ 103 | >>> 104 | >>> quadratic(2,3,4,.5) 105 | 6.0 106 | >>> quadratic(2,3,4,1) 107 | 9 108 | >>> 109 | -------------------------------------------------------------------------------- /Week 4/hands_on_2-25.py: -------------------------------------------------------------------------------- 1 | Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> mylist = list("Hello World!") 4 | >>> mylist 5 | ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'] 6 | >>> x = [1,2,3] 7 | >>> x 8 | [1, 2, 3] 9 | >>> y = [] 10 | >>> type(y) 11 | 12 | >>> x[1] = 7 13 | >>> print(x) 14 | [1, 7, 3] 15 | >>> names = ["Enes", "Yunus", "Emre", "Bedir", "Behic", "Amy"] 16 | >>> del name[2] 17 | Traceback (most recent call last): 18 | File "", line 1, in 19 | del name[2] 20 | NameError: name 'name' is not defined 21 | >>> del names[2] 22 | >>> print(names) 23 | ['Enes', 'Yunus', 'Bedir', 'Behic', 'Amy'] 24 | >>> name = list("Perl") 25 | >>> print(name) 26 | ['P', 'e', 'r', 'l'] 27 | >>> name[2:] list("ar") 28 | SyntaxError: invalid syntax 29 | >>> name[2:] = list("ar") 30 | >>> print(name) 31 | ['P', 'e', 'a', 'r'] 32 | >>> krypton = ["Krypton", "KR", -157.2, 153, True] 33 | >>> krytopn[0] 34 | Traceback (most recent call last): 35 | File "", line 1, in 36 | krytopn[0] 37 | NameError: name 'krytopn' is not defined 38 | >>> krypton[0] 39 | 'Krypton' 40 | >>> krypton[5] 41 | Traceback (most recent call last): 42 | File "", line 1, in 43 | krypton[5] 44 | IndexError: list index out of range 45 | >>> krypton[2] 46 | -157.2 47 | >>> 48 | >>> len(krypton) 49 | 5 50 | >>> half_lives = [887.7, 24100.0, 6563.0, 14, 373300.0] 51 | >>> max(half_lives) 52 | 373300.0 53 | >>> max(krypton) 54 | Traceback (most recent call last): 55 | File "", line 1, in 56 | max(krypton) 57 | TypeError: unorderable types: float() > str() 58 | >>> min(half_lives) 59 | 14 60 | >>> sum(ha) 61 | Traceback (most recent call last): 62 | File "", line 1, in 63 | sum(ha) 64 | NameError: name 'ha' is not defined 65 | >>> sum(half_lives) 66 | 404864.7 67 | >>> sorted(half_lives) 68 | [14, 887.7, 6563.0, 24100.0, 373300.0] 69 | >>> lst = [1,2,3] 70 | >>> lst.append(4) 71 | >>> lst 72 | [1, 2, 3, 4] 73 | >>> print(['to', 'be', 'or', 'not', 'to', 'be'].count('to')) 74 | 2 75 | >>> count_to = ['to', 'be', 'or', 'not', 'to', 'be'].count('to') 76 | >>> print(count_to) 77 | 2 78 | >>> a = [1,2,3] 79 | >>> b = [4,5,6] 80 | >>> a.extend(b) 81 | >>> print(a) 82 | [1, 2, 3, 4, 5, 6] 83 | >>> a = [1,2,3] 84 | >>> b = [4,5,6] 85 | >>> print(a+b) 86 | [1, 2, 3, 4, 5, 6] 87 | >>> a.append(b) 88 | >>> print(a.append(b)) 89 | None 90 | >>> a = a.append(b) 91 | >>> a 92 | >>> print([a]) 93 | [None] 94 | >>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni'] 95 | >>> knights.index("who") 96 | 4 97 | >>> knigths.index("me") 98 | Traceback (most recent call last): 99 | File "", line 1, in 100 | knigths.index("me") 101 | NameError: name 'knigths' is not defined 102 | >>> knights.index("me") 103 | Traceback (most recent call last): 104 | File "", line 1, in 105 | knights.index("me") 106 | ValueError: 'me' is not in list 107 | >>> sorted(knigths) 108 | Traceback (most recent call last): 109 | File "", line 1, in 110 | sorted(knigths) 111 | NameError: name 'knigths' is not defined 112 | >>> sorted(knights) 113 | ['We', 'are', 'knights', 'ni', 'say', 'the', 'who'] 114 | >>> 115 | -------------------------------------------------------------------------------- /Week 4/list_example_byte_of_python.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 22 02:28:35 2015 4 | 5 | @author: Enes Kemal Ergin 6 | 7 | List Examples from A Byte of Python 8 | """ 9 | 10 | shoplist = ['apple', 'mango', 'carrot', 'banana'] 11 | 12 | print('I have', len(shoplist), 'items to purchase.') 13 | 14 | print('These items are: ', end= ' ') 15 | 16 | for item in shoplist: 17 | print(item, end= ' ') 18 | 19 | print('\n also have to buy rice.') 20 | shoplist.append('rice') 21 | print('My Shopping list is now', shoplist) 22 | 23 | print('I want to sort my list') 24 | shoplist.sort() 25 | print('Sorted list: ', shoplist) 26 | 27 | print('The first item I will buy is', shoplist[0]) 28 | olditem = shoplist[0] 29 | 30 | del shoplist[0] 31 | 32 | print('I bought the', olditem) 33 | print('My shopping list is now', shoplist) -------------------------------------------------------------------------------- /Week 4/list_example_novice_to_professional.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 22 02:33:41 2015 4 | 5 | @author: Enes Kemal Ergin 6 | 7 | List Examples from Beginning Python from novice to Professional 8 | """ 9 | 10 | mylist = list("Hello World") 11 | print(mylist) 12 | 13 | # Overwriting an element on list. 14 | x = [1,2,3] 15 | x[1]= 7 # Lists are mutable 16 | print(x) 17 | 18 | # Deleting Elements 19 | names = ['Alice', 'Beth', "Cecil", "Dee-Dee", "Earl"] 20 | del names[2] 21 | print(names) 22 | 23 | # Assigning to Slices 24 | name = list("Perl") 25 | print(name) 26 | name[2:] = list("ar") 27 | print(name) 28 | 29 | lst = [1,2,3] 30 | lst.append(4) 31 | print(lst) 32 | 33 | 34 | print(['to', 'be', 'or', 'not', 'to', 'be'].count('to')) 35 | 36 | x = [[1, 2], 1, 1, [2, 1, [1, 2]]] 37 | x.count(1) 38 | 39 | a = [1,2,3] 40 | b = [4,5,6] 41 | a.extend(b) 42 | print(a) 43 | 44 | # It does the same thing as: 45 | 46 | a = [1,2,3] 47 | b = [4,5,6] 48 | 49 | print(a + b) # concatenate doesnot overwrite the compounds. 50 | 51 | print(a) 52 | 53 | 54 | knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni'] 55 | knights.index('who') 56 | 57 | knights.index('herring') # Will throw and error because herring is not in the list 58 | 59 | knights[4] 60 | 61 | numbers = [1, 2, 3, 5, 6, 7] 62 | numbers.insert(3, 'four') 63 | print(numbers) 64 | 65 | numbers = [1, 2, 3, 5, 6, 7] 66 | numbers[3:3] = ['four'] 67 | numbers 68 | 69 | 70 | x = [1,2,3] 71 | x.pop() 72 | print(x) 73 | 74 | x.append(x.pop()) # Appends the removed one, so it won't change anything. 75 | 76 | x = ['to', 'be', 'or', 'not', 'to', 'be'] 77 | x.remove('be') 78 | print(x) 79 | 80 | x.remove('bee') # It will throw and error. 81 | 82 | x = [1, 2, 3] 83 | x.reverse() 84 | print(x) 85 | 86 | x = [4, 6, 2, 1, 7, 9] 87 | x.sort() 88 | print(x) 89 | -------------------------------------------------------------------------------- /Week 4/save.py: -------------------------------------------------------------------------------- 1 | def function_name(parameter): 2 | # This is my function body 3 | print("Hello World!") 4 | print(2+5) 5 | print(parameter) 6 | return "Bye Bye!" 7 | 8 | # Tests 9 | function_name([2,3]) 10 | print("-"*50) 11 | function_name("Enes") 12 | 13 | def another_function(): 14 | # This is my function body 15 | print("Hello World!") 16 | print(2+5) 17 | return "Bye Bye!" 18 | -------------------------------------------------------------------------------- /Week 5/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NAU-Python-Class/Py101-Spring-15/61676ee020bc66613209b6928058bdc9e4c34c9d/Week 5/.DS_Store -------------------------------------------------------------------------------- /Week 5/Hands0n2.py: -------------------------------------------------------------------------------- 1 | # Python 101 03/26/15 2 | 3 | # Subject Dictionaries... 4 | 5 | stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2} 6 | 7 | print stuff['height'] 8 | 9 | stuff['city'] = "San Francisco" 10 | 11 | del stuff['city'] 12 | 13 | # Creating 5 element dictionary 14 | states = { 15 | 'Oregon': 'OR', 16 | 'Florida': 'FL', 17 | 'California': 'CA', 18 | 'New York': 'NY', 19 | 'Michigan': 'MI' 20 | } 21 | cities = { } 22 | cities = dict() 23 | # adding more elements 24 | cities['NY'] = 'New York' 25 | cities['OR'] = 'Portland' 26 | 27 | 28 | state = states.get('Texas') 29 | print state 30 | 31 | if not state: 32 | print "Sorry, no Texas." 33 | 34 | def histogram(s): 35 | d = dict() 36 | for c in s: 37 | if c not in d: 38 | d[c] = 1 39 | else: 40 | d[c] += 1 41 | return d 42 | 43 | print histogram("alibaba") 44 | 45 | 46 | 47 | def print_hist(h): 48 | for c in h: 49 | print c, h[c] 50 | 51 | h = histogram('parrot') 52 | print_hist(h) 53 | 54 | 55 | t = 'a', 'b', 'c', 'd', 'e' 56 | print type(t) 57 | print t 58 | t = ('a', 'b', 'c', 'd', 'e') 59 | 60 | t = tuple("alibaba") 61 | print t 62 | 63 | l = list("alibaba") 64 | 65 | print t[0] 66 | 67 | a = 1 68 | b = 3 69 | 70 | temp = a 71 | a = b 72 | b = temp 73 | 74 | a,b = b,a 75 | 76 | 77 | def min_max(t): 78 | return min(t), max(t) 79 | 80 | t = (1,2,3,4,5,6,7,8,9,0) 81 | print min_max(t) 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /Week 5/Programming Concepts.md: -------------------------------------------------------------------------------- 1 | # Programming Concepts - Week 5 2 | 3 | > This file is all about practice. Writing all practices by yourself will improve your understanding in Python. Also I will put here more detailed, and somehow advanced examples, so you can challenge yourself practicing on them. 4 | 5 | --- 6 | 7 | ## Dictionaries 8 | Dictionaries are one of the most flexible built-in data types in Python.You can think of dictionaries as unordered collections; the chief distinction is that in dictionaries, items are stored and fetched by key, instead of by positional offset. 9 | 10 | Dictionaries can replace many of the searching algorithms and data structures you might have to implement manually in lower-level languages—as a highly optimized built-in type, indexing a dictionary is a very fast search operation. There are some features of dictionaries: 11 | 12 | - Accessed by key, not offset position(index): 13 | - They are sometimes called associative arrays or hashes. They associate a set of values with keys, so you can fetch an item out of a dictionary using the key under which you originally stored it. 14 | - Unordered collections of arbitrary objects 15 | - Unlike in a list, items stored in a dictionary aren’t kept in any particular order; in fact, Python pseudo-randomizes their left-to-right order to provide quick lookup. 16 | - Variable-length, heterogeneous, and arbitrarily nestable 17 | - Like lists, dictionaries can grow and shrink in place (without new copies being made), they can contain objects of any type, and they support nesting to any depth (they can contain lists, other dictionaries, and so on). Each key can have just one associated value, but that value can be a collection of multiple objects if needed, and a given value can be stored under any number of keys. 18 | - Mutable mapping 19 | - You can change dictionaries in place by assigning to indexes (they are mutable), but they don’t support the sequence operations that work on strings and lists. 20 | - Hash Tables 21 | - If lists are arrays of object references that support access by position, dictionaries are unordered tables of object references that support access by key. Internally, dictionaries are implemented as hash tables 22 | 23 | ### Basic Dictionary Operations 24 | 25 | ```Python 26 | D = {'spam': 2, 'ham': 1, 'eggs': 3} # Makes a dictionary 27 | D['spam'] 28 | # 2 29 | D # Showing order is not important 30 | # {'eggs': 3, 'spam': 2, 'ham': 1} 31 | 32 | # Number of entries 33 | len(D) 34 | # 3 35 | 36 | # testing by key 37 | 'ham' in D 38 | # True 39 | 40 | # Creates a new list of D's keys 41 | list(D.keys()) 42 | # ['eggs', 'spam', 'ham'] 43 | 44 | ``` 45 | 46 | ### Changing Dictionaries in Place 47 | ```Python 48 | D 49 | # {'eggs': 3, 'spam': 2, 'ham': 1} 50 | 51 | # Changing entry (value = list) 52 | D['ham'] = ['grill', 'bake', 'fry'] 53 | D 54 | # {'eggs': 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']} 55 | 56 | # Delete entry 57 | del D['eggs'] 58 | D 59 | # {'spam': 2, 'ham': ['grill', 'bake', 'fry']} 60 | 61 | # Adds new entry 62 | D['brunch'] = 'Bacon' 63 | D 64 | # {'brunch': 'Bacon', 'spam': 2, 'ham': ['grill', 'bake', 'fry']} 65 | ``` 66 | 67 | ### More Dictionary Methods 68 | 69 | ```Python 70 | D = {'spam': 2, 'ham': 1, 'eggs': 3} 71 | list(D.values()) 72 | # [3, 2, 1] 73 | list(D.items()) 74 | # [('eggs', 3), ('spam', 2), ('ham', 1)] 75 | 76 | 77 | # A key that is there 78 | D.get('spam') 79 | # 2 80 | 81 | # A key that is missing 82 | print(D.get('toast')) 83 | # None 84 | 85 | # Assings 'toast' to 88 get the result 86 | D.get('toast', 88) 87 | # 88 88 | 89 | D 90 | # {'eggs': 3, 'spam': 2, 'ham': 1} 91 | D2 = {'toast':4, 'muffin':5} # Lots of delicious scrambled order here 92 | 93 | # Updates D with items in D2 94 | D.update(D2) 95 | D 96 | # {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2, 'ham': 1} 97 | 98 | # pop a dictionary by key 99 | D 100 | # {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2, 'ham': 1} 101 | D.pop('muffin') 102 | # 5 103 | D.pop('toast') # Delete and return from a key 104 | # 4 105 | D 106 | # {'eggs': 3, 'spam': 2, 'ham': 1} 107 | 108 | # pop a list by position 109 | L = ['aa', 'bb', 'cc', 'dd'] 110 | L.pop() # Delete and return from the end 111 | # 'dd' 112 | 113 | L 114 | # ['aa', 'bb', 'cc'] 115 | L.pop(1) # Delete from a specific position 116 | # 'bb' 117 | L 118 | # ['aa', 'cc'] 119 | ``` 120 | 121 | 122 | ## Tuples 123 | 124 | Tuples construct simple groups of objects. They work exactly like lists, except that tuples can’t be changed in place (they’re immutable) and are usually written as a series of items in parentheses, not square brackets. Although they don’t support as many methods, tuples share most of their properties with lists. Here are the features of tuples: 125 | 126 | - Ordered collections of arbitrary objects 127 | - Like strings and lists, tuples are positionally ordered collections of objects (i.e., they maintain a left-to-right order among their contents); like lists, they can embed any kind of object. 128 | - Accessed by offset 129 | - Like strings and lists, items in a tuple are accessed by offset (not by key); they support all the offset-based access operations, such as indexing and slicing. 130 | - Of the category “immutable sequence” 131 | - Like strings and lists, tuples are sequences; they support many of the same operations. However, like strings, tuples are immutable; they don’t support any of the in-place change operations applied to lists. 132 | - Fixed-length, heterogeneous, and arbitrarily nestable 133 | - Because tuples are immutable, you cannot change the size of a tuple without making a copy. On the other hand, tuples can hold any type of object, including other compound objects (e.g., lists, dictionaries, other tuples), and so support arbitrary nesting. 134 | - Arrays of object references 135 | - Like lists, tuples are best thought of as object reference arrays; tuples store access points to other objects (references), and indexing a tuple is relatively quick. 136 | 137 | 138 | ### Tuples usage 139 | ```Python 140 | 141 | ``` 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | -------------------------------------------------------------------------------- /Week 5/hands0n1.py: -------------------------------------------------------------------------------- 1 | """ 03/25/15 Python 101 """ 2 | # Subject : 3 | # Dictionaries 4 | # Tuples 5 | # Going advance on them 6 | 7 | dic = dict() 8 | 9 | print(dic) 10 | print(type(dic)) 11 | 12 | # This is how you can add key-value pairs 13 | dic['one'] = 'uno' 14 | print(dic) 15 | 16 | eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} 17 | print(eng2sp) 18 | 19 | # This is how you indexing with dictionaries 20 | print(eng2sp['one']) 21 | 22 | print(len(eng2sp)) 23 | 24 | print('one' in eng2sp) 25 | print('uno' in eng2sp) 26 | 27 | 28 | def histogram(s): 29 | d = dict() # or d = {} 30 | for c in s: 31 | if c not in d: 32 | d[c] = 1 33 | else: 34 | d[c] += 1 # d = d + 1 35 | return d 36 | 37 | string = "Watermelon" 38 | h = histogram(string) 39 | print(h) 40 | 41 | def print_hist(h): 42 | for c in h: 43 | print c, h[c] 44 | print_hist(h) 45 | 46 | 47 | """ Tuples """ 48 | 49 | t = 'a', 'b', 'c', 'd', 'e' 50 | print(t) 51 | print(type(t)) 52 | 53 | t1 = ("a", "b", "c", "d", "e") 54 | print(t) 55 | 56 | 57 | t2 = tuple("String") 58 | print(t2) 59 | 60 | print(t2[0]) 61 | 62 | # Tuples are not mutable 63 | #t2[0] = 'A' 64 | 65 | t2 = ("A",) + t2[1:] 66 | print(t2) 67 | 68 | a = 1 69 | b = 2 70 | temp = a 71 | a = b 72 | b = temp 73 | 74 | a, b = b, a 75 | print a, b 76 | 77 | 78 | 79 | --------------------------------------------------------------------------------