├── 00-00-python-pycharm-installation.md ├── 00-01-course-guide.md ├── 00-02-01-all-python-code.md ├── 00-02-02-all-java-code.md ├── 00-03-course-overview.png ├── LICENSE ├── README.md ├── java-code ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── in28minutes │ └── java │ └── to │ └── python │ └── examples │ ├── set1 │ ├── Book.java │ ├── BookEnhanced.java │ ├── DoWhileRepeatedQuestionRunner.java │ ├── ForLoopExercises.java │ ├── HelloWorld.java │ ├── MathBasic.java │ ├── MathBasic2.java │ ├── MenuConditionalRunner.java │ ├── MultiplicationTable.java │ ├── Person.java │ ├── Planet.java │ ├── Player.java │ ├── StringBasic.java │ ├── Student.java │ └── SwitchExercisesRunner.java │ ├── set2 │ ├── AbstractRecipe.java │ ├── ChessGame.java │ ├── GameRunner.java │ ├── GamingConsole.java │ ├── MarioGame.java │ ├── Recipe1.java │ ├── RecipeRunner.java │ └── RecipeWithMicrowave.java │ └── set3 │ ├── ExceptionHandlingRunner.java │ ├── FunctionalProgrammingRunner.java │ └── ThrowingExceptionRunner.java └── python-code ├── oops ├── abstract_class_example.py ├── abstract_class_to_implement_interface_example.py ├── book_example.py ├── encapsulation_examples.py ├── exception_handling_examples.py ├── inheritance_examples.py ├── motor_bike_example.py ├── multiple_inheritance_examples.py ├── oops_in_depth.py ├── oops_puzzles.py ├── operator_overloading_examples.py └── static_examples.py ├── python-hello-world ├── first_method.py ├── for_loop_examples.py ├── for_loop_exercises.py ├── hello_world.py ├── if_examples.py ├── math_basic.py ├── menu_with_if.py ├── multiplication_table.py ├── oops_trials.py ├── repeated_question.py └── while_loop_examples.py ├── python-shell-extract.txt └── tips ├── all_about_methods.py ├── enum_examples.py ├── module_1.py ├── module_2.py └── switch_alternatives.py /00-00-python-pycharm-installation.md: -------------------------------------------------------------------------------- 1 | ## Installing Python 2 | 3 | https://www.python.org/downloads/ 4 | 5 | #### Google for "java 9 jdk download" 6 | ![Image](/images/01_Java9JDKDownload.png) 7 | --- 8 | #### Land on the Oracle JDK Download Site 9 | ![Image](/images/02_Oracle_Site.png) 10 | --- 11 | #### Accept License Agreement 12 | ![Image](/images/03_AcceptLicenseAgreement_Error.png) 13 | ![Image](/images/04_AcceptLicenseAgreement.png) 14 | --- 15 | #### Download JDK for Your Specific Operating System 16 | ![Image](/images/05_Download_JDK_9.png) 17 | --- 18 | #### Launch the Downloaded file 19 | ![Image](/images/06_DoubleClick_And_Start_Installation.png) 20 | --- 21 | #### Java Installation Screens 22 | ![Image](/images/10_Installation_First_Screen.png) 23 | --- 24 | ![Image](/images/11_Installation_Ready_Screen.png) 25 | --- 26 | #### Choose Defaults and Copy Install Location 27 | ![Image](/images/12_Installation_Features_Select_Screen.png) 28 | --- 29 | ![Image](/images/13_Installation_Status_Screen.png) 30 | --- 31 | #### Choose Defaults and Copy Install Location 32 | ![Image](/images/14_Installation_Choose_Custom_Setup.png) 33 | --- 34 | ![Image](/images/15_Installation_Status_Screen.png) 35 | --- 36 | #### Congratulations 37 | ![Image](/images/16_Congratulations.png) 38 | --- 39 | 40 | ## Verify Java and JShell Installation 41 | 42 | #### Launch Terminal or Command Prompt 43 | ![Image](/images/21_Launch_Command_Prompt_Windows.png) 44 | --- 45 | ![Image](/images/21_Launch_Terminal_Mac.png) 46 | --- 47 | ##### Detailed Instructions 48 | 1. If you are on Windows : Open the Command Prompt window by 49 | * Click the Start button 50 | * Select All Programs -> Accessories > Command Prompt. 51 | * Or use Ctrl + Esc, and type in cmd and launch up command. 52 | 2. If you are on Mac or other OS, launch up Terminal. 53 | * cmd + space -> Type terminal -> Press enter 54 | 55 | #### Java Version Successful 56 | ![Image](/images/22_Java_Version_Mac.png) 57 | --- 58 | ![Image](/images/22_Java_Version_Windows.png) 59 | --- 60 | #### JShell Version Successful 61 | ![Image](/images/23_JShell_Version_Success_Windows.png) 62 | --- 63 | ![Image](/images/24_JShell_Version_Success_Mac_1.png) 64 | --- 65 | #### Launching JShell 66 | ![Image](/images/26_JShell_Launch_Screen.png) 67 | --- 68 | ![Image](/images/25_JShell_Example_Command.png) 69 | --- 70 | #### Error In Launching JShell 71 | ![Image](/images/24_JShell_Version_Error.png) 72 | --- 73 | > If you are in windows, ```java -version``` is working and ```jshell -version``` is not working, directly jump to the section ```Setting PATH environment variable in Windows``` 74 | 75 | ### Troubleshooting 76 | 1. Check if there are any pre-existing Java installs. Uninstall them and reinstall again. 77 | 2. Temporarily turn off firewalls and antivirus software. 78 | 3. If you get file corrupt message, download the installation file again. 79 | 4. Check if you are on 32-bit OS or 64-bit OS. Remember, Java 9 is not supported on 32 bit windows. 80 | 5. Check if you need PATH variable to point to right Java Version - https://www.java.com/en/download/help/path.xml 81 | 82 | ### More Help 83 | - Windows - https://docs.oracle.com/javase/9/install/installation-jdk-and-jre-microsoft-windows-platforms.htm 84 | - Mac - https://docs.oracle.com/javase/9/install/installation-jdk-and-jre-macos.htm#JSJIG-GUID-2FE451B0-9572-4E38-A1A5-568B77B146DE 85 | - Linux - https://docs.oracle.com/javase/9/install/installation-jdk-and-jre-linux-platforms.htm#JSJIG-GUID-737A84E4-2EFF-4D38-8E60-3E29D1B884B8 86 | 87 | 88 | ## Setting PATH environment variable in Windows 89 | 90 | #### Goal - What we want to do? 91 | ![Image](/images/30_JShell_In_JDK_Bin_Folder.png) 92 | --- 93 | #### More Help 94 | - https://www.java.com/en/download/help/path.xml 95 | - https://www.computerhope.com/issues/ch000549.htm 96 | --- 97 | 98 | #### Browsing to Java Folder 99 | ![Image](/images/31_Browsing_To_Java_Folder.png) 100 | --- 101 | #### Browsing to JDK Bin Folder 102 | ![Image](/images/32_Browsing_To_JDK_Bin_Folder.png) 103 | --- 104 | #### Launch Environment Variables 105 | Two Options 106 | - Short Route - ```Click``` Start Button or ```Ctrl + Esc``` to launch start menu and type in ```Env```. Choose ```Edit System Environment Variables```. 107 | - Long Route - Select ```Control Panel``` and then ```System```. Click ```Advanced``` and then ```Environment Variables```. 108 | ![Image](/images/33_Windows_Environment_Variables.png) 109 | --- 110 | ![Image](/images/34_Click_Environment_Variables.png) 111 | --- 112 | #### Select and Edit Path Variable 113 | ![Image](/images/35_Scroll_And_Select_Path_And_Edit.png) 114 | --- 115 | ![Image](/images/36_Default_Path_value.png) 116 | --- 117 | #### Add JDK Bin Folder To Path 118 | ![Image](/images/37_Add_JDK_Bin_Folder_To_Path.png) 119 | --- 120 | ![Image](/images/38_Click_ok.png) 121 | --- 122 | ![Image](/images/39_Click_ok.png) 123 | --- 124 | ![Image](/images/40_Click_ok.png) 125 | --- 126 | 127 | ## Installing Eclipse 128 | 129 | Eclipse is the most popular open source Java IDE. 130 | 131 | Choose the latest available version of Eclipse - Eclipse Oxygen (4.7) or Later. 132 | 133 | > Tip : Do not use an old eclipse version! 134 | 135 | ### Prerequisites 136 | - Java JDK 9 137 | 138 | ### Installation 139 | 140 | 1. Search google for “download eclipse” and choose the first result. The direct link is http://www.eclipse.org/downloads/eclipse-packages/. 141 | ![Image](/images/51_google-search-download-eclipse.png) 142 | 143 | 2. Choose the right Operation System. 144 | ![Image](/images/52_eclipse-choose-installation.png) 145 | 146 | 3. We recommend to choose “Eclipse IDE for Java EE Developers”. Choose 32 bit or 64 bit based on your operating system. (Right-click My Computer, and then click Properties. If "x64 Edition" is listed under System, your processor is capable of running a 64-bit version of Windows.) 147 | 148 | 4. Wait for the download to complete. Extract the zip file to a folder (Example : c:\eclipse). 149 | 5. When you unzip Eclipse, the directory layout looks something like this: 150 | 151 | ``` 152 | eclipse/ 153 | features/ ''the directory containing Eclipse features'' 154 | plugins/ ''the directory containing Eclipse plugins'' 155 | eclipse.exe ''platform executable'' 156 | eclipse.ini 157 | eclipsec.exe ''(windows only) console executable'' 158 | epl-v10.html ''the EPL license'' 159 | jre/ ''the JRE to run Eclipse with'' 160 | notice.html 161 | readme 162 | ``` 163 | 6. You can start Eclipse by running eclipse.exe on Windows or eclipse on other platforms. This small launcher essentially finds and loads the JVM. On Windows, the eclipsec.exe console executable can be used for improved command line behavior. 164 | 165 | > More Details - https://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F 166 | 167 | ### Troubleshooting 168 | - Use 7Zip instead of windows built-in decompression utility. 169 | - Unzip to root folder (e.g. c:\) compared to a long directory path (e.g. c:\Program Files\Eclipse). 170 | - Reference - https://wiki.eclipse.org/Eclipse/Installation#Troubleshooting 171 | -------------------------------------------------------------------------------- /00-01-course-guide.md: -------------------------------------------------------------------------------- 1 | # Course Guide 2 | 3 | 4 | 5 | ## Getting Started With Python 6 | 7 | ### Step By Step Details 8 | 9 | ### Python Shell Code 10 | 11 | ```py 12 | ``` 13 | ### PyCharm Code 14 | 15 | 16 | 17 | ## Conditionals and Loops 18 | 19 | ### Step By Step Details 20 | 21 | ### Python Shell Code 22 | 23 | ```py 24 | ``` 25 | ### PyCharm Code 26 | 27 | 28 | 29 | 30 | ## Object Oriented Programming with Python 31 | 32 | ### Step By Step Details 33 | 34 | ### Python Shell Code 35 | 36 | ```py 37 | ``` 38 | ### PyCharm Code 39 | 40 | 41 | 42 | ## Built-In Python Modules 43 | 44 | ### Step By Step Details 45 | 46 | ### Python Shell Code 47 | 48 | ```py 49 | ``` 50 | ### PyCharm Code 51 | 52 | 53 | 54 | 55 | ## Python Data Structures 56 | 57 | ### Step By Step Details 58 | 59 | ### Python Shell Code 60 | 61 | ```py 62 | ``` 63 | ### PyCharm Code 64 | 65 | 66 | 67 | ## Exception Handling in Python 68 | 69 | ### Step By Step Details 70 | 71 | ### Python Shell Code 72 | 73 | ```py 74 | ``` 75 | ### PyCharm Code 76 | 77 | 78 | 79 | ## Functional Programming 80 | 81 | ### Step By Step Details 82 | 83 | ### Python Shell Code 84 | 85 | ```py 86 | ``` 87 | ### PyCharm Code 88 | 89 | 90 | 91 | ## Python Tips 92 | 93 | ### Step By Step Details 94 | 95 | ### Python Shell Code 96 | 97 | ```py 98 | ``` 99 | ### PyCharm Code 100 | -------------------------------------------------------------------------------- /00-02-01-all-python-code.md: -------------------------------------------------------------------------------- 1 | 4 | 5 | ## Complete Code Example 6 | 7 | 8 | ### /oops/abstract_class_example.py 9 | 10 | ```py 11 | from abc import ABC, abstractmethod 12 | 13 | class AbstractRecipe(ABC): 14 | 15 | def execute(self): 16 | self.get_ready() 17 | self.do_the_dish() 18 | self.cleanup() 19 | 20 | @abstractmethod 21 | def get_ready(self): 22 | pass 23 | 24 | @abstractmethod 25 | def do_the_dish(self): 26 | pass 27 | 28 | @abstractmethod 29 | def cleanup(self): 30 | pass 31 | 32 | 33 | class Recipe1(AbstractRecipe): 34 | 35 | def get_ready(self): 36 | print('Get raw materials') 37 | print('Get utensils') 38 | 39 | def do_the_dish(self): 40 | print('do the dish') 41 | 42 | def cleanup(self): 43 | print('clean utensils') 44 | 45 | 46 | # TypeError: Can't instantiate abstract class AbstractRecipe 47 | # with abstract methods cleanup, do_the_dish, get_ready 48 | # recipe = AbstractRecipe() 49 | 50 | recipe = Recipe1() 51 | 52 | recipe.execute() 53 | ``` 54 | --- 55 | 56 | ### /oops/abstract_class_to_implement_interface_example.py 57 | 58 | ```py 59 | from abc import ABC,abstractmethod 60 | 61 | 62 | # class GamingConsole(ABC): 63 | # @abstractmethod 64 | # def up(self): pass 65 | # 66 | # @abstractmethod 67 | # def down(self): pass 68 | # 69 | # @abstractmethod 70 | # def left(self): pass 71 | # 72 | # @abstractmethod 73 | # def right(self): pass 74 | 75 | 76 | class MarioGame: 77 | def up(self): print('jump') 78 | 79 | def down(self): print('goes into a hole') 80 | 81 | def left(self): pass 82 | 83 | def right(self): print('Go Forward') 84 | 85 | 86 | class ChessGame: 87 | def up(self): print('Move piece up') 88 | 89 | def down(self): print('Move piece down') 90 | 91 | def left(self): print('Move piece left') 92 | 93 | def right(self): print('Move piece right') 94 | 95 | 96 | # games = [ChessGame(), MarioGame()] 97 | # 98 | # for game in games: 99 | # game.up() 100 | # game.down() 101 | # game.left() 102 | # game.right() 103 | 104 | class Test1: 105 | def method(self): print("Test1") 106 | 107 | class Test2: 108 | def method(self): print("Test2") 109 | 110 | tests = [Test1(),Test2()] 111 | 112 | for test in tests: 113 | test.method() 114 | 115 | ``` 116 | --- 117 | 118 | ### /oops/book_example.py 119 | 120 | ```py 121 | # MotorBike 122 | # gear, speed 123 | 124 | class Book: 125 | 126 | def __init__(self, name, copies): 127 | self.name = name 128 | self.copies = copies 129 | 130 | def __repr__(self): 131 | return repr((self.name, self.copies)) 132 | 133 | def increase_copies(self, how_much): 134 | self.copies += how_much 135 | 136 | def decrease_copies(self, how_much): 137 | self.copies -= how_much 138 | 139 | #set 140 | #get 141 | 142 | book1 = Book('Mastering Spring 5.0', 200) 143 | book1.increase_copies(50) 144 | 145 | book2 = Book('Mastering Python 3', 15) 146 | book2.decrease_copies(5) 147 | 148 | print(book1) 149 | print(book2) 150 | ``` 151 | --- 152 | 153 | ### /oops/encapsulation_examples.py 154 | 155 | ```py 156 | class BookEnhanced: 157 | def __init__(self, name, copies): 158 | self.name = name 159 | self._copies = copies 160 | 161 | @property 162 | def copies(self): 163 | print('getter called') 164 | return self._copies 165 | 166 | @copies.setter 167 | def copies(self, copies): 168 | print('setter called') 169 | if(copies>=0): 170 | self._copies = copies 171 | 172 | microservices = BookEnhanced('Microservices',5) 173 | 174 | print(microservices.copies) 175 | 176 | microservices.copies = 10 177 | 178 | print(microservices.copies) 179 | ``` 180 | --- 181 | 182 | ### /oops/exception_handling_examples.py 183 | 184 | ```py 185 | # try: 186 | # i = 0 187 | # number = 10/i 188 | # except ZeroDivisionError as error: 189 | # print(error) 190 | # number = 0 191 | # else: # else is execute when exception is not thrown 192 | # print('else') 193 | # finally: 194 | # print('finally') 195 | # 196 | # print(number) 197 | # 198 | 199 | class Amount: 200 | def __init__(self, currency, amount): 201 | self.currency = currency 202 | self.amount = amount 203 | 204 | def add(self, that): 205 | if(self.currency==that.currency): 206 | self.amount += that.amount 207 | else: 208 | raise CurrencyDoNotMatchException(self.currency + " " + that.currency) 209 | 210 | def __repr__(self): 211 | return repr((self.currency,self.amount)) 212 | 213 | class CurrencyDoNotMatchException(Exception): 214 | def __init__(self, message): 215 | super().__init__(message) 216 | 217 | 218 | amount1 = Amount('EUR',35) 219 | amount2 = Amount('INR',70) 220 | 221 | amount2.add(amount1) 222 | print(amount2) 223 | ``` 224 | --- 225 | 226 | ### /oops/inheritance_examples.py 227 | 228 | ```py 229 | # Student(college,year,degree) 230 | # IS A Person(name, address) 231 | 232 | 233 | class Person: 234 | def __init__(self, name): 235 | self.name = name 236 | 237 | def __repr__(self): 238 | return repr((self.name)) 239 | 240 | 241 | class Student(Person): 242 | 243 | def __init__(self, name, college_name): 244 | super().__init__(name) 245 | self.college_name = college_name 246 | 247 | def __repr__(self): 248 | return repr((super().__repr__(),self.college_name)) 249 | 250 | 251 | person = Person('Ranga') 252 | 253 | student = Student('Ranga', 'Pondicherry Engg College') 254 | 255 | print(person) 256 | 257 | print(student) 258 | 259 | class Planet: 260 | pass 261 | 262 | earth = Planet() 263 | earth.__repr__() 264 | ``` 265 | --- 266 | 267 | ### /oops/motor_bike_example.py 268 | 269 | ```py 270 | class MotorBike: 271 | 272 | def __init__(self, gear, speed): 273 | self.gear = gear 274 | self.speed = speed 275 | 276 | def __repr__(self): 277 | return repr((self.gear, self.speed)) 278 | 279 | 280 | # instance 1 or object 1 281 | honda = MotorBike(3, 50) 282 | 283 | # instance 2 or object 2 284 | ducati = MotorBike(1, 10) 285 | 286 | print(honda) 287 | print(ducati) 288 | ``` 289 | --- 290 | 291 | ### /oops/multiple_inheritance_examples.py 292 | 293 | ```py 294 | class LandAnimal: 295 | def walk(self): 296 | print('walk') 297 | 298 | class WaterAnimal: 299 | def swim(self): 300 | print('swim') 301 | 302 | class Amphibian(LandAnimal, WaterAnimal): 303 | pass 304 | 305 | frog = Amphibian() 306 | 307 | frog.swim() 308 | frog.walk() 309 | 310 | ``` 311 | --- 312 | 313 | ### /oops/oops_in_depth.py 314 | 315 | ```py 316 | class Planet: 317 | def __init__(self, name, distance_from_sun): 318 | self.name = name 319 | self.distance_from_sun = distance_from_sun 320 | 321 | earth = Planet('Earth', 200) 322 | mars = Planet('Mars', 500) 323 | 324 | earth.speed = 10000 325 | print(earth.speed) 326 | 327 | # mars.name = 'Mars' 328 | print(mars.name) 329 | ``` 330 | --- 331 | 332 | ### /oops/oops_puzzles.py 333 | 334 | ```py 335 | class Country: 336 | # def __init__(self): 337 | # print('constuctor 1') 338 | 339 | def __init__(self, name="Default"): 340 | self.name = name 341 | print('constuctor 2') 342 | 343 | def instance_method(self): 344 | print('instance method') 345 | 346 | 347 | default_country = Country() 348 | india = Country('India') 349 | 350 | print(default_country.name) 351 | print(india.name) 352 | #TypeError: __init__() missing 1 required positional argument: 'name' 353 | ``` 354 | --- 355 | 356 | ### /oops/operator_overloading_examples.py 357 | 358 | ```py 359 | from functools import total_ordering 360 | 361 | @total_ordering 362 | class Money: 363 | def __init__(self, currency, amount): 364 | self.currency = currency 365 | self.amount = amount 366 | 367 | def __add__(self, other): 368 | return Money(self.currency, self.amount + other.amount) 369 | 370 | def __sub__(self, other): 371 | return Money(self.currency, self.amount - other.amount) 372 | 373 | def __repr__(self): 374 | return repr((self.currency, self.amount)) 375 | 376 | def __eq__(self, other): 377 | return (self.currency, self.amount) == (other.currency,other.amount) 378 | 379 | def __le__(self, other): 380 | return (self.amount) <= (other.amount) 381 | 382 | amount1 = Money('EUR', 10) 383 | amount2 = Money('EUR', 20) 384 | amount3 = Money('EUR', 10) 385 | 386 | print(amount1 < amount2) 387 | print(amount2 < amount3) 388 | print(amount3 < amount1) 389 | 390 | print(amount3 <= amount1) 391 | print(amount3 >= amount1) 392 | 393 | # print(amount1 == amount2) 394 | # print(amount1 != amount2) 395 | # print(amount1 == amount3) 396 | # print(amount1 != amount3) 397 | 398 | # print(amount1 + amount2) 399 | # print(amount2 - amount1) 400 | 401 | 402 | 403 | # object.__add__(self, other) 404 | # object.__sub__(self, other) 405 | # object.__mul__(self, other) * 406 | # object.__matmul__(self, other) 407 | # object.__truediv__(self, other) \ 408 | # object.__floordiv__(self, other) \\ 409 | # object.__mod__(self, other) % 410 | # object.__pow__(self, other[, modulo]) ** 411 | # object.__and__(self, other) and 412 | # object.__xor__(self, other) ^ 413 | # object.__or__(self, other) or 414 | # 415 | # i methods 416 | ``` 417 | --- 418 | 419 | ### /oops/static_examples.py 420 | 421 | ```py 422 | class Player: 423 | count = 0 424 | 425 | def __init__(self, name): 426 | self.name = name 427 | Player.count += 1 428 | 429 | @staticmethod 430 | def get_count(): 431 | return Player.count 432 | 433 | messi = Player('Messi') 434 | ronaldo = Player('Ronaldo') 435 | 436 | print(messi.get_count()) 437 | print(ronaldo.get_count()) 438 | print(Player.get_count()) 439 | 440 | # print(Player.count) 441 | # 442 | # print(messi.count) 443 | # print(ronaldo.count) 444 | # 445 | # Player.count = 100 446 | # 447 | # print(Player.count) 448 | # 449 | # print(messi.count) 450 | # print(ronaldo.count) 451 | 452 | # messi.count = 100 453 | # 454 | # print(Player.count)//2 455 | # 456 | # print(messi.count)//100 457 | # print(ronaldo.count)//2 458 | ``` 459 | --- 460 | 461 | ### /python-hello-world/first_method.py 462 | 463 | ```py 464 | # print("Hello World") 465 | 466 | 467 | def print_hello_world_twice(): 468 | print("Hello World 1") 469 | print("Hello World 2") 470 | 471 | 472 | def print_hello_world_multiple_times(times): 473 | for i in range(1, times+1): 474 | print("Hello World") 475 | 476 | 477 | # print("Hello World 3") 478 | 479 | # print_hello_world_twice() 480 | 481 | print_hello_world_multiple_times(4) 482 | ``` 483 | --- 484 | 485 | ### /python-hello-world/for_loop_examples.py 486 | 487 | ```py 488 | for i in range(1,10): 489 | print(i) 490 | print("Done") 491 | 492 | for i in range(1,10): 493 | print(i*i) 494 | 495 | print("Test") 496 | ``` 497 | --- 498 | 499 | ### /python-hello-world/for_loop_exercises.py 500 | 501 | ```py 502 | 503 | def is_prime(number): 504 | 505 | if number < 2: 506 | return False 507 | 508 | for divisor in range(2,number): 509 | if number % divisor == 0: 510 | return False 511 | 512 | return True 513 | 514 | # print(is_prime(15)); 515 | 516 | 517 | def sum_upto_n(number): 518 | 519 | sum = 0 520 | 521 | for i in range(1, number+1): 522 | sum = sum + i 523 | 524 | return sum 525 | 526 | 527 | # print(sum_upto_n(6)) 528 | # print(sum_upto_n(10)) 529 | 530 | 531 | def calculate_sum_of_divisors(number): 532 | sum_of_divisors = 0 533 | 534 | for divisor in range(1,number+1): 535 | if number % divisor == 0: 536 | sum_of_divisors = sum_of_divisors + divisor 537 | 538 | return sum_of_divisors 539 | 540 | # print(calculate_sum_of_divisors(6)) 541 | # print(calculate_sum_of_divisors(15)) 542 | 543 | 544 | def print_a_number_triangle(number): 545 | for j in range(1, number + 1): 546 | for i in range(1, j + 1): 547 | print(i, end=' ') 548 | print() 549 | 550 | 551 | print_a_number_triangle(6) 552 | ``` 553 | --- 554 | 555 | ### /python-hello-world/hello_world.py 556 | 557 | ```py 558 | print('Hello World') 559 | print("Hello World2") 560 | print("Hello World3") 561 | ``` 562 | --- 563 | 564 | ### /python-hello-world/if_examples.py 565 | 566 | ```py 567 | x_string = input("Enter a Number") 568 | x = int(x_string) 569 | 570 | if x == 1: 571 | print(f"{x} is 1") 572 | print("this is part of if") 573 | elif x == 2: 574 | print(f"{x} is 2") 575 | print("this is part of elif") 576 | else: 577 | print(f"{x} is NOT 1 or 2") 578 | print("this is part of else") 579 | ``` 580 | --- 581 | 582 | ### /python-hello-world/math_basic.py 583 | 584 | ```py 585 | def print_squares_of_numbers_upto(n): 586 | for i in range(1,n+1): 587 | print(i*i) 588 | 589 | 590 | def print_squares_of_even_numbers_upto(n): 591 | for i in range(2,n+1,2): 592 | print(i*i) 593 | 594 | 595 | def sum_of_two_numbers(number1,number2): 596 | sum = number1 + number2 597 | return sum 598 | 599 | 600 | def print_numbers_in_reverse(n): 601 | for i in range(n,0,-1): 602 | print(i) 603 | 604 | 605 | print(sum_of_two_numbers(5,6)) 606 | # print_squares_of_even_numbers_upto(10) 607 | # print_numbers_in_reverse(10) 608 | ``` 609 | --- 610 | 611 | ### /python-hello-world/menu_with_if.py 612 | 613 | ```py 614 | number1 = int(input("Enter Number1:")) 615 | number2 = int(input("Enter Number2:")) 616 | 617 | print("Choices Available are ") 618 | print("1 - Add") 619 | print("2 - Subtract") 620 | print("3 - Divide") 621 | print("4 - Multiply") 622 | 623 | choice = int(input("Enter Choice: ")) 624 | 625 | print("Your Choices are") 626 | 627 | if choice == 1: 628 | print(f"Result = {number1 + number2}") 629 | elif choice == 2: 630 | print(f"Result = {number1 - number2}") 631 | elif choice == 3: 632 | print(f"Result = {number1 / number2}") 633 | elif choice == 4: 634 | print(f"Result = {number1 * number2}") 635 | else: 636 | print("Invalid Operation") 637 | ``` 638 | --- 639 | 640 | ### /python-hello-world/multiplication_table.py 641 | 642 | ```py 643 | def print_multiplication_table(table=5, start=1, end=10): 644 | for i in range(start, end+1): 645 | print(f"{table} X {i} = {table*i}") 646 | 647 | 648 | print_multiplication_table() 649 | 650 | # print_multiplication_table(6) 651 | 652 | # print_multiplication_table(7, 31, 40) 653 | ``` 654 | --- 655 | 656 | ### /python-hello-world/oops_trials.py 657 | 658 | ```py 659 | class Book: 660 | 661 | count = 0 662 | 663 | def __init__(self, name): 664 | self._name = name 665 | Book.count = Book.count + 1 666 | 667 | @property 668 | def name(self): 669 | print("Getter For Name Called") 670 | return self._name 671 | 672 | @name.setter 673 | def name(self, name): 674 | print("Setter For Name Called") 675 | self._name = name 676 | 677 | @staticmethod 678 | def static_method(): 679 | print("I'm static") 680 | 681 | def __setattr__(self, key, value): 682 | print(f'{key} - {value}') 683 | self.__dict__[key] = value 684 | 685 | 686 | # book1 = Book('Microservices') 687 | # print(book1.name) 688 | # book1.name = 'ABC' 689 | # print(book1.name) 690 | # book2 = Book('Web Services') 691 | 692 | # print(Book.count) 693 | # print(book1.count) 694 | # print(book2.count) 695 | # Book.static_method() 696 | # book1.static_method() 697 | 698 | # print(book1.name) 699 | 700 | def do_this_and_print(func,data): 701 | print(func(data)) 702 | 703 | 704 | def double(data): 705 | return data * 2 706 | 707 | def triple(data): 708 | return data * 3 709 | 710 | 711 | do_this_and_print(double,5) 712 | 713 | do_this_and_print(triple,5) 714 | 715 | do_this_and_print(lambda x : x*2, 5) 716 | 717 | do_this_and_print(lambda x : x*5, 5) 718 | ``` 719 | --- 720 | 721 | ### /python-hello-world/repeated_question.py 722 | 723 | ```py 724 | number = int(input('Enter a number:')) 725 | 726 | while number >= 0: 727 | print(f'cube is {number ** 3}') 728 | number = int(input('Enter a number:')) 729 | ``` 730 | --- 731 | 732 | ### /python-hello-world/while_loop_examples.py 733 | 734 | ```py 735 | i = 0 736 | 737 | while i<11: 738 | print(i) 739 | i += 1 740 | 741 | 742 | # print all the squares of numbers < 100 743 | # 1 4 9 .. 81 744 | def print_squares_of_numbers_below(limit): 745 | i = 1 746 | while i*i < limit : 747 | print(i*i, end=' ') 748 | i += 1 749 | print() 750 | 751 | print_squares_of_numbers_below(100) 752 | ``` 753 | --- 754 | 755 | ### /python-shell-extract.txt 756 | 757 | ``` 758 | Last login: Mon Jun 18 17:36:38 on ttys002 759 | Rangas-MacBook-Pro:~ rangaraokaranam$ python3 760 | Python 3.6.5 (default, Mar 30 2018, 06:42:10) 761 | [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin 762 | Type "help", "copyright", "credits" or "license" for more information. 763 | >>> 34567890 764 | 34567890 765 | >>> type(34567890) 766 | 767 | >>> type(45.6) 768 | 769 | >>> type(45.6475894237589072348957938240) 770 | 771 | >>> type(True) 772 | 773 | >>> type(False) 774 | 775 | >>> type(false) 776 | Traceback (most recent call last): 777 | File "", line 1, in 778 | NameError: name 'false' is not defined 779 | >>> type(talse) 780 | Traceback (most recent call last): 781 | File "", line 1, in 782 | NameError: name 'talse' is not defined 783 | >>> type(true) 784 | Traceback (most recent call last): 785 | File "", line 1, in 786 | NameError: name 'true' is not defined 787 | >>> type("Text") 788 | 789 | >>> type("T") 790 | 791 | >>> type('T') 792 | 793 | >>> number1 = 10 794 | >>> number2 = 20 795 | >>> type(number1) 796 | 797 | >>> number1 + number2 798 | 30 799 | >>> number1 - number2 800 | -10 801 | >>> number1 * number2 802 | 200 803 | >>> number1 / number2 804 | 0.5 805 | >>> type(number1/number2) 806 | 807 | >>> number1 = 20 808 | >>> type(number1/number2) 809 | 810 | >>> number1/number2 811 | 1.0 812 | >>> number1=30 813 | >>> number1/number2 814 | 1.5 815 | >>> number1//number2 816 | 1 817 | >>> 10 ** 3 818 | 1000 819 | >>> 5 ** 3 820 | 125 821 | >>> pow(5,3) 822 | 125 823 | >>> number1++ 824 | File "", line 1 825 | number1++ 826 | ^ 827 | SyntaxError: invalid syntax 828 | >>> number1-- 829 | File "", line 1 830 | number1-- 831 | ^ 832 | SyntaxError: invalid syntax 833 | >>> number1 += 1 834 | >>> number1 = number1 + 1 835 | >>> max(2,4,3) 836 | 4 837 | >>> min(2,4,3) 838 | 2 839 | >>> round(5.6) 840 | 6 841 | >>> round(5.65643,3) 842 | 5.656 843 | >>> round(5.65663,3) 844 | 5.657 845 | >>> float(5) 846 | 5.0 847 | >>> int(5.5) 848 | 5 849 | >>> True 850 | True 851 | >>> False 852 | False 853 | >>> is_done = True 854 | >>> i = 6 855 | >>> i > 6 856 | False 857 | >>> True and True 858 | True 859 | >>> True and False 860 | False 861 | >>> False or False 862 | False 863 | >>> !True 864 | File "", line 1 865 | !True 866 | ^ 867 | SyntaxError: invalid syntax 868 | >>> not True 869 | False 870 | >>> not False 871 | True 872 | >>> True ^ True 873 | False 874 | >>> True ^ False 875 | True 876 | >>> False ^ False 877 | False 878 | >>> i = 5 879 | >>> i > 5 880 | False 881 | >>> i >= 5 882 | True 883 | >>> i <5 884 | False 885 | >>> i <= 5 886 | True 887 | >>> i == 5 888 | True 889 | >>> i != 6 890 | True 891 | >>> os.system('clear') 892 | 893 | 894 | 895 | 896 | 0 897 | >>> i = 45 898 | >>> if i: print("Something") 899 | ... 900 | Something 901 | >>> bool(45) 902 | True 903 | >>> bool(-45) 904 | True 905 | >>> bool(-1) 906 | True 907 | >>> bool(1) 908 | True 909 | >>> bool(0) 910 | False 911 | >>> i = 0 912 | >>> if i: print("Something") 913 | ... 914 | >>> bool(0.0) 915 | False 916 | >>> bool(-1.0) 917 | True 918 | >>> str = "Test" 919 | >>> bool(str) 920 | True 921 | >>> bool("") 922 | False 923 | >>> bool('') 924 | False 925 | >>> i = 45 926 | >>> if i%2 == 1: print("odd") 927 | ... 928 | odd 929 | >>> i = 44 930 | >>> if i%2 == 1: print("odd") 931 | ... 932 | >>> if i%2: print("odd") 933 | ... 934 | >>> i = 45 935 | >>> if i%2: print("odd") 936 | ... 937 | odd 938 | >>> for ch in 'Hello World': 939 | ... print(ch) 940 | ... 941 | H 942 | e 943 | l 944 | l 945 | o 946 | 947 | W 948 | o 949 | r 950 | l 951 | d 952 | >>> for word in 'Hello World'.split(): 953 | ... print(word) 954 | ... 955 | Hello 956 | World 957 | >>> for item in (3, 8, 9): 958 | ... print(item) 959 | ... 960 | 3 961 | 8 962 | 9 963 | >>> 1/0 964 | Traceback (most recent call last): 965 | File "", line 1, in 966 | ZeroDivisionError: division by zero 967 | >>> i = 0 968 | File "", line 1 969 | i = 0 970 | ^ 971 | IndentationError: unexpected indent 972 | >>> j = 10/i 973 | >>> 2 + '2' 974 | Traceback (most recent call last): 975 | File "", line 1, in 976 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 977 | >>> values = [1,'2'] 978 | >>> sum(values) 979 | Traceback (most recent call last): 980 | File "", line 1, in 981 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 982 | >>> value 983 | Traceback (most recent call last): 984 | File "", line 1, in 985 | NameError: name 'value' is not defined 986 | >>> values.non_existing 987 | Traceback (most recent call last): 988 | File "", line 1, in 989 | AttributeError: 'list' object has no attribute 'non_existing' 990 | >>> values.non_existing() 991 | Traceback (most recent call last): 992 | File "", line 1, in 993 | AttributeError: 'list' object has no attribute 'non_existing' 994 | >>> import builtins 995 | >>> 996 | >>> help(builtins) 997 | 998 | >>> 999 | >>> help(builtins) 1000 | 1001 | >>> k = 10/non_existing_variable 1002 | Traceback (most recent call last): 1003 | File "", line 1, in 1004 | NameError: name 'non_existing_variable' is not defined 1005 | >>> 10/0 1006 | Traceback (most recent call last): 1007 | File "", line 1, in 1008 | ZeroDivisionError: division by zero 1009 | >>> values = [1,'1'] 1010 | >>> sum(values) 1011 | Traceback (most recent call last): 1012 | File "", line 1, in 1013 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 1014 | 1015 | 0 1016 | >>> def multiply_by_2(data): 1017 | ... return data*2 1018 | ... 1019 | >>> multiply_by_2 1020 | 1021 | >>> def do_this_and_print(func, data): 1022 | ... print(func(data)) 1023 | ... 1024 | >>> do_this_and_print(multiply_by_2, 125) 1025 | 250 1026 | >>> func_example_reference = multiply_by_2 1027 | >>> func_example_reference(23) 1028 | 46 1029 | >>> def multiply_by_3(data): 1030 | ... return data * 3 1031 | ... 1032 | >>> do_this_and_print(multiply_by_3, 125) 1033 | 375 1034 | >>> do_this_and_print(lambda data:data*3, 125) 1035 | 375 1036 | >>> do_this_and_print(lambda data:data*5, 125) 1037 | 625 1038 | >>> do_this_and_print(lambda data:data*data, 125) 1039 | 15625 1040 | >>> do_this_and_print(lambda data:data*data*data, 125) 1041 | 1953125 1042 | >>> do_this_and_print(lambda data:data ** 3, 125) 1043 | 1953125 1044 | >>> do_this_and_print(lambda data:len(data), 'Test') 1045 | 4 1046 | >>> numbers = [1,89,54,35] 1047 | >>> filter( lambda x : x%2==1 ,numbers) 1048 | 1049 | >>> list(filter( lambda x : x%2==1 ,numbers)) 1050 | [1, 89, 35] 1051 | >>> list(filter( lambda x : x%2==0 ,numbers)) 1052 | [54] 1053 | >>> list(filter( lambda x : x%2 ,numbers)) 1054 | [1, 89, 35] 1055 | >>> words = ["Apple", "Ant", "Bat"] 1056 | >>> list(filter(lambda x: x.endswith('at'), words)) 1057 | ['Bat'] 1058 | >>> list( filter( lambda x: x.endswith('at') , words ) ) 1059 | ['Bat'] 1060 | >>> list( filter( lambda x: len(x)==3 , words ) ) 1061 | ['Ant', 'Bat'] 1062 | >>> list( filter( lambda x: x.startswith('A') , words ) ) 1063 | ['Apple', 'Ant'] 1064 | >>> os.system('clear') 1065 | 1066 | 1067 | 1068 | 0 1069 | >>> words = ["Apple", "Ant", "Bat"] 1070 | >>> "Apple".upper 1071 | 1072 | >>> "Apple".upper() 1073 | 'APPLE' 1074 | >>> map(lambda x: x.upper() ,words) 1075 | 1076 | >>> list(map(lambda x: x.upper() ,words)) 1077 | ['APPLE', 'ANT', 'BAT'] 1078 | >>> list(map(lambda x: len(x) ,words)) 1079 | [5, 3, 3] 1080 | >>> number = [1, 5, 2 , 9] 1081 | >>> numbers = [1, 5, 2 , 9] 1082 | >>> list(map(lambda x: x*x ,numbers)) 1083 | [1, 25, 4, 81] 1084 | >>> list(map(lambda x: x*x ,range(1,11))) 1085 | [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 1086 | >>> list(map(lambda x: x ** 3 ,range(1,11))) 1087 | [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 1088 | >>> os.system('clear') 1089 | 1090 | 1091 | 0 1092 | >>> numbers = [3, 15,12,10] 1093 | >>> sum(numbers) 1094 | 40 1095 | >>> max(numbers) 1096 | 15 1097 | >>> reduce(lambda x,y:x+y ,numbers ) 1098 | 40 1099 | >>> reduce(lambda x,y:x*y ,numbers ) 1100 | 5400 1101 | >>> reduce(lambda x,y:max(x,y) ,numbers ) 1102 | 15 1103 | >>> reduce(lambda x,y:min(x,y) ,numbers ) 1104 | 3 1105 | >>> words = ['Apple', 'Ant','Bat'] 1106 | >>> reduce(lambda x,y: x if len(x)>len(y) else y ,words ) 1107 | 'Apple' 1108 | >>> os.system('clear') 1109 | 1110 | 1111 | 1112 | 1113 | 1114 | 0 1115 | >>> numbers = [3, 7, 8, 15, 24, 35, 46] 1116 | >>> list(filter(lambda x: x%2==0, numbers)) 1117 | [8, 24, 46] 1118 | >>> list(map( lambda x:x*x ,filter(lambda x: x%2==0, numbers)) ) 1119 | [64, 576, 2116] 1120 | >>> sum(map( lambda x:x*x ,filter(lambda x: x%2==0, numbers)) ) 1121 | 2756 1122 | >>> reduce(lambda x,y:x+y, map( lambda x:x*x ,filter(lambda x: x%2==0, numbers)) ) 1123 | 2756 1124 | >>> os.system('clear') 1125 | 1126 | >>> months = [('Jan',31),('Feb',28),('Mar',31)] 1127 | >>> tuple_ex = ('Dec',31) 1128 | >>> tuple_ex[0] 1129 | 'Dec' 1130 | >>> tuple_ex[1] 1131 | 31 1132 | >>> sum(map(lambda x:x[1] , months)) 1133 | 90 1134 | >>> reduce( lambda x,y : x if x[1]>> reduce( lambda x,y : x if x[1]>> (1,1) == (1,1) 1141 | True 1142 | >>> ('1',1) == ('1',1) 1143 | True 1144 | >>> ('1',1) == ('1',2) 1145 | False 1146 | >>> ('1',1) == ('2',1) 1147 | False 1148 | >>> (1,1) > (1,1) 1149 | False 1150 | >>> (1,1) > (0,1) 1151 | True 1152 | >>> (1,2) > (1,1) 1153 | True 1154 | >>> (1,2) > (1,3) 1155 | False 1156 | >>> (1,2) < (1,3) 1157 | True 1158 | >>> os.system('clear') 1159 | 1160 | 1161 | 1162 | >>> import datetime 1163 | >>> datetime.datetime.today() 1164 | datetime.datetime(2018, 6, 27, 17, 4, 2, 258274) 1165 | >>> today = datetime.datetime.today() 1166 | >>> today.__str__() 1167 | '2018-06-27 17:04:12.850102' 1168 | >>> today.__repr__() 1169 | 'datetime.datetime(2018, 6, 27, 17, 4, 12, 850102)' 1170 | >>> today2 = datetime.datetime(2018, 6, 27, 17, 4, 12, 850102) 1171 | >>> os.system('clear') 1172 | 1173 | >>> import random 1174 | >>> random.random() 1175 | 0.08354021584691451 1176 | >>> random.random() 1177 | 0.7427402538127307 1178 | >>> random.random() 1179 | 0.18347949440543265 1180 | >>> random.randint(1,10) 1181 | 1 1182 | >>> random.randint(1,10) 1183 | 4 1184 | >>> random.randint(1,10) 1185 | 2 1186 | >>> random.randint(1,10) 1187 | 1 1188 | >>> random.randrange(1,25,2) 1189 | 17 1190 | >>> random.randrange(1,25,2) 1191 | 19 1192 | >>> random.randrange(1,25,2) 1193 | 19 1194 | >>> random.randrange(0,30,3) 1195 | 21 1196 | >>> random.randrange(0,30,3) 1197 | 18 1198 | >>> list = [2, 7, 9,34,56] 1199 | >>> random.choice(list) 1200 | 7 1201 | >>> random.choice(list) 1202 | 34 1203 | >>> random.choice(list) 1204 | 9 1205 | >>> random.choice(list) 1206 | 56 1207 | >>> random.choice(list) 1208 | 34 1209 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 1210 | 'r' 1211 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 1212 | 'x' 1213 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 1214 | 'a' 1215 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 1216 | 's' 1217 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 1218 | 'q' 1219 | >>> random.sample(list, 2) 1220 | [34, 9] 1221 | >>> random.sample(list, 3) 1222 | [7, 2, 9] 1223 | >>> random.sample(list, 5) 1224 | [7, 2, 9, 34, 56] 1225 | >>> def some_function(): 1226 | ... return 1, 'string', 4.5 1227 | ... 1228 | >>> tuple1 = some_function() 1229 | >>> tuple1[0] 1230 | 1 1231 | >>> tuple1[1] 1232 | 'string' 1233 | >>> 1234 | >>> tuple1[2] 1235 | 4.5 1236 | >>> os.system('clear') 1237 | 1238 | >>> from collections import namedtuple 1239 | >>> Point = namedtuple('Point',['x','y']) 1240 | >>> point1 = Point(1,2) 1241 | >>> point1.x 1242 | 1 1243 | >>> point1.y 1244 | 2 1245 | >>> 3DPoint = namedtuple('3DPoint',['x','y','z']) 1246 | File "", line 1 1247 | 3DPoint = namedtuple('3DPoint',['x','y','z']) 1248 | ^ 1249 | SyntaxError: invalid syntax 1250 | >>> ThreeDPoint = namedtuple('ThreeDPoint',['x','y','z']) 1251 | >>> point2 = ThreeDPoint(7, 4, 6) 1252 | >>> point2.x 1253 | 7 1254 | >>> point2.z 1255 | 6 1256 | >>> 1257 | 1258 | >>> message = "Hello World" 1259 | >>> message = 'Hello World' 1260 | >>> message = 'Hello World" 1261 | File "", line 1 1262 | message = 'Hello World" 1263 | ^ 1264 | SyntaxError: EOL while scanning string literal 1265 | >>> message = "Hello World" 1266 | >>> type(message) 1267 | 1268 | >>> message.upper() 1269 | 'HELLO WORLD' 1270 | >>> message.lower() 1271 | 'hello world' 1272 | >>> message = "hello" 1273 | >>> message.capitalize() 1274 | 'Hello' 1275 | >>> "hello".capitalize() 1276 | 'Hello' 1277 | >>> 'hello'.capitalize() 1278 | 'Hello' 1279 | >>> 'hello'.islower() 1280 | True 1281 | >>> 'Hello'.islower() 1282 | False 1283 | >>> 'Hello'.istitle() 1284 | True 1285 | >>> 'hello'.istitle() 1286 | False 1287 | >>> 'hello'.isupper() 1288 | False 1289 | >>> 'Hello'.isupper() 1290 | False 1291 | >>> 'HELLO'.isupper() 1292 | True 1293 | >>> '123'.isdigit() 1294 | True 1295 | >>> 'A23'.isdigit() 1296 | False 1297 | >>> '2 3'.isdigit() 1298 | False 1299 | >>> '23'.isdigit() 1300 | True 1301 | >>> '23'.isalpha() 1302 | False 1303 | >>> '2A'.isalpha() 1304 | False 1305 | >>> 'ABC'.isalpha() 1306 | True 1307 | >>> 'ABC123'.isalnum() 1308 | True 1309 | >>> 'ABC 123'.isalnum() 1310 | False 1311 | >>> 'Hello World'.endswith('World') 1312 | True 1313 | >>> 'Hello World'.endswith('ld') 1314 | True 1315 | >>> 'Hello World'.endswith('old') 1316 | False 1317 | >>> 'Hello World'.endswith('Wo') 1318 | False 1319 | >>> 'Hello World'.startswith('Wo') 1320 | False 1321 | >>> 'Hello World'.startswith('He') 1322 | True 1323 | >>> 'Hello World'.startswith('Hell0') 1324 | False 1325 | >>> 'Hello World'.startswith('Hello') 1326 | True 1327 | >>> 'Hello World'.find('Hello') 1328 | 0 1329 | >>> 'Hello World'.find('ello') 1330 | 1 1331 | >>> 'Hello World'.find('Ello') 1332 | -1 1333 | >>> 'Hello World'.find('bello') 1334 | -1 1335 | >>> 'Hello World'.find('Ello') 1336 | -1 1337 | >>> os.system('clear') 1338 | Traceback (most recent call last): 1339 | File "", line 1, in 1340 | NameError: name 'os' is not defined 1341 | >>> import os 1342 | >>> os.system('clear') 1343 | 1344 | 0 1345 | >>> str(True) 1346 | 'True' 1347 | >>> bool('True') 1348 | True 1349 | >>> bool('true') 1350 | True 1351 | >>> bool('tru') 1352 | True 1353 | >>> bool('false') 1354 | True 1355 | >>> bool('False') 1356 | True 1357 | >>> bool('') 1358 | False 1359 | >>> str(123) 1360 | '123' 1361 | >>> str(12345) 1362 | '12345' 1363 | >>> str(12345.45678) 1364 | '12345.45678' 1365 | >>> int('45') 1366 | 45 1367 | >>> int('45.56') 1368 | Traceback (most recent call last): 1369 | File "", line 1, in 1370 | ValueError: invalid literal for int() with base 10: '45.56' 1371 | >>> int('45dfsafk') 1372 | Traceback (most recent call last): 1373 | File "", line 1, in 1374 | ValueError: invalid literal for int() with base 10: '45dfsafk' 1375 | >>> int('45abc',16) 1376 | 285372 1377 | >>> int('a',16) 1378 | 10 1379 | >>> int('b',16) 1380 | 11 1381 | >>> int('c',16) 1382 | 12 1383 | >>> int('f',16) 1384 | 15 1385 | >>> int('g',16) 1386 | Traceback (most recent call last): 1387 | File "", line 1, in 1388 | ValueError: invalid literal for int() with base 16: 'g' 1389 | >>> float("34.43") 1390 | 34.43 1391 | >>> float("34.43rer") 1392 | Traceback (most recent call last): 1393 | File "", line 1, in 1394 | ValueError: could not convert string to float: '34.43rer' 1395 | >>> os.system('clear') 1396 | 1397 | 0 1398 | >>> message = "Hello" 1399 | >>> message.upper() 1400 | 'HELLO' 1401 | >>> message 1402 | 'Hello' 1403 | >>> message = message.upper() 1404 | >>> message 1405 | 'HELLO' 1406 | >>> message = "Hello" 1407 | >>> message.upper() 1408 | 'HELLO' 1409 | >>> message_upper = message.upper() 1410 | >>> message = "ABC" 1411 | >>> message = message.lowercase() 1412 | Traceback (most recent call last): 1413 | File "", line 1, in 1414 | AttributeError: 'str' object has no attribute 'lowercase' 1415 | >>> message = message.lower() 1416 | >>> os.system('clear') 1417 | 1418 | 1419 | 0 1420 | >>> message = "Hello World" 1421 | >>> message[0] 1422 | 'H' 1423 | >>> type(message[0]) 1424 | 1425 | >>> type(message) 1426 | 1427 | >>> message[0] 1428 | 'H' 1429 | >>> message[1] 1430 | 'e' 1431 | >>> message[2] 1432 | 'l' 1433 | >>> message[3] 1434 | 'l' 1435 | >>> message[100] 1436 | Traceback (most recent call last): 1437 | File "", line 1, in 1438 | IndexError: string index out of range 1439 | >>> for ch in message: 1440 | ... print(ch) 1441 | ... 1442 | H 1443 | e 1444 | l 1445 | l 1446 | o 1447 | 1448 | W 1449 | o 1450 | r 1451 | l 1452 | d 1453 | >>> os.system('clear') 1454 | 1455 | 0 1456 | >>> import string 1457 | >>> string. 1458 | string.Formatter( string.ascii_uppercase string.octdigits 1459 | string.Template( string.capwords( string.printable 1460 | string.ascii_letters string.digits string.punctuation 1461 | string.ascii_lowercase string.hexdigits string.whitespace 1462 | >>> string.ascii_letters 1463 | 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 1464 | >>> string.ascii_lowercase 1465 | 'abcdefghijklmnopqrstuvwxyz' 1466 | >>> string.ascii_uppercase 1467 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 1468 | >>> string.digits 1469 | '0123456789' 1470 | >>> string.hexdigits 1471 | '0123456789abcdefABCDEF' 1472 | >>> string.punctuation 1473 | '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' 1474 | >>> 'a' in string.ascii_letters 1475 | True 1476 | >>> string.ascii_letters 1477 | 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 1478 | >>> 'ab' in string.ascii_letters 1479 | True 1480 | >>> 'abc' in string.ascii_letters 1481 | True 1482 | >>> 'a' in string.ascii_letters 1483 | True 1484 | >>> '1' in '13579' 1485 | True 1486 | >>> '2' in '13579' 1487 | False 1488 | >>> '4' in '13579' 1489 | False 1490 | >>> char = 'a' 1491 | >>> vowel_string = 'aeiouAEIOU' 1492 | >>> char in vowel_string 1493 | True 1494 | >>> char = 'b' 1495 | >>> char in vowel_string 1496 | False 1497 | >>> vowel_string = 'AEIOU' 1498 | >>> char.upper() in vowel_string 1499 | False 1500 | >>> char = 'a' 1501 | >>> char.upper() in vowel_string 1502 | True 1503 | >>> vowel_string = 'aeiou' 1504 | >>> char.lower() in vowel_string 1505 | True 1506 | >>> char = 'A' 1507 | >>> char.lower() in vowel_string 1508 | True 1509 | >>> import string 1510 | >>> string. 1511 | string.Formatter( string.ascii_uppercase string.octdigits 1512 | string.Template( string.capwords( string.printable 1513 | string.ascii_letters string.digits string.punctuation 1514 | string.ascii_lowercase string.hexdigits string.whitespace 1515 | >>> string.ascii_uppercase 1516 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 1517 | >>> for char in string.ascii_uppercase: 1518 | ... print(char) 1519 | ... 1520 | A 1521 | B 1522 | C 1523 | D 1524 | E 1525 | F 1526 | G 1527 | H 1528 | I 1529 | J 1530 | K 1531 | L 1532 | M 1533 | N 1534 | O 1535 | P 1536 | Q 1537 | R 1538 | S 1539 | T 1540 | U 1541 | V 1542 | W 1543 | X 1544 | Y 1545 | Z 1546 | >>> for char in string.ascii_lowercase: 1547 | ... print(char) 1548 | ... 1549 | a 1550 | b 1551 | c 1552 | d 1553 | e 1554 | f 1555 | g 1556 | h 1557 | i 1558 | j 1559 | k 1560 | l 1561 | m 1562 | n 1563 | o 1564 | p 1565 | q 1566 | r 1567 | s 1568 | t 1569 | u 1570 | v 1571 | w 1572 | x 1573 | y 1574 | z 1575 | >>> for char in string. 1576 | string.Formatter( string.ascii_uppercase string.octdigits 1577 | string.Template( string.capwords( string.printable 1578 | string.ascii_letters string.digits string.punctuation 1579 | string.ascii_lowercase string.hexdigits string.whitespace 1580 | >>> for char in string.digits: 1581 | ... print(char) 1582 | ... 1583 | 0 1584 | 1 1585 | 2 1586 | 3 1587 | 4 1588 | 5 1589 | 6 1590 | 7 1591 | 8 1592 | 9 1593 | >>> vowel_string = 'aeiou' 1594 | >>> char.lower() in vowel_string 1595 | False 1596 | >>> 'b'.lower() not in vowel_string 1597 | True 1598 | >>> 'a'.lower() not in vowel_string 1599 | False 1600 | >>> '1'.lower() not in vowel_string 1601 | True 1602 | >>> '1'.isalpha() and '1'.lower() not in vowel_string 1603 | False 1604 | >>> char.isalpha() and char.lower() not in vowel_string 1605 | True 1606 | >>> char 1607 | 'b' 1608 | >>> char = '1' 1609 | >>> char.isalpha() and char.lower() not in vowel_string 1610 | False 1611 | >>> os.system('clear') 1612 | 1613 | 0 1614 | >>> string_example = "This is a great thing" 1615 | >>> string_example. 1616 | string_example.capitalize( string_example.join( 1617 | string_example.casefold( string_example.ljust( 1618 | string_example.center( string_example.lower( 1619 | string_example.count( string_example.lstrip( 1620 | string_example.encode( string_example.maketrans( 1621 | string_example.endswith( string_example.partition( 1622 | string_example.expandtabs( string_example.replace( 1623 | string_example.find( string_example.rfind( 1624 | string_example.format( string_example.rindex( 1625 | string_example.format_map( string_example.rjust( 1626 | string_example.index( string_example.rpartition( 1627 | string_example.isalnum( string_example.rsplit( 1628 | string_example.isalpha( string_example.rstrip( 1629 | string_example.isdecimal( string_example.split( 1630 | string_example.isdigit( string_example.splitlines( 1631 | string_example.isidentifier( string_example.startswith( 1632 | string_example.islower( string_example.strip( 1633 | string_example.isnumeric( string_example.swapcase( 1634 | string_example.isprintable( string_example.title( 1635 | string_example.isspace( string_example.translate( 1636 | string_example.istitle( string_example.upper( 1637 | string_example.isupper( string_example.zfill( 1638 | >>> string_example.split() 1639 | ['This', 'is', 'a', 'great', 'thing'] 1640 | >>> for word in string_example.split(): 1641 | ... print(word) 1642 | ... 1643 | This 1644 | is 1645 | a 1646 | great 1647 | thing 1648 | >>> string_example = "This\nis\n\ngreat\nthing" 1649 | >>> print(string_example) 1650 | This 1651 | is 1652 | 1653 | great 1654 | thing 1655 | >>> string_example = "This\nis\na\ngreat\nthing" 1656 | >>> print(string_example) 1657 | This 1658 | is 1659 | a 1660 | great 1661 | thing 1662 | >>> string_example.split 1663 | string_example.split( string_example.splitlines( 1664 | >>> string_example.splitlines() 1665 | ['This', 'is', 'a', 'great', 'thing'] 1666 | >>> 1 + 2 1667 | 3 1668 | >>> "1" + "2" 1669 | '12' 1670 | >>> "1" + 1 1671 | Traceback (most recent call last): 1672 | File "", line 1, in 1673 | TypeError: must be str, not int 1674 | >>> "ABC" + "DEF" 1675 | 'ABCDEF' 1676 | >>> 1 * 20 1677 | 20 1678 | >>> '1' * 20 1679 | '11111111111111111111' 1680 | >>> 'A' * 10 1681 | 'AAAAAAAAAA' 1682 | >>> str = "test" 1683 | >>> str2 = "test1" 1684 | >>> str == str2 1685 | False 1686 | >>> str2 = "test" 1687 | >>> str == str2 1688 | True 1689 | >>> 1690 | 1691 | Last login: Fri May 18 14:08:00 on ttys004 1692 | Rangas-MacBook-Pro:~ rangaraokaranam$ python3 1693 | Python 3.6.5 (default, Mar 30 2018, 06:42:10) 1694 | [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin 1695 | Type "help", "copyright", "credits" or "license" for more information. 1696 | >>> mark1 = 45 1697 | >>> mark2 = 54 1698 | >>> mark3 = 80 1699 | >>> mark1 + mark2 + mark3 1700 | 179 1701 | >>> (mark1 + mark2 + mark3)/3 1702 | 59.666666666666664 1703 | >>> mark4 = 43 1704 | >>> (mark1 + mark2 + mark3 + mark4)/3 1705 | 74.0 1706 | >>> (mark1 + mark2 + mark3 + mark4)/4 1707 | 55.5 1708 | >>> marks = [45, 54, 80] 1709 | >>> sum(marks) 1710 | 179 1711 | >>> sum(marks)/len(marks) 1712 | 59.666666666666664 1713 | >>> marks.append(43) 1714 | >>> sum(marks)/len(marks) 1715 | 55.5 1716 | >>> type(marks) 1717 | 1718 | >>> import os 1719 | >>> os.system('clear') 1720 | 1721 | 0 1722 | >>> marks = [23,56,67] 1723 | >>> sum(marks) 1724 | 146 1725 | >>> max(marks) 1726 | 67 1727 | >>> min(marks) 1728 | 23 1729 | >>> len(marks) 1730 | 3 1731 | >>> marks.append(76) 1732 | >>> marks 1733 | [23, 56, 67, 76] 1734 | >>> marks.insert(2, 60) 1735 | >>> marks 1736 | [23, 56, 60, 67, 76] 1737 | >>> marks.remove(60) 1738 | >>> 55 in marks 1739 | False 1740 | >>> 56 in marks 1741 | True 1742 | >>> marks.index(67) 1743 | 2 1744 | >>> marks 1745 | [23, 56, 67, 76] 1746 | >>> marks.index(69) 1747 | Traceback (most recent call last): 1748 | File "", line 1, in 1749 | ValueError: 69 is not in list 1750 | >>> for mark in marks: 1751 | ... print(mark) 1752 | ... 1753 | 23 1754 | 56 1755 | 67 1756 | 76 1757 | >>> os.system('clear') 1758 | 1759 | 0 1760 | >>> animals = ['Cat', 'Dog','Elephant'] 1761 | >>> len(animals) 1762 | 3 1763 | >>> sum(animals) 1764 | Traceback (most recent call last): 1765 | File "", line 1, in 1766 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 1767 | >>> animals.append('Fish') 1768 | >>> animals 1769 | ['Cat', 'Dog', 'Elephant', 'Fish'] 1770 | >>> animals.remove('Dog') 1771 | >>> animals 1772 | ['Cat', 'Elephant', 'Fish'] 1773 | >>> animals[2] 1774 | 'Fish' 1775 | >>> animals[1] 1776 | 'Elephant' 1777 | >>> animals[0] 1778 | 'Cat' 1779 | >>> animals[4] 1780 | Traceback (most recent call last): 1781 | File "", line 1, in 1782 | IndexError: list index out of range 1783 | >>> del animals[2] 1784 | >>> animals 1785 | ['Cat', 'Elephant'] 1786 | >>> animals.extend('Fish') 1787 | >>> animals 1788 | ['Cat', 'Elephant', 'F', 'i', 's', 'h'] 1789 | >>> animals.append('Fish') 1790 | >>> animals 1791 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish'] 1792 | >>> animals.extend(['Giraffe', 'Horse']) 1793 | >>> animals 1794 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse'] 1795 | >>> animals = animals + ['Jackal','Kangaroo'] 1796 | >>> animals 1797 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal', 'Kangaroo'] 1798 | >>> animals += ['Lion','Monkey'] 1799 | >>> animals 1800 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal', 'Kangaroo', 'Lion', 'Monkey'] 1801 | >>> animals.append(10) 1802 | >>> animals 1803 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal', 'Kangaroo', 'Lion', 'Monkey', 10] 1804 | >>> os.system('clear') 1805 | 1806 | 0 1807 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1808 | >>> len(numbers) 1809 | 10 1810 | >>> number[2] 1811 | Traceback (most recent call last): 1812 | File "", line 1, in 1813 | NameError: name 'number' is not defined 1814 | >>> numbers[2] 1815 | 'Two' 1816 | >>> numbers[2:6] 1817 | ['Two', 'Three', 'Four', 'Five'] 1818 | >>> numbers[:6] 1819 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five'] 1820 | >>> numbers[3:] 1821 | ['Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1822 | >>> numbers[1:8:2] 1823 | ['One', 'Three', 'Five', 'Seven'] 1824 | >>> numbers[1:8:3] 1825 | ['One', 'Four', 'Seven'] 1826 | >>> numbers[::3] 1827 | ['Zero', 'Three', 'Six', 'Nine'] 1828 | >>> numbers[::-1] 1829 | ['Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'Zero'] 1830 | >>> numbers[::-3] 1831 | ['Nine', 'Six', 'Three', 'Zero'] 1832 | >>> del numbers[3:] 1833 | >>> numbers 1834 | ['Zero', 'One', 'Two'] 1835 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1836 | >>> del numbers[5:7] 1837 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1838 | >>> numbers[3:7] = [3,4,5,6] 1839 | >>> numbers 1840 | ['Zero', 'One', 'Two', 3, 4, 5, 6, 'Seven', 'Eight', 'Nine'] 1841 | >>> os.system('clear') 1842 | 1843 | 1844 | 1845 | 1846 | 1847 | 1848 | 1849 | 0 1850 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1851 | >>> numbers.reverse() 1852 | >>> numbers 1853 | ['Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'Zero'] 1854 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1855 | >>> numbers 1856 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1857 | >>> reversed(numbers) 1858 | 1859 | >>> for number in reversed(numbers): 1860 | ... print(number) 1861 | ... 1862 | Nine 1863 | Eight 1864 | Seven 1865 | Six 1866 | Five 1867 | Four 1868 | Three 1869 | Two 1870 | One 1871 | Zero 1872 | >>> numbers 1873 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1874 | >>> numbers.sort() 1875 | >>> numbers 1876 | ['Eight', 'Five', 'Four', 'Nine', 'One', 'Seven', 'Six', 'Three', 'Two', 'Zero'] 1877 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1878 | >>> for number in sorted(numbers): 1879 | ... print(number) 1880 | ... 1881 | Eight 1882 | Five 1883 | Four 1884 | Nine 1885 | One 1886 | Seven 1887 | Six 1888 | Three 1889 | Two 1890 | Zero 1891 | >>> numbers 1892 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1893 | >>> for number in sorted(numbers, key=len): 1894 | ... print(number) 1895 | ... 1896 | One 1897 | Two 1898 | Six 1899 | Zero 1900 | Four 1901 | Five 1902 | Nine 1903 | Three 1904 | Seven 1905 | Eight 1906 | >>> for number in sorted(numbers, key=len, reverse=True): 1907 | ... print(number) 1908 | ... 1909 | Three 1910 | Seven 1911 | Eight 1912 | Zero 1913 | Four 1914 | Five 1915 | Nine 1916 | One 1917 | Two 1918 | Six 1919 | >>> numbers.sort(key=len) 1920 | >>> numbers 1921 | ['One', 'Two', 'Six', 'Zero', 'Four', 'Five', 'Nine', 'Three', 'Seven', 'Eight'] 1922 | >>> numbers.sort(key=len, reverse=True) 1923 | >>> numbers 1924 | ['Three', 'Seven', 'Eight', 'Zero', 'Four', 'Five', 'Nine', 'One', 'Two', 'Six'] 1925 | >>> os.system('clear') 1926 | 1927 | 0 1928 | >>> numbers = [] 1929 | >>> numbers.append(1) 1930 | >>> numbers.append(2) 1931 | >>> numbers.append(3) 1932 | >>> numbers.append(4) 1933 | >>> numbers.pop() 1934 | 4 1935 | >>> numbers 1936 | [1, 2, 3] 1937 | >>> numbers.pop() 1938 | 3 1939 | >>> numbers 1940 | [1, 2] 1941 | >>> numbers.append(10) 1942 | >>> numbers.pop() 1943 | 10 1944 | >>> numbers 1945 | [1, 2] 1946 | >>> numbers = [] 1947 | >>> numbers.append(1) 1948 | >>> numbers.append(2) 1949 | >>> numbers.append(3) 1950 | >>> numbers.append(4) 1951 | >>> numbers.pop(0) 1952 | 1 1953 | >>> numbers 1954 | [2, 3, 4] 1955 | >>> numbers.pop(0) 1956 | 2 1957 | >>> numbers 1958 | [3, 4] 1959 | >>> numbers.append(10) 1960 | >>> numbers.pop(0) 1961 | 3 1962 | >>> numbers.pop(0) 1963 | 4 1964 | >>> numbers.pop(0) 1965 | 10 1966 | >>> numbers 1967 | [] 1968 | >>> os.system('clear') 1969 | 1970 | 0 1971 | >>> numbers = ['Zero', 'One','Two','Three','Four','Five','Six','Seven', 'Eight','Nine'] 1972 | >>> numbers_length_four=[] 1973 | >>> for number in numbers: 1974 | ... if len(number)== 4: 1975 | ... numbers_length_four.append(number) 1976 | ... 1977 | >>> numbers_length_four 1978 | ['Zero', 'Four', 'Five', 'Nine'] 1979 | >>> numbers_length_four = [ number for number in numbers ] 1980 | >>> numbers_length_four 1981 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1982 | >>> numbers_length_four = [ len(number) for number in numbers ] 1983 | >>> numbers_length_four 1984 | [4, 3, 3, 5, 4, 4, 3, 5, 5, 4] 1985 | >>> numbers_length_four = [ number.upper() for number in numbers ] 1986 | >>> numbers_length_four 1987 | ['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE'] 1988 | >>> numbers_length_four = [ number for number in numbers if len(number)==4 ] 1989 | >>> numbers_length_four 1990 | ['Zero', 'Four', 'Five', 'Nine'] 1991 | >>> values = [3, 6, 9, 1, 4, 15, 6, 3] 1992 | >>> values_even = [ value for value in values if value%2==0] 1993 | >>> values_even 1994 | [6, 4, 6] 1995 | >>> values_odd = [ value for value in values if value%2==1] 1996 | >>> values_odd 1997 | [3, 9, 1, 15, 3] 1998 | >>> os.system('clear') 1999 | 2000 | 0 2001 | >>> numbers = [1,2,3,2,1] 2002 | >>> numbers 2003 | [1, 2, 3, 2, 1] 2004 | >>> numbers_set = set(numbers) 2005 | >>> numbers_set 2006 | {1, 2, 3} 2007 | >>> numbers_set.add(3) 2008 | >>> numbers_set 2009 | {1, 2, 3} 2010 | >>> numbers_set.add(4) 2011 | >>> numbers_set 2012 | {1, 2, 3, 4} 2013 | >>> numbers_set.add(0) 2014 | >>> numbers_set 2015 | {0, 1, 2, 3, 4} 2016 | >>> numbers_set.remove(0) 2017 | >>> numbers_set 2018 | {1, 2, 3, 4} 2019 | >>> numbers_set[0] 2020 | Traceback (most recent call last): 2021 | File "", line 1, in 2022 | TypeError: 'set' object does not support indexing 2023 | >>> 1 in numbers_set 2024 | True 2025 | >>> 5 in numbers_set 2026 | False 2027 | >>> min(numbers_set) 2028 | 1 2029 | >>> max(numbers_set) 2030 | 4 2031 | >>> sum(numbers_set) 2032 | 10 2033 | >>> len(numbers_set) 2034 | 4 2035 | >>> numbers_1_to_5_set = set(range(1,6)) 2036 | >>> numbers_1_to_5_set 2037 | {1, 2, 3, 4, 5} 2038 | >>> numbers_4_to_10_set = set(range(4,11)) 2039 | >>> numbers_4_to_10_set 2040 | {4, 5, 6, 7, 8, 9, 10} 2041 | >>> numbers_1_to_5_set + numbers_4_to_10_set 2042 | Traceback (most recent call last): 2043 | File "", line 1, in 2044 | TypeError: unsupported operand type(s) for +: 'set' and 'set' 2045 | >>> numbers_1_to_5_set | numbers_4_to_10_set 2046 | {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 2047 | >>> numbers_1_to_5_set & numbers_4_to_10_set 2048 | {4, 5} 2049 | >>> numbers_1_to_5_set - numbers_4_to_10_set 2050 | {1, 2, 3} 2051 | >>> numbers_4_to_10_set - numbers_1_to_5_set 2052 | {6, 7, 8, 9, 10} 2053 | >>> os.system('clear') 2054 | 2055 | 0 2056 | >>> occurances = dict(a=5 b=6 c=8) 2057 | File "", line 1 2058 | occurances = dict(a=5 b=6 c=8) 2059 | ^ 2060 | SyntaxError: invalid syntax 2061 | >>> occurances = dict(a=5,b=6,c=8) 2062 | >>> occurances 2063 | {'a': 5, 'b': 6, 'c': 8} 2064 | >>> type(occurances) 2065 | 2066 | >>> occurances['d'] = 15 2067 | >>> occurances 2068 | {'a': 5, 'b': 6, 'c': 8, 'd': 15} 2069 | >>> occurances['d'] = 10 2070 | >>> occurances 2071 | {'a': 5, 'b': 6, 'c': 8, 'd': 10} 2072 | >>> occurances['d'] 2073 | 10 2074 | >>> occurances['e'] 2075 | Traceback (most recent call last): 2076 | File "", line 1, in 2077 | KeyError: 'e' 2078 | >>> occurances.get('d') 2079 | 10 2080 | >>> occurances.get('e') 2081 | >>> occurances.get('e', 10) 2082 | 10 2083 | >>> occurances 2084 | {'a': 5, 'b': 6, 'c': 8, 'd': 10} 2085 | >>> occurances.keys() 2086 | dict_keys(['a', 'b', 'c', 'd']) 2087 | >>> occurances.values() 2088 | dict_values([5, 6, 8, 10]) 2089 | >>> occurances.items() 2090 | dict_items([('a', 5), ('b', 6), ('c', 8), ('d', 10)]) 2091 | >>> for (key,value) in occurances.items(): 2092 | ... print(f"{key} {value}") 2093 | ... 2094 | a 5 2095 | b 6 2096 | c 8 2097 | d 10 2098 | >>> occurances['a']=0 2099 | >>> occurances 2100 | {'a': 0, 'b': 6, 'c': 8, 'd': 10} 2101 | >>> del occurances['a'] 2102 | >>> occurances 2103 | {'b': 6, 'c': 8, 'd': 10} 2104 | >>> os.system('clear' 2105 | ... ) 2106 | 2107 | 2108 | 2109 | 2110 | 2111 | 2112 | 2113 | 2114 | 2115 | 0 2116 | >>> str = "This is an awesome occasion. This has never happened before." 2117 | >>> squares_first_ten_numbers = [ i*i for i in range(1,11) ] 2118 | >>> type(squares_first_ten_numbers) 2119 | 2120 | >>> squares_first_ten_numbers_set = set(squares_of_first_10_numbers) 2121 | >>> squares_first_ten_numbers_set = { i*i for i in range(1,11)} 2122 | >>> type(squares_first_ten_numbers_set) 2123 | 2124 | >>> squares_first_ten_numbers_dict = { i:i*i for i in range(1,11)} 2125 | >>> type(squares_first_ten_numbers_dict) 2126 | 2127 | >>> squares_first_ten_numbers_dict 2128 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} 2129 | >>> type([]) 2130 | 2131 | >>> type({}) 2132 | 2133 | >>> type(set()) 2134 | 2135 | >>> type({1}) 2136 | 2137 | >>> type({'A':5}) 2138 | 2139 | >>> type(()) 2140 | 2141 | >>> type((1,2,3)) 2142 | 2143 | >>> 2144 | 2145 | 2146 | >>> print(4.5 - 3.2) 2147 | 1.2999999999999998 2148 | >>> value1 = Decimal('4.5') 2149 | Traceback (most recent call last): 2150 | File "", line 1, in 2151 | NameError: name 'Decimal' is not defined 2152 | >>> import decimal 2153 | >>> from decimal import Decimal 2154 | >>> value1 = Decimal('4.5') 2155 | >>> value2 = Decimal('3.2') 2156 | >>> value1 - value2 2157 | Decimal('1.3') 2158 | >>> import math 2159 | >>> math. 2160 | math.acos( math.erf( math.inf math.pi 2161 | math.acosh( math.erfc( math.isclose( math.pow( 2162 | math.asin( math.exp( math.isfinite( math.radians( 2163 | math.asinh( math.expm1( math.isinf( math.sin( 2164 | math.atan( math.fabs( math.isnan( math.sinh( 2165 | math.atan2( math.factorial( math.ldexp( math.sqrt( 2166 | math.atanh( math.floor( math.lgamma( math.tan( 2167 | math.ceil( math.fmod( math.log( math.tanh( 2168 | math.copysign( math.frexp( math.log10( math.tau 2169 | math.cos( math.fsum( math.log1p( math.trunc( 2170 | math.cosh( math.gamma( math.log2( 2171 | math.degrees( math.gcd( math.modf( 2172 | math.e math.hypot( math.nan 2173 | >>> math.pi 2174 | 3.141592653589793 2175 | >>> math.e 2176 | 2.718281828459045 2177 | >>> help(math.factorial) 2178 | 2179 | >>> help(math.ceil) 2180 | 2181 | >>> math.ceil(5.5) 2182 | 6 2183 | >>> math.ceil(-5.5) 2184 | -5 2185 | >>> import os 2186 | >>> os.system('clear') 2187 | 2188 | 0 2189 | >>> import statistics 2190 | >>> statistics. 2191 | statistics.Decimal( statistics.mean( 2192 | statistics.Fraction( statistics.median( 2193 | statistics.StatisticsError( statistics.median_grouped( 2194 | statistics.bisect_left( statistics.median_high( 2195 | statistics.bisect_right( statistics.median_low( 2196 | statistics.chain( statistics.mode( 2197 | statistics.collections statistics.numbers 2198 | statistics.decimal statistics.pstdev( 2199 | statistics.groupby( statistics.pvariance( 2200 | statistics.harmonic_mean( statistics.stdev( 2201 | statistics.math statistics.variance( 2202 | >>> marks = [1, 6, 9, 23, 2] 2203 | >>> statistics.mean(marks) 2204 | 8.2 2205 | >>> statistics.median(marks) 2206 | 6 2207 | >>> marks = [1, 6, 9, 23, 2, 7] 2208 | >>> statistics.median(marks) 2209 | 6.5 2210 | >>> statistics.median_high(marks) 2211 | 7 2212 | >>> statistics.median_low(marks) 2213 | 6 2214 | >>> statistics.variance(marks) 2215 | 63.2 2216 | >>> os.system('clear') 2217 | 2218 | 0 2219 | >>> from collections import deque 2220 | >>> queue = deque(['Zero','One','Two']) 2221 | >>> queue.pop() 2222 | 'Two' 2223 | >>> queue.append('Three') 2224 | >>> queue 2225 | deque(['Zero', 'One', 'Three']) 2226 | >>> queue.append('Four') 2227 | >>> queue.append('Five') 2228 | >>> queue.appendLeft('Minus One') 2229 | Traceback (most recent call last): 2230 | File "", line 1, in 2231 | AttributeError: 'collections.deque' object has no attribute 'appendLeft' 2232 | >>> queue.append 2233 | queue.append( queue.appendleft( 2234 | >>> queue.appendleft('Minus One') 2235 | >>> queue 2236 | deque(['Minus One', 'Zero', 'One', 'Three', 'Four', 'Five']) 2237 | >>> queue.pop() 2238 | 'Five' 2239 | >>> queue.popleft() 2240 | 'Minus One' 2241 | >>> os.system('clear') 2242 | 2243 | 0 2244 | >>> import datetime 2245 | >>> datetime.datetime.today() 2246 | datetime.datetime(2018, 5, 21, 9, 59, 57, 450683) 2247 | >>> today_date = datetime.datetime.today() 2248 | >>> today_date 2249 | datetime.datetime(2018, 5, 21, 10, 0, 39, 732463) 2250 | >>> today_date.year 2251 | 2018 2252 | >>> today_date.month 2253 | 5 2254 | >>> today_date.day 2255 | 21 2256 | >>> today_date.hour 2257 | 10 2258 | >>> today_date.minute 2259 | 0 2260 | >>> today_date.second 2261 | 39 2262 | >>> some_date = datetime.datetime(2019, 5, 27) 2263 | >>> some_date 2264 | datetime.datetime(2019, 5, 27, 0, 0) 2265 | >>> some_date = datetime.datetime(2019, 5, 27, 9, 5,25) 2266 | >>> some_date 2267 | datetime.datetime(2019, 5, 27, 9, 5, 25) 2268 | >>> some_date = datetime.datetime(2019, 5, 27, 9, 5,25, 234567) 2269 | >>> some_date 2270 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 2271 | >>> some_date.date() 2272 | datetime.date(2019, 5, 27) 2273 | >>> some_date.time() 2274 | datetime.time(9, 5, 25, 234567) 2275 | >>> some_date 2276 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 2277 | >>> day = some_date 2278 | >>> day 2279 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 2280 | >>> day + time.timedelta(day=90) 2281 | Traceback (most recent call last): 2282 | File "", line 1, in 2283 | NameError: name 'time' is not defined 2284 | >>> day + datetime.timedelta(day=90) 2285 | Traceback (most recent call last): 2286 | File "", line 1, in 2287 | TypeError: 'day' is an invalid keyword argument for this function 2288 | >>> day + datetime.timedelta(days=90) 2289 | datetime.datetime(2019, 8, 25, 9, 5, 25, 234567) 2290 | >>> day 2291 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 2292 | >>> day + datetime.timedelta(days=90) 2293 | datetime.datetime(2019, 8, 25, 9, 5, 25, 234567) 2294 | >>> day + datetime.timedelta(weeks=3) 2295 | datetime.datetime(2019, 6, 17, 9, 5, 25, 234567) 2296 | >>> day + datetime.timedelta(hours=48) 2297 | datetime.datetime(2019, 5, 29, 9, 5, 25, 234567) 2298 | >>> os.system('clear') 2299 | 2300 | 0 2301 | >>> import math 2302 | >>> math. 2303 | math.acos( math.erf( math.inf math.pi 2304 | math.acosh( math.erfc( math.isclose( math.pow( 2305 | math.asin( math.exp( math.isfinite( math.radians( 2306 | math.asinh( math.expm1( math.isinf( math.sin( 2307 | math.atan( math.fabs( math.isnan( math.sinh( 2308 | math.atan2( math.factorial( math.ldexp( math.sqrt( 2309 | math.atanh( math.floor( math.lgamma( math.tan( 2310 | math.ceil( math.fmod( math.log( math.tanh( 2311 | math.copysign( math.frexp( math.log10( math.tau 2312 | math.cos( math.fsum( math.log1p( math.trunc( 2313 | math.cosh( math.gamma( math.log2( 2314 | math.degrees( math.gcd( math.modf( 2315 | math.e math.hypot( math.nan 2316 | >>> math.floor(4.5) 2317 | 4 2318 | >>> help(math.floor) 2319 | 2320 | >>> help(math) 2321 | 2322 | >>> 2323 | >>> from math import * 2324 | >>> floor(5) 2325 | 5 2326 | >>> gcd(34,56) 2327 | 2 2328 | >>> from math import gcd 2329 | >>> gcd(56,68) 2330 | 4 2331 | >>> os.system('clear') 2332 | 2333 | 2334 | 2335 | 2336 | 2337 | 0 2338 | >>> numbers = [1,4,6,3,4] 2339 | >>> for number in numbers: 2340 | ... print(number) 2341 | ... 2342 | 1 2343 | 4 2344 | 6 2345 | 3 2346 | 4 2347 | >>> for index,number in enumerate(numbers): 2348 | ... print(f'{index} - {number}') 2349 | ... 2350 | 0 - 1 2351 | 1 - 4 2352 | 2 - 6 2353 | 3 - 3 2354 | 4 - 4 2355 | >>> values = list('aeiou') 2356 | >>> values 2357 | ['a', 'e', 'i', 'o', 'u'] 2358 | >>> for index, vowel in enumerate(values): 2359 | ... printf(f'{index} - {vowel}') 2360 | ... 2361 | Traceback (most recent call last): 2362 | File "", line 2, in 2363 | NameError: name 'printf' is not defined 2364 | >>> for index, vowel in enumerate(values): 2365 | ... print(f'{index} - {vowel}') 2366 | ... 2367 | 0 - a 2368 | 1 - e 2369 | 2 - i 2370 | 3 - o 2371 | 4 - u 2372 | >>> import os 2373 | >>> os.system('clear') 2374 | 2375 | 0 2376 | >>> number = 5 2377 | >>> if(number%2==0): 2378 | ... isEven = True 2379 | ... else: 2380 | ... isEven = False 2381 | ... 2382 | >>> isEven = True if number%2==0 else False 2383 | >>> isEven 2384 | False 2385 | >>> number = 6 2386 | >>> isEven = True if number%2==0 else False 2387 | >>> isEven 2388 | True 2389 | >>> isEven = number%2==0 2390 | >>> isEven = "Yes" if number%2==0 else "No" 2391 | >>> isEven 2392 | 'Yes' 2393 | >>> os.system('clear') 2394 | 2395 | 2396 | 2397 | 0 2398 | >>> a = 1 2399 | >>> len(1) 2400 | Traceback (most recent call last): 2401 | File "", line 1, in 2402 | TypeError: object of type 'int' has no len() 2403 | >>> type(a) 2404 | 2405 | >>> str = "Value" 2406 | >>> str.upper() 2407 | 'VALUE' 2408 | >>> a.upper() 2409 | Traceback (most recent call last): 2410 | File "", line 1, in 2411 | AttributeError: 'int' object has no attribute 'upper' 2412 | >>> type(1) 2413 | 2414 | >>> type(1.5) 2415 | 2416 | >>> type("1.5") 2417 | 2418 | >>> type(True) 2419 | 2420 | >>> type(str) 2421 | 2422 | >>> str = 1 2423 | >>> type(str) 2424 | 2425 | >>> str = True 2426 | >>> type(str) 2427 | 2428 | >>> str = [1,2] 2429 | >>> type(str) 2430 | 2431 | >>> os.system('clear') 2432 | 2433 | 0 2434 | >>> def create_ranga(): 2435 | ... return 'Ranga',1981,'India' 2436 | ... 2437 | >>> ranga = create_ranga() 2438 | >>> type(ranga) 2439 | 2440 | >>> name, year, country = ranga 2441 | >>> ranga 2442 | ('Ranga', 1981, 'India') 2443 | >>> name 2444 | 'Ranga' 2445 | >>> year 2446 | 1981 2447 | >>> country 2448 | 'India' 2449 | >>> len(ranga) 2450 | 3 2451 | >>> ranga[0] 2452 | 'Ranga' 2453 | >>> ranga[1] 2454 | 1981 2455 | >>> ranga[2] 2456 | 'India' 2457 | >>> ranga[1] = 1991 2458 | Traceback (most recent call last): 2459 | File "", line 1, in 2460 | TypeError: 'tuple' object does not support item assignment 2461 | >>> person = ('Ranga', 5, 'India') 2462 | >>> person = 'Ranga', 5, 'India' 2463 | >>> type(person) 2464 | 2465 | >>> name, age, country = person 2466 | >>> name, age = person 2467 | Traceback (most recent call last): 2468 | File "", line 1, in 2469 | ValueError: too many values to unpack (expected 2) 2470 | >>> x = 0 2471 | >>> y = 1 2472 | >>> x, y = 0, 1 2473 | >>> x, y = y, x 2474 | >>> x 2475 | 1 2476 | >>> y 2477 | 0 2478 | >>> x = (0) 2479 | >>> type(x) 2480 | 2481 | >>> x = (0,) 2482 | >>> x = 1, 2483 | >>> type(x) 2484 | 2485 | >>> os.system('clear') 2486 | 2487 | 2488 | 2489 | 2490 | 2491 | 2492 | 2493 | 2494 | 2495 | 2496 | 0 2497 | >>> 2498 | 2499 | 2500 | 2501 | 2502 | 2503 | 2504 | 2505 | 2506 | 2507 | 2508 | 2509 | 2510 | >>> sum 2511 | 2512 | >>> sum([12,34,56]) 2513 | 102 2514 | >>> number1 = 10 2515 | >>> number2 = 20 2516 | >>> sum = number1 + number2 2517 | >>> sum 2518 | 30 2519 | >>> sum([12,34,56]) 2520 | Traceback (most recent call last): 2521 | File "", line 1, in 2522 | TypeError: 'int' object is not callable 2523 | >>> sum_ = number1 + number2 2524 | >>> del sum 2525 | >>> sum 2526 | 2527 | >>> sum([12,34,56]) 2528 | 102 2529 | >>> os.system('clear') 2530 | Traceback (most recent call last): 2531 | File "", line 1, in 2532 | NameError: name 'os' is not defined 2533 | >>> import os 2534 | >>> os.system('clear') 2535 | 2536 | 0 2537 | >>> None 2538 | >>> type(None) 2539 | 2540 | >>> def email(subject, content, to , cc , bcc): 2541 | ... print(f" {subject}, {content}, {to}, {cc}, " 2542 | ... ) 2543 | ... 2544 | >>> email("subject", "great work", in28minutes@gmail.com) 2545 | Traceback (most recent call last): 2546 | File "", line 1, in 2547 | NameError: name 'in28minutes' is not defined 2548 | >>> email("subject", "great work", "in28minutes@gmail.com") 2549 | Traceback (most recent call last): 2550 | File "", line 1, in 2551 | TypeError: email() missing 2 required positional arguments: 'cc' and 'bcc' 2552 | >>> def email(subject, content, to , cc=None , bcc=None): 2553 | ... print(f" {subject}, {content}, {to}, {cc}, {bcc}"); 2554 | ... 2555 | >>> email("subject", "great work", "in28minutes@gmail.com") 2556 | subject, great work, in28minutes@gmail.com, None, None 2557 | >>> email("subject", "great work", "in28minutes@gmail.com", None, None) 2558 | subject, great work, in28minutes@gmail.com, None, None 2559 | >>> email(None, "great work", "in28minutes@gmail.com", None, None) 2560 | None, great work, in28minutes@gmail.com, None, None 2561 | >>> var = "123" 2562 | >>> if var is None : print ("do something"); 2563 | ... 2564 | >>> var = None 2565 | >>> if var is None : print ("do something"); 2566 | ... 2567 | do something 2568 | >>> os.system('clear') 2569 | 2570 | 0 2571 | >>> class Student: pass 2572 | ... 2573 | >>> student1 = Student() 2574 | >>> student2 = Student() 2575 | >>> id(student1) 2576 | 4554811768 2577 | >>> id(student2) 2578 | 4554811992 2579 | >>> student1 is student2 2580 | False 2581 | >>> student3 = student1 2582 | >>> id(student3) 2583 | 4554811768 2584 | >>> student1 is student3 2585 | True 2586 | >>> student1 == student2 2587 | False 2588 | >>> student1 == student3 2589 | True 2590 | >>> class Student: 2591 | ... def __init__(self, id): 2592 | ... self.id = id 2593 | ... 2594 | >>> student1 = Student(1) 2595 | >>> student2 = Student(2) 2596 | >>> student3 = Student(1) 2597 | >>> student4 = student1 2598 | >>> id(student1) 2599 | 4554812160 2600 | >>> id(student4) 2601 | 4554812160 2602 | >>> student1 is student4 2603 | True 2604 | >>> student1 is student2 2605 | False 2606 | >>> student1 is student3 2607 | False 2608 | >>> student1 == student3 2609 | False 2610 | >>> class Student: 2611 | ... def __init__(self, id): 2612 | ... self.id = id 2613 | ... def __eq__(self, other): 2614 | ... return self.id == other.id 2615 | ... 2616 | >>> student1 = Student(1) 2617 | >>> student2 = Student(2) 2618 | >>> student3 = Student(1) 2619 | >>> student4 = student1 2620 | >>> student4 == student1 2621 | True 2622 | >>> student2 == student1 2623 | False 2624 | >>> student3 == student1 2625 | True 2626 | >>> os.system('clear') 2627 | 2628 | 0 2629 | >>> i=1 2630 | File "", line 1 2631 | i=1 2632 | ^ 2633 | IndentationError: unexpected indent 2634 | >>> i=3 2635 | File "", line 1 2636 | i=3 2637 | ^ 2638 | IndentationError: unexpected indent 2639 | >>> i=1 2640 | >>> if(i==3): 2641 | ... print('somethin') 2642 | File "", line 2 2643 | print('somethin') 2644 | ^ 2645 | IndentationError: expected an indented block 2646 | >>> if(i==3): 2647 | ... print('something') 2648 | ... print('') 2649 | File "", line 3 2650 | print('') 2651 | ^ 2652 | IndentationError: unindent does not match any outer indentation level 2653 | >>> os.system('clear') 2654 | 2655 | 0 2656 | >>> import this 2657 | The Zen of Python, by Tim Peters 2658 | 2659 | Beautiful is better than ugly. 2660 | Explicit is better than implicit. 2661 | Simple is better than complex. 2662 | Complex is better than complicated. 2663 | Flat is better than nested. 2664 | Sparse is better than dense. 2665 | Readability counts. 2666 | Special cases aren't special enough to break the rules. 2667 | Although practicality beats purity. 2668 | Errors should never pass silently. 2669 | Unless explicitly silenced. 2670 | In the face of ambiguity, refuse the temptation to guess. 2671 | There should be one-- and preferably only one --obvious way to do it. 2672 | Although that way may not be obvious at first unless you're Dutch. 2673 | Now is better than never. 2674 | Although never is often better than *right* now. 2675 | If the implementation is hard to explain, it's a bad idea. 2676 | If the implementation is easy to explain, it may be a good idea. 2677 | Namespaces are one honking great idea -- let's do more of those! 2678 | >>> 2679 | 2680 | >>> 1/0 2681 | Traceback (most recent call last): 2682 | File "", line 1, in 2683 | ZeroDivisionError: division by zero 2684 | >>> i = 0 2685 | >>> j = 10/i 2686 | Traceback (most recent call last): 2687 | File "", line 1, in 2688 | ZeroDivisionError: division by zero 2689 | >>> 2 + '2' 2690 | Traceback (most recent call last): 2691 | File "", line 1, in 2692 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 2693 | >>> values = [1,'2'] 2694 | >>> sum(values) 2695 | Traceback (most recent call last): 2696 | File "", line 1, in 2697 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 2698 | >>> value 2699 | Traceback (most recent call last): 2700 | File "", line 1, in 2701 | NameError: name 'value' is not defined 2702 | >>> values.non_existing 2703 | Traceback (most recent call last): 2704 | File "", line 1, in 2705 | AttributeError: 'list' object has no attribute 'non_existing' 2706 | >>> values.non_existing() 2707 | Traceback (most recent call last): 2708 | File "", line 1, in 2709 | AttributeError: 'list' object has no attribute 'non_existing' 2710 | >>> import builtins 2711 | >>> help(builtins) 2712 | 2713 | >>> help(builtins) 2714 | 2715 | >>> k = 10/non_existing_variable 2716 | Traceback (most recent call last): 2717 | File "", line 1, in 2718 | NameError: name 'non_existing_variable' is not defined 2719 | >>> 10/0 2720 | Traceback (most recent call last): 2721 | File "", line 1, in 2722 | ZeroDivisionError: division by zero 2723 | >>> values = [1,'1'] 2724 | File "", line 1 2725 | values = [1,'1'] 2726 | ^ 2727 | IndentationError: unexpected indent 2728 | >>> sum(values) 2729 | File "", line 1 2730 | sum(values) 2731 | ^ 2732 | IndentationError: unexpected indent 2733 | >>> values = [1,'1'] 2734 | >>> sum(values) 2735 | Traceback (most recent call last): 2736 | File "", line 1, in 2737 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 2738 | >>> import builtins 2739 | >>> help(builtins) 2740 | 2741 | >>> 2742 | ``` 2743 | --- 2744 | 2745 | ### /tips/all_about_methods.py 2746 | 2747 | ```py 2748 | def example_method(mandatory_parameter, default_parameter="Default" 2749 | , *args, **kwargs): 2750 | print(f""" 2751 | mandatory_parameter = {mandatory_parameter} {type(mandatory_parameter)} 2752 | default_parameter = {default_parameter} {type(default_parameter)} 2753 | args = {args} {type(args)} 2754 | kwargs = {kwargs} {type(kwargs)} 2755 | """) 2756 | 2757 | # example_method() #example_method() missing 1 required positional argument 2758 | # example_method(mandatory_parameter=15) #example_method(15) 2759 | # example_method(25,"Some String") 2760 | # example_method(25,"String 1","String 2","String 3") 2761 | # example_method(25,"String 1","String 2","String 3","String 4","String 5") 2762 | # example_method(25,"String 1","String 2","String 3",key1='a', key2='b') 2763 | #example_method(25,"String 1",key1='a', key2='b') 2764 | # example_method(key1='a', key2='b',mandatory_parameter=25,default_parameter="String 1") 2765 | # example_method(25,"String 1",key1='a', key2='b') 2766 | example_list = [1,2,3,4,5,6] 2767 | # example_method(*example_list) 2768 | example_dict = {'a':'1', 'b':'2'} 2769 | example_method(*example_list, **example_dict) 2770 | ``` 2771 | --- 2772 | 2773 | ### /tips/enum_examples.py 2774 | 2775 | ```py 2776 | # Currency - USD EUR INR 2777 | from enum import Enum 2778 | 2779 | 2780 | class Currency(Enum): 2781 | USD = 1 2782 | EUR = 2 2783 | INR = 3 2784 | 2785 | # for currency in Currency: 2786 | # print(currency) 2787 | 2788 | print(Currency(1)) 2789 | 2790 | print(Currency(1).name) 2791 | print(Currency(1).value) 2792 | 2793 | 2794 | # print(Currency.USD) 2795 | # print(Currency.INR) 2796 | ``` 2797 | --- 2798 | 2799 | ### /tips/module_1.py 2800 | 2801 | ```py 2802 | def method_1(): 2803 | print("method 1") 2804 | 2805 | class ClassA: 2806 | def class_method_1(self): 2807 | print("class_method_1 method 1") 2808 | 2809 | # print(__name__) 2810 | 2811 | if __name__ == '__main__': 2812 | method_1() 2813 | ClassA().class_method_1() 2814 | ``` 2815 | --- 2816 | 2817 | ### /tips/module_2.py 2818 | 2819 | ```py 2820 | import module_1 2821 | 2822 | module_1.method_1() 2823 | module_1.ClassA().class_method_1() 2824 | ``` 2825 | --- 2826 | 2827 | ### /tips/switch_alternatives.py 2828 | 2829 | ```py 2830 | week_days = { 2831 | 0 : 'Sunday', 2832 | 1 : 'Monday', 2833 | 2 : 'Tuesday' 2834 | # You can fill rest of the stuff 2835 | } 2836 | 2837 | print(week_days.get(7,'Invalid_day')) 2838 | ``` 2839 | --- 2840 | -------------------------------------------------------------------------------- /00-02-02-all-java-code.md: -------------------------------------------------------------------------------- 1 | 4 | 5 | ## Complete Code Example 6 | 7 | 8 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/Book.java 9 | 10 | ```java 11 | package com.in28minutes.java.to.python.examples.set1; 12 | 13 | public class Book { 14 | 15 | private int noOfCopies; 16 | private String name; 17 | 18 | public Book(String name, int noOfCopies) { 19 | this.name = name; 20 | this.noOfCopies = noOfCopies; 21 | } 22 | 23 | public void increaseNoOfCopies(int howMuch) { 24 | this.noOfCopies = this.noOfCopies + howMuch; 25 | } 26 | 27 | public void decreaseNoOfCopies(int howMuch) { 28 | this.noOfCopies = this.noOfCopies - howMuch; 29 | } 30 | 31 | public String toString() { 32 | return "Book["+name+","+noOfCopies+"]"; 33 | } 34 | } 35 | ``` 36 | --- 37 | 38 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/BookEnhanced.java 39 | 40 | ```java 41 | package com.in28minutes.java.to.python.examples.set1; 42 | 43 | public class BookEnhanced { 44 | 45 | private int copies; 46 | 47 | private String name; 48 | 49 | public BookEnhanced(String name, int copies) { 50 | this.name = name; 51 | this.copies = copies; 52 | } 53 | 54 | public int getCopies() { 55 | return copies; 56 | } 57 | 58 | public void setCopies(int copies) { 59 | if(copies>=0) 60 | this.copies = copies; 61 | } 62 | 63 | public String getName() { 64 | return name; 65 | } 66 | 67 | public void setName(String name) { 68 | this.name = name; 69 | } 70 | 71 | } 72 | ``` 73 | --- 74 | 75 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/DoWhileRepeatedQuestionRunner.java 76 | 77 | ```java 78 | package com.in28minutes.java.to.python.examples.set1; 79 | 80 | import java.util.Scanner; 81 | 82 | public class DoWhileRepeatedQuestionRunner { 83 | 84 | public static void main(String[] args) { 85 | 86 | Scanner scanner = new Scanner(System.in); 87 | int number; 88 | 89 | do { 90 | System.out.print("Enter a number: "); 91 | number = scanner.nextInt(); 92 | System.out.println("Cube is " + (number * number * number)); 93 | } while (number >= 0); 94 | 95 | System.out.print("Thank You! Have Fun!"); 96 | scanner.close(); 97 | } 98 | 99 | } 100 | ``` 101 | --- 102 | 103 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/ForLoopExercises.java 104 | 105 | ```java 106 | package com.in28minutes.java.to.python.examples.set1; 107 | 108 | public class ForLoopExercises { 109 | 110 | public static boolean isPrime(int number) { 111 | // 2 to number-1 112 | // How can check if a number is divisible by 2? 113 | 114 | if (number < 2) { 115 | return false; 116 | } 117 | 118 | for (int i = 2; i <= number - 1; i++) { 119 | if (number % i == 0) { 120 | return false; 121 | } 122 | } 123 | 124 | return true; 125 | } 126 | 127 | public static int sumUptoN(int number) { 128 | int sum = 0; 129 | 130 | for (int i = 1; i <= number; i++) { 131 | sum = sum + i; 132 | } 133 | 134 | return sum; 135 | } 136 | 137 | public static int sumOfDivisors(int number) { 138 | // 6 except 1 , 6 => 2,3 139 | // 2 + 3 140 | 141 | int sum = 0; 142 | 143 | for (int i = 2; i <= number - 1; i++) { 144 | if (number % i == 0) { 145 | sum = sum + i; 146 | } 147 | } 148 | 149 | return sum; 150 | } 151 | 152 | public static void printNumberTriangle(int number) { 153 | // 1 154 | // 1 2 155 | // 1 2 3 156 | // 1 2 3 4 157 | // 1 2 3 4 5 158 | 159 | for (int i = 1; i <= number; i++) { 160 | for (int j = 1; j <= i; j++) { 161 | System.out.print(j + " "); 162 | } 163 | System.out.println(); 164 | } 165 | 166 | } 167 | 168 | } 169 | ``` 170 | --- 171 | 172 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/HelloWorld.java 173 | 174 | ```java 175 | package com.in28minutes.java.to.python.examples.set1; 176 | 177 | public class HelloWorld { 178 | public static void main(String[] args) { 179 | System.out.println("Hello World"); 180 | char a = 'a'; 181 | } 182 | } 183 | ``` 184 | --- 185 | 186 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/MathBasic.java 187 | 188 | ```java 189 | package com.in28minutes.java.to.python.examples.set1; 190 | public class MathBasic { 191 | 192 | static void printSquaresOfNumbersUpto(int n) { 193 | for(int i=1; i<=n; i++) { 194 | System.out.println(i*i); 195 | } 196 | } 197 | 198 | public static void main(String[] args) { 199 | printSquaresOfNumbersUpto(10); 200 | //printSquaresOfEvenNumbersUpto(10); 201 | //printNumbersInReverse(10); 202 | } 203 | } 204 | ``` 205 | --- 206 | 207 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/MathBasic2.java 208 | 209 | ```java 210 | package com.in28minutes.java.to.python.examples.set1; 211 | 212 | public class MathBasic2 { 213 | 214 | static int sumOfTwoNumbers(int firstNumber, int secondNumber) { 215 | int sum = firstNumber + secondNumber; 216 | return sum; 217 | } 218 | 219 | public static void main(String[] args) { 220 | sumOfTwoNumbers(10,20); 221 | } 222 | } 223 | ``` 224 | --- 225 | 226 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/MenuConditionalRunner.java 227 | 228 | ```java 229 | package com.in28minutes.java.to.python.examples.set1; 230 | 231 | import java.util.Scanner; 232 | 233 | public class MenuConditionalRunner { 234 | public static void main(String[] args) { 235 | Scanner scanner = new Scanner(System.in); 236 | System.out.print("Enter Number1: "); 237 | int number1 = scanner.nextInt(); 238 | 239 | System.out.print("Enter Number2: "); 240 | int number2 = scanner.nextInt(); 241 | 242 | System.out.println("Choices Available are "); 243 | System.out.println("1 - Add"); 244 | System.out.println("2 - Subtract"); 245 | System.out.println("3 - Divide"); 246 | System.out.println("4 - Multiply"); 247 | 248 | System.out.print("Enter Choice: "); 249 | int choice = scanner.nextInt(); 250 | 251 | System.out.println("Your Choices are"); 252 | System.out.println("Number1 " + number1); 253 | System.out.println("Number2 " + number2); 254 | System.out.println("Choice " + choice); 255 | 256 | performOperationUsingNestedIfElse(number1, number2, choice); 257 | } 258 | 259 | private static void performOperationUsingNestedIfElse(int number1, int number2, int choice) { 260 | if (choice == 1) { 261 | System.out.println("Result " + (number1 + number2)); 262 | } else if (choice == 2) { 263 | System.out.println("Result " + (number1 - number2)); 264 | } else if (choice == 3) { 265 | System.out.println("Result " + (number1 / number2)); 266 | } else if (choice == 4) { 267 | System.out.println("Result " + (number1 * number2)); 268 | } else { 269 | System.out.println("Invalid Operation"); 270 | } 271 | } 272 | } 273 | ``` 274 | --- 275 | 276 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/MultiplicationTable.java 277 | 278 | ```java 279 | package com.in28minutes.java.to.python.examples.set1; 280 | public class MultiplicationTable { 281 | 282 | static void print() { 283 | print(5); 284 | } 285 | 286 | static void print(int table) { 287 | print(table, 1, 10); 288 | } 289 | 290 | static void print(int table, int from, int to) { 291 | for (int i = from; i <= to; i++) { 292 | System.out.printf("%d X %d = %d", table, i, table * i).println(); 293 | } 294 | } 295 | 296 | public static void main(String[] args) { 297 | print(); 298 | print(6); 299 | print(7,31,40); 300 | } 301 | } 302 | ``` 303 | --- 304 | 305 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/Person.java 306 | 307 | ```java 308 | package com.in28minutes.java.to.python.examples.set1; 309 | public class Person { 310 | private String name; 311 | private String email; 312 | private String phoneNumber; 313 | 314 | public Person(String name) { 315 | System.out.println("Person Constructor"); 316 | this.name = name; 317 | } 318 | 319 | public String getName() { 320 | return name; 321 | } 322 | 323 | public String getEmail() { 324 | return email; 325 | } 326 | 327 | public void setEmail(String email) { 328 | this.email = email; 329 | } 330 | 331 | public String getPhoneNumber() { 332 | return phoneNumber; 333 | } 334 | 335 | public void setPhoneNumber(String phoneNumber) { 336 | this.phoneNumber = phoneNumber; 337 | } 338 | 339 | public String toString() { 340 | return name + "#" + email + "#" + phoneNumber; 341 | } 342 | } 343 | ``` 344 | --- 345 | 346 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/Planet.java 347 | 348 | ```java 349 | package com.in28minutes.java.to.python.examples.set1; 350 | 351 | public class Planet { 352 | String name; 353 | 354 | public static void main(String[] args) { 355 | Planet earth = new Planet(); 356 | earth.name = "Earth"; 357 | 358 | } 359 | 360 | } 361 | ``` 362 | --- 363 | 364 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/Player.java 365 | 366 | ```java 367 | package com.in28minutes.java.to.python.examples.set1; 368 | public class Player { 369 | private String name; 370 | private static int count; 371 | 372 | public Player(String name) { 373 | System.out.println("Person Constructor"); 374 | this.name = name; 375 | count++; 376 | } 377 | 378 | public static int getCount() { 379 | return count; 380 | } 381 | 382 | public String getName() { 383 | return this.name; 384 | } 385 | 386 | } 387 | ``` 388 | --- 389 | 390 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/StringBasic.java 391 | 392 | ```java 393 | package com.in28minutes.java.to.python.examples.set1; 394 | public class StringBasic { 395 | static void printString(String str, int times) { 396 | for(int i=1; i<=times; i++) { 397 | System.out.println(str); 398 | } 399 | } 400 | 401 | public static void main(String[] args) { 402 | printString("I'm Having Fun", 10); 403 | } 404 | } 405 | ``` 406 | --- 407 | 408 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/Student.java 409 | 410 | ```java 411 | package com.in28minutes.java.to.python.examples.set1; 412 | public class Student extends Person { 413 | private String collegeName; 414 | private int year; 415 | 416 | public Student(String name, String collegeName) { 417 | super(name); 418 | this.collegeName = collegeName; 419 | } 420 | 421 | public String getCollegeName() { 422 | return collegeName; 423 | } 424 | 425 | public void setCollegeName(String collegeName) { 426 | this.collegeName = collegeName; 427 | } 428 | 429 | public int getYear() { 430 | return year; 431 | } 432 | 433 | public void setYear(int year) { 434 | this.year = year; 435 | } 436 | 437 | } 438 | ``` 439 | --- 440 | 441 | ### /src/main/java/com/in28minutes/java/to/python/examples/set1/SwitchExercisesRunner.java 442 | 443 | ```java 444 | package com.in28minutes.java.to.python.examples.set1; 445 | public class SwitchExercisesRunner { 446 | 447 | public static void main(String[] args) { 448 | System.out.println(determineNameOfDay(5)); 449 | } 450 | 451 | public static String determineNameOfDay(int dayNumber) { 452 | switch (dayNumber) { 453 | case 0: 454 | return "Sunday"; 455 | case 1: 456 | return "Monday"; 457 | case 2: 458 | return "Tuesday"; 459 | case 3: 460 | return "Wednesday"; 461 | case 4: 462 | return "Thursday"; 463 | case 5: 464 | return "Friday"; 465 | case 6: 466 | return "Saturday"; 467 | } 468 | 469 | return "Invalid_day"; 470 | } 471 | } 472 | ``` 473 | --- 474 | 475 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/AbstractRecipe.java 476 | 477 | ```java 478 | package com.in28minutes.java.to.python.examples.set2; 479 | 480 | public abstract class AbstractRecipe { 481 | 482 | public void execute() { 483 | getReady(); 484 | doTheDish(); 485 | cleanup(); 486 | } 487 | 488 | abstract void getReady(); 489 | abstract void doTheDish(); 490 | abstract void cleanup(); 491 | } 492 | 493 | ``` 494 | --- 495 | 496 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/ChessGame.java 497 | 498 | ```java 499 | package com.in28minutes.java.to.python.examples.set2; 500 | public class ChessGame implements GamingConsole{ 501 | 502 | @Override 503 | public void up() { 504 | System.out.println("Move piece up"); 505 | } 506 | 507 | @Override 508 | public void down() { 509 | System.out.println("Move piece down"); 510 | } 511 | 512 | @Override 513 | public void left() { 514 | System.out.println("Move piece left"); 515 | } 516 | 517 | @Override 518 | public void right() { 519 | System.out.println("Move piece right"); 520 | } 521 | 522 | } 523 | 524 | 525 | ``` 526 | --- 527 | 528 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/GameRunner.java 529 | 530 | ```java 531 | package com.in28minutes.java.to.python.examples.set2; 532 | public class GameRunner { 533 | 534 | public static void main(String[] args) { 535 | GamingConsole[] games = {new MarioGame(), new ChessGame()}; 536 | 537 | for(GamingConsole game:games) { 538 | game.up(); 539 | game.down(); 540 | game.left(); 541 | game.right(); 542 | } 543 | 544 | } 545 | 546 | } 547 | ``` 548 | --- 549 | 550 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/GamingConsole.java 551 | 552 | ```java 553 | package com.in28minutes.java.to.python.examples.set2; 554 | 555 | public interface GamingConsole { 556 | public void up(); 557 | public void down(); 558 | public void left(); 559 | public void right(); 560 | } 561 | 562 | ``` 563 | --- 564 | 565 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/MarioGame.java 566 | 567 | ```java 568 | package com.in28minutes.java.to.python.examples.set2; 569 | public class MarioGame implements GamingConsole{ 570 | 571 | @Override 572 | public void up() { 573 | System.out.println("Jump"); 574 | } 575 | 576 | @Override 577 | public void down() { 578 | System.out.println("Goes into a hole"); 579 | } 580 | 581 | @Override 582 | public void left() { 583 | } 584 | 585 | @Override 586 | public void right() { 587 | System.out.println("Go Forward"); 588 | } 589 | 590 | } 591 | 592 | ``` 593 | --- 594 | 595 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/Recipe1.java 596 | 597 | ```java 598 | package com.in28minutes.java.to.python.examples.set2; 599 | public class Recipe1 extends AbstractRecipe{ 600 | 601 | @Override 602 | void getReady() { 603 | System.out.println("Get the raw materials"); 604 | System.out.println("Get the utensils"); 605 | } 606 | 607 | @Override 608 | void doTheDish() { 609 | System.out.println("do the dish"); 610 | } 611 | 612 | @Override 613 | void cleanup() { 614 | System.out.println("Cleanup the utensils"); 615 | } 616 | 617 | } 618 | 619 | ``` 620 | --- 621 | 622 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/RecipeRunner.java 623 | 624 | ```java 625 | package com.in28minutes.java.to.python.examples.set2; 626 | public class RecipeRunner { 627 | 628 | public static void main(String[] args) { 629 | Recipe1 recipe = new Recipe1(); 630 | recipe.execute(); 631 | 632 | RecipeWithMicrowave recipeWithMicrowave = new RecipeWithMicrowave(); 633 | recipeWithMicrowave.execute(); 634 | 635 | } 636 | 637 | } 638 | ``` 639 | --- 640 | 641 | ### /src/main/java/com/in28minutes/java/to/python/examples/set2/RecipeWithMicrowave.java 642 | 643 | ```java 644 | package com.in28minutes.java.to.python.examples.set2; 645 | public class RecipeWithMicrowave extends AbstractRecipe{ 646 | 647 | @Override 648 | void getReady() { 649 | System.out.println("Get the raw materials"); 650 | System.out.println("Switch on the microwave"); 651 | } 652 | 653 | @Override 654 | void doTheDish() { 655 | System.out.println("get stuff ready"); 656 | System.out.println("Put it in the microwave"); 657 | } 658 | 659 | @Override 660 | void cleanup() { 661 | System.out.println("Cleanup the utensils"); 662 | System.out.println("Switch off the microwave"); 663 | } 664 | 665 | } 666 | 667 | ``` 668 | --- 669 | 670 | ### /src/main/java/com/in28minutes/java/to/python/examples/set3/ExceptionHandlingRunner.java 671 | 672 | ```java 673 | package com.in28minutes.java.to.python.examples.set3; 674 | 675 | public class ExceptionHandlingRunner { 676 | 677 | public static void main(String[] args) { 678 | try { 679 | // String str = null; 680 | // str.length(); 681 | int i = 0; 682 | int number = 10 / i; 683 | System.out.println("Method2 Ended"); 684 | } catch (NullPointerException ex) { 685 | System.out.println("Matched NullPointerException"); 686 | ex.printStackTrace(); 687 | } catch (ArithmeticException ex) { 688 | System.out.println("Matched ArithmeticException"); 689 | ex.printStackTrace(); 690 | } catch (Exception ex) { 691 | System.out.println("Matched Exception"); 692 | ex.printStackTrace(); 693 | } 694 | System.out.println("Method1 Ended"); 695 | System.out.println("Main Ended"); 696 | } 697 | } 698 | ``` 699 | --- 700 | 701 | ### /src/main/java/com/in28minutes/java/to/python/examples/set3/FunctionalProgrammingRunner.java 702 | 703 | ```java 704 | package com.in28minutes.java.to.python.examples.set3; 705 | 706 | import java.util.List; 707 | import java.util.function.BiFunction; 708 | import java.util.function.Function; 709 | import java.util.stream.Collectors; 710 | 711 | public class FunctionalProgrammingRunner { 712 | 713 | public static void main(String[] args) { 714 | 715 | Function 716 | multiplyByTwo = x -> x * 2; 717 | 718 | System.out.println(multiplyByTwo.apply(2)); 719 | 720 | BiFunction 721 | productOfTwoNumbers = (x, y) -> x * y; 722 | 723 | System.out.println( 724 | productOfTwoNumbers.apply(2, 7)); 725 | 726 | List numbers = List.of(1, 4, 7, 9); 727 | 728 | System.out.println(numbers.stream() 729 | .filter(x -> x % 2 == 1) 730 | .collect(Collectors.toList())); 731 | 732 | System.out.println(numbers.stream() 733 | .map(x -> x * 2) 734 | .collect(Collectors.toList())); 735 | 736 | System.out.println(numbers.stream() 737 | .reduce((x, y) -> x * y).get()); 738 | 739 | System.out.println(numbers.stream() 740 | .reduce((x, y) -> x + y).get()); 741 | 742 | System.out.println(numbers.stream() 743 | .reduce((x, y) -> Math.max(x, y)).get()); 744 | 745 | List words = List.of("Apple", "Ant", "Bat"); 746 | 747 | System.out.println(words.stream() 748 | .map(x -> x.toUpperCase()) 749 | .collect(Collectors.toList())); 750 | 751 | System.out.println(words.stream() 752 | .map(x -> x.length()) 753 | .collect(Collectors.toList())); 754 | 755 | } 756 | 757 | } 758 | ``` 759 | --- 760 | 761 | ### /src/main/java/com/in28minutes/java/to/python/examples/set3/ThrowingExceptionRunner.java 762 | 763 | ```java 764 | 765 | package com.in28minutes.java.to.python.examples.set3; 766 | 767 | class Amount { 768 | private String currency; 769 | private int amount; 770 | 771 | public Amount(String currency, int amount) { 772 | super(); 773 | this.currency = currency; 774 | this.amount = amount; 775 | } 776 | 777 | public void add(Amount that) throws CurrenciesDoNotMatchException { 778 | 779 | if (!this.currency.equals(that.currency)) { 780 | // throw new Exception("Currencies Don't Match " + this.currency + " & " 781 | // +that.currency ); 782 | throw new CurrenciesDoNotMatchException("Currencies Don't Match " + this.currency + " & " + that.currency); 783 | } 784 | 785 | this.amount = this.amount + that.amount; 786 | } 787 | 788 | public String toString() { 789 | return amount + " " + currency; 790 | } 791 | } 792 | 793 | class CurrenciesDoNotMatchException extends Exception { 794 | public CurrenciesDoNotMatchException(String msg) { 795 | super(msg); 796 | } 797 | } 798 | 799 | public class ThrowingExceptionRunner { 800 | 801 | public static void main(String[] args) throws CurrenciesDoNotMatchException { 802 | Amount amount1 = new Amount("USD", 10); 803 | Amount amount2 = new Amount("EUR", 20); 804 | amount1.add(amount2); 805 | System.out.println(amount1); 806 | } 807 | 808 | } 809 | ``` 810 | --- 811 | -------------------------------------------------------------------------------- /00-03-course-overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/in28minutes/java-to-python-in-100-steps/20ca1cb054d811deb69ec3a07c9c7d5b8783593a/00-03-course-overview.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java to Python in 100 Easy Steps 2 | 3 | ## Fastest way to Learn Python for Experienced Java Programmers 4 | 5 | ## Course Links 6 | 7 | [![Image](https://www.springboottutorial.com/images/Course-Python-Programming-For-Java-Programmers-in-100-Easy-Steps.png "Python For Beginners - Java to Python in 100 Steps")](https://www.udemy.com/course/learn-python-programming-for-java-programmers) 8 | 9 | ## Installing Tools 10 | - TODO 11 | 12 | ## Introduction To Course 13 | 14 | We love Programming. And we love programming in a variety of languages. 15 | 16 | Python is one of the most popular programming languages. Python offers both object oriented and structural programming features. Learning Python can be an awesome experience. 17 | 18 | If you have prior experience with Java, why do you need to start from zero. Why not use your Java knowledge and help you learn Python by comparing and contrasting with Python? 19 | 20 | We take an hands-on approach using a combination of Python Shell and PyCharm as an IDE to illustrate more than 100 Python Coding Exercises, Puzzles and Code Examples. We convert a number of Java Examples to Python. 21 | 22 | In about 100 Steps, we explore the most important Python Programming Language Features 23 | - Basics of Python Programming - Expressions, Variables and Printing Output 24 | - Python Conditionals and If Statement 25 | - Methods - Parameters, Arguments and Return Values 26 | - Object Oriented Programming - Class, Object, State and Behavior 27 | - Basics of OOPS - Encapsulation, Inheritance and Abstract Class. 28 | - Basics about Python Data Types 29 | - Basics about Python Built in Modules 30 | - Conditionals with Python - If Else Statement, Nested If Else 31 | - Loops - For Loop, While Loop in Python, Break and Continue 32 | - Immutablity of Python Basic Types 33 | - Python Data Structures - List, Set, Dictionary and Tuples 34 | - Basics of Designing a Class - Class, Object, State and Behavior. Deciding State and Constructors. 35 | - Introduction to Exception Handling - try, except, else and finally. Exception Hierarchy. Throwing an Exception. Creating and Throwing a Custom Exception. 36 | 37 | ## What You will learn 38 | - You will learn how to think as a Python Programmer 39 | - You will learn how to start your journey as a Python Programmer 40 | - You will learn to develop awesome object oriented programs with Python 41 | - You will solve a wide variety of hands-on exercises on the topics discussed below 42 | - You will learn about implementing Object Oriented Programming Concepts in Python- Inheritance, Abstract Class and Constructors 43 | - You will learn about a wide variety of Python Data Structures - List, Set, Dictionary and Tuples 44 | 45 | ## Requirements 46 | - Connectivity to Internet to download Python 3 and PyCharm. 47 | - We will help you install Python 3 and PyCharm. 48 | - We use Eclipe Oxygen to run Java 8 Examples. 49 | - We expect you to be an experienced Java Programmer 50 | 51 | 52 | ### Troubleshooting 53 | - Refer our TroubleShooting Guide - https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-TroubleshootingGuide-And-FAQ 54 | 55 | ## Youtube Playlists - 500+ Videos 56 | 57 | [Click here - 30+ Playlists with 500+ Videos on Spring, Spring Boot, REST, Microservices and the Cloud](https://www.youtube.com/user/rithustutorials/playlists?view=1&sort=lad&flow=list) 58 | 59 | ## Keep Learning in28Minutes 60 | 61 | in28Minutes is creating amazing solutions for you to learn Spring Boot, Full Stack and the Cloud - Docker, Kubernetes, AWS, React, Angular etc. - [Check out all our courses here](https://github.com/in28minutes/learn) 62 | -------------------------------------------------------------------------------- /java-code/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 4.0.0 5 | 6 | com.in28minutes.learn.python 7 | java-examples 8 | 1.0-SNAPSHOT 9 | 10 | jar 11 | 12 | java-examples 13 | http://www.in28minutes.com 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | org.apache.maven.plugins 22 | maven-compiler-plugin 23 | 3.2 24 | 25 | true 26 | 1.8 27 | 1.8 28 | true 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/Book.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | public class Book { 4 | 5 | private int noOfCopies; 6 | private String name; 7 | 8 | public Book(String name, int noOfCopies) { 9 | this.name = name; 10 | this.noOfCopies = noOfCopies; 11 | } 12 | 13 | public void increaseNoOfCopies(int howMuch) { 14 | this.noOfCopies = this.noOfCopies + howMuch; 15 | } 16 | 17 | public void decreaseNoOfCopies(int howMuch) { 18 | this.noOfCopies = this.noOfCopies - howMuch; 19 | } 20 | 21 | public String toString() { 22 | return "Book["+name+","+noOfCopies+"]"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/BookEnhanced.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | public class BookEnhanced { 4 | 5 | private int copies; 6 | 7 | private String name; 8 | 9 | public BookEnhanced(String name, int copies) { 10 | this.name = name; 11 | this.copies = copies; 12 | } 13 | 14 | public int getCopies() { 15 | return copies; 16 | } 17 | 18 | public void setCopies(int copies) { 19 | if(copies>=0) 20 | this.copies = copies; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public void setName(String name) { 28 | this.name = name; 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/DoWhileRepeatedQuestionRunner.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | import java.util.Scanner; 4 | 5 | public class DoWhileRepeatedQuestionRunner { 6 | 7 | public static void main(String[] args) { 8 | 9 | Scanner scanner = new Scanner(System.in); 10 | int number; 11 | 12 | do { 13 | System.out.print("Enter a number: "); 14 | number = scanner.nextInt(); 15 | System.out.println("Cube is " + (number * number * number)); 16 | } while (number >= 0); 17 | 18 | System.out.print("Thank You! Have Fun!"); 19 | scanner.close(); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/ForLoopExercises.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | public class ForLoopExercises { 4 | 5 | public static boolean isPrime(int number) { 6 | // 2 to number-1 7 | // How can check if a number is divisible by 2? 8 | 9 | if (number < 2) { 10 | return false; 11 | } 12 | 13 | for (int i = 2; i <= number - 1; i++) { 14 | if (number % i == 0) { 15 | return false; 16 | } 17 | } 18 | 19 | return true; 20 | } 21 | 22 | public static int sumUptoN(int number) { 23 | int sum = 0; 24 | 25 | for (int i = 1; i <= number; i++) { 26 | sum = sum + i; 27 | } 28 | 29 | return sum; 30 | } 31 | 32 | public static int sumOfDivisors(int number) { 33 | // 6 except 1 , 6 => 2,3 34 | // 2 + 3 35 | 36 | int sum = 0; 37 | 38 | for (int i = 2; i <= number - 1; i++) { 39 | if (number % i == 0) { 40 | sum = sum + i; 41 | } 42 | } 43 | 44 | return sum; 45 | } 46 | 47 | public static void printNumberTriangle(int number) { 48 | // 1 49 | // 1 2 50 | // 1 2 3 51 | // 1 2 3 4 52 | // 1 2 3 4 5 53 | 54 | for (int i = 1; i <= number; i++) { 55 | for (int j = 1; j <= i; j++) { 56 | System.out.print(j + " "); 57 | } 58 | System.out.println(); 59 | } 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | public class HelloWorld { 4 | public static void main(String[] args) { 5 | System.out.println("Hello World"); 6 | char a = 'a'; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/MathBasic.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | public class MathBasic { 3 | 4 | static void printSquaresOfNumbersUpto(int n) { 5 | for(int i=1; i<=n; i++) { 6 | System.out.println(i*i); 7 | } 8 | } 9 | 10 | public static void main(String[] args) { 11 | printSquaresOfNumbersUpto(10); 12 | //printSquaresOfEvenNumbersUpto(10); 13 | //printNumbersInReverse(10); 14 | } 15 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/MathBasic2.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | public class MathBasic2 { 4 | 5 | static int sumOfTwoNumbers(int firstNumber, int secondNumber) { 6 | int sum = firstNumber + secondNumber; 7 | return sum; 8 | } 9 | 10 | public static void main(String[] args) { 11 | sumOfTwoNumbers(10,20); 12 | } 13 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/MenuConditionalRunner.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | import java.util.Scanner; 4 | 5 | public class MenuConditionalRunner { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | System.out.print("Enter Number1: "); 9 | int number1 = scanner.nextInt(); 10 | 11 | System.out.print("Enter Number2: "); 12 | int number2 = scanner.nextInt(); 13 | 14 | System.out.println("Choices Available are "); 15 | System.out.println("1 - Add"); 16 | System.out.println("2 - Subtract"); 17 | System.out.println("3 - Divide"); 18 | System.out.println("4 - Multiply"); 19 | 20 | System.out.print("Enter Choice: "); 21 | int choice = scanner.nextInt(); 22 | 23 | System.out.println("Your Choices are"); 24 | System.out.println("Number1 " + number1); 25 | System.out.println("Number2 " + number2); 26 | System.out.println("Choice " + choice); 27 | 28 | performOperationUsingNestedIfElse(number1, number2, choice); 29 | } 30 | 31 | private static void performOperationUsingNestedIfElse(int number1, int number2, int choice) { 32 | if (choice == 1) { 33 | System.out.println("Result " + (number1 + number2)); 34 | } else if (choice == 2) { 35 | System.out.println("Result " + (number1 - number2)); 36 | } else if (choice == 3) { 37 | System.out.println("Result " + (number1 / number2)); 38 | } else if (choice == 4) { 39 | System.out.println("Result " + (number1 * number2)); 40 | } else { 41 | System.out.println("Invalid Operation"); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/MultiplicationTable.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | public class MultiplicationTable { 3 | 4 | static void print() { 5 | print(5); 6 | } 7 | 8 | static void print(int table) { 9 | print(table, 1, 10); 10 | } 11 | 12 | static void print(int table, int from, int to) { 13 | for (int i = from; i <= to; i++) { 14 | System.out.printf("%d X %d = %d", table, i, table * i).println(); 15 | } 16 | } 17 | 18 | public static void main(String[] args) { 19 | print(); 20 | print(6); 21 | print(7,31,40); 22 | } 23 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/Person.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | public class Person { 3 | private String name; 4 | private String email; 5 | private String phoneNumber; 6 | 7 | public Person(String name) { 8 | System.out.println("Person Constructor"); 9 | this.name = name; 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public String getEmail() { 17 | return email; 18 | } 19 | 20 | public void setEmail(String email) { 21 | this.email = email; 22 | } 23 | 24 | public String getPhoneNumber() { 25 | return phoneNumber; 26 | } 27 | 28 | public void setPhoneNumber(String phoneNumber) { 29 | this.phoneNumber = phoneNumber; 30 | } 31 | 32 | public String toString() { 33 | return name + "#" + email + "#" + phoneNumber; 34 | } 35 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/Planet.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | 3 | public class Planet { 4 | String name; 5 | 6 | public static void main(String[] args) { 7 | Planet earth = new Planet(); 8 | earth.name = "Earth"; 9 | 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/Player.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | public class Player { 3 | private String name; 4 | private static int count; 5 | 6 | public Player(String name) { 7 | System.out.println("Person Constructor"); 8 | this.name = name; 9 | count++; 10 | } 11 | 12 | public static int getCount() { 13 | return count; 14 | } 15 | 16 | public String getName() { 17 | return this.name; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/StringBasic.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | public class StringBasic { 3 | static void printString(String str, int times) { 4 | for(int i=1; i<=times; i++) { 5 | System.out.println(str); 6 | } 7 | } 8 | 9 | public static void main(String[] args) { 10 | printString("I'm Having Fun", 10); 11 | } 12 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/Student.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | public class Student extends Person { 3 | private String collegeName; 4 | private int year; 5 | 6 | public Student(String name, String collegeName) { 7 | super(name); 8 | this.collegeName = collegeName; 9 | } 10 | 11 | public String getCollegeName() { 12 | return collegeName; 13 | } 14 | 15 | public void setCollegeName(String collegeName) { 16 | this.collegeName = collegeName; 17 | } 18 | 19 | public int getYear() { 20 | return year; 21 | } 22 | 23 | public void setYear(int year) { 24 | this.year = year; 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set1/SwitchExercisesRunner.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set1; 2 | public class SwitchExercisesRunner { 3 | 4 | public static void main(String[] args) { 5 | System.out.println(determineNameOfDay(5)); 6 | } 7 | 8 | public static String determineNameOfDay(int dayNumber) { 9 | switch (dayNumber) { 10 | case 0: 11 | return "Sunday"; 12 | case 1: 13 | return "Monday"; 14 | case 2: 15 | return "Tuesday"; 16 | case 3: 17 | return "Wednesday"; 18 | case 4: 19 | return "Thursday"; 20 | case 5: 21 | return "Friday"; 22 | case 6: 23 | return "Saturday"; 24 | } 25 | 26 | return "Invalid_day"; 27 | } 28 | } -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/AbstractRecipe.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | 3 | public abstract class AbstractRecipe { 4 | 5 | public void execute() { 6 | getReady(); 7 | doTheDish(); 8 | cleanup(); 9 | } 10 | 11 | abstract void getReady(); 12 | abstract void doTheDish(); 13 | abstract void cleanup(); 14 | } 15 | 16 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/ChessGame.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | public class ChessGame implements GamingConsole{ 3 | 4 | @Override 5 | public void up() { 6 | System.out.println("Move piece up"); 7 | } 8 | 9 | @Override 10 | public void down() { 11 | System.out.println("Move piece down"); 12 | } 13 | 14 | @Override 15 | public void left() { 16 | System.out.println("Move piece left"); 17 | } 18 | 19 | @Override 20 | public void right() { 21 | System.out.println("Move piece right"); 22 | } 23 | 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/GameRunner.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | public class GameRunner { 3 | 4 | public static void main(String[] args) { 5 | GamingConsole[] games = {new MarioGame(), new ChessGame()}; 6 | 7 | for(GamingConsole game:games) { 8 | game.up(); 9 | game.down(); 10 | game.left(); 11 | game.right(); 12 | } 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/GamingConsole.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | 3 | public interface GamingConsole { 4 | public void up(); 5 | public void down(); 6 | public void left(); 7 | public void right(); 8 | } 9 | 10 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/MarioGame.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | public class MarioGame implements GamingConsole{ 3 | 4 | @Override 5 | public void up() { 6 | System.out.println("Jump"); 7 | } 8 | 9 | @Override 10 | public void down() { 11 | System.out.println("Goes into a hole"); 12 | } 13 | 14 | @Override 15 | public void left() { 16 | } 17 | 18 | @Override 19 | public void right() { 20 | System.out.println("Go Forward"); 21 | } 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/Recipe1.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | public class Recipe1 extends AbstractRecipe{ 3 | 4 | @Override 5 | void getReady() { 6 | System.out.println("Get the raw materials"); 7 | System.out.println("Get the utensils"); 8 | } 9 | 10 | @Override 11 | void doTheDish() { 12 | System.out.println("do the dish"); 13 | } 14 | 15 | @Override 16 | void cleanup() { 17 | System.out.println("Cleanup the utensils"); 18 | } 19 | 20 | } 21 | 22 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/RecipeRunner.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | public class RecipeRunner { 3 | 4 | public static void main(String[] args) { 5 | Recipe1 recipe = new Recipe1(); 6 | recipe.execute(); 7 | 8 | RecipeWithMicrowave recipeWithMicrowave = new RecipeWithMicrowave(); 9 | recipeWithMicrowave.execute(); 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set2/RecipeWithMicrowave.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set2; 2 | public class RecipeWithMicrowave extends AbstractRecipe{ 3 | 4 | @Override 5 | void getReady() { 6 | System.out.println("Get the raw materials"); 7 | System.out.println("Switch on the microwave"); 8 | } 9 | 10 | @Override 11 | void doTheDish() { 12 | System.out.println("get stuff ready"); 13 | System.out.println("Put it in the microwave"); 14 | } 15 | 16 | @Override 17 | void cleanup() { 18 | System.out.println("Cleanup the utensils"); 19 | System.out.println("Switch off the microwave"); 20 | } 21 | 22 | } 23 | 24 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set3/ExceptionHandlingRunner.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set3; 2 | 3 | public class ExceptionHandlingRunner { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | // String str = null; 8 | // str.length(); 9 | int i = 0; 10 | int number = 10 / i; 11 | System.out.println("Method2 Ended"); 12 | } catch (NullPointerException ex) { 13 | System.out.println("Matched NullPointerException"); 14 | ex.printStackTrace(); 15 | } catch (ArithmeticException ex) { 16 | System.out.println("Matched ArithmeticException"); 17 | ex.printStackTrace(); 18 | } catch (Exception ex) { 19 | System.out.println("Matched Exception"); 20 | ex.printStackTrace(); 21 | } 22 | System.out.println("Method1 Ended"); 23 | System.out.println("Main Ended"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set3/FunctionalProgrammingRunner.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.to.python.examples.set3; 2 | 3 | import java.util.List; 4 | import java.util.function.BiFunction; 5 | import java.util.function.Function; 6 | import java.util.stream.Collectors; 7 | 8 | public class FunctionalProgrammingRunner { 9 | 10 | public static void main(String[] args) { 11 | 12 | Function 13 | multiplyByTwo = x -> x * 2; 14 | 15 | System.out.println(multiplyByTwo.apply(2)); 16 | 17 | BiFunction 18 | productOfTwoNumbers = (x, y) -> x * y; 19 | 20 | System.out.println( 21 | productOfTwoNumbers.apply(2, 7)); 22 | 23 | List numbers = List.of(1, 4, 7, 9); 24 | 25 | System.out.println(numbers.stream() 26 | .filter(x -> x % 2 == 1) 27 | .collect(Collectors.toList())); 28 | 29 | System.out.println(numbers.stream() 30 | .map(x -> x * 2) 31 | .collect(Collectors.toList())); 32 | 33 | System.out.println(numbers.stream() 34 | .reduce((x, y) -> x * y).get()); 35 | 36 | System.out.println(numbers.stream() 37 | .reduce((x, y) -> x + y).get()); 38 | 39 | System.out.println(numbers.stream() 40 | .reduce((x, y) -> Math.max(x, y)).get()); 41 | 42 | List words = List.of("Apple", "Ant", "Bat"); 43 | 44 | System.out.println(words.stream() 45 | .map(x -> x.toUpperCase()) 46 | .collect(Collectors.toList())); 47 | 48 | System.out.println(words.stream() 49 | .map(x -> x.length()) 50 | .collect(Collectors.toList())); 51 | 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /java-code/src/main/java/com/in28minutes/java/to/python/examples/set3/ThrowingExceptionRunner.java: -------------------------------------------------------------------------------- 1 | 2 | package com.in28minutes.java.to.python.examples.set3; 3 | 4 | class Amount { 5 | private String currency; 6 | private int amount; 7 | 8 | public Amount(String currency, int amount) { 9 | super(); 10 | this.currency = currency; 11 | this.amount = amount; 12 | } 13 | 14 | public void add(Amount that) throws CurrenciesDoNotMatchException { 15 | 16 | if (!this.currency.equals(that.currency)) { 17 | // throw new Exception("Currencies Don't Match " + this.currency + " & " 18 | // +that.currency ); 19 | throw new CurrenciesDoNotMatchException("Currencies Don't Match " + this.currency + " & " + that.currency); 20 | } 21 | 22 | this.amount = this.amount + that.amount; 23 | } 24 | 25 | public String toString() { 26 | return amount + " " + currency; 27 | } 28 | } 29 | 30 | class CurrenciesDoNotMatchException extends Exception { 31 | public CurrenciesDoNotMatchException(String msg) { 32 | super(msg); 33 | } 34 | } 35 | 36 | public class ThrowingExceptionRunner { 37 | 38 | public static void main(String[] args) throws CurrenciesDoNotMatchException { 39 | Amount amount1 = new Amount("USD", 10); 40 | Amount amount2 = new Amount("EUR", 20); 41 | amount1.add(amount2); 42 | System.out.println(amount1); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /python-code/oops/abstract_class_example.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | class AbstractRecipe(ABC): 4 | 5 | def execute(self): 6 | self.get_ready() 7 | self.do_the_dish() 8 | self.cleanup() 9 | 10 | @abstractmethod 11 | def get_ready(self): 12 | pass 13 | 14 | @abstractmethod 15 | def do_the_dish(self): 16 | pass 17 | 18 | @abstractmethod 19 | def cleanup(self): 20 | pass 21 | 22 | 23 | class Recipe1(AbstractRecipe): 24 | 25 | def get_ready(self): 26 | print('Get raw materials') 27 | print('Get utensils') 28 | 29 | def do_the_dish(self): 30 | print('do the dish') 31 | 32 | def cleanup(self): 33 | print('clean utensils') 34 | 35 | 36 | # TypeError: Can't instantiate abstract class AbstractRecipe 37 | # with abstract methods cleanup, do_the_dish, get_ready 38 | # recipe = AbstractRecipe() 39 | 40 | recipe = Recipe1() 41 | 42 | recipe.execute() -------------------------------------------------------------------------------- /python-code/oops/abstract_class_to_implement_interface_example.py: -------------------------------------------------------------------------------- 1 | from abc import ABC,abstractmethod 2 | 3 | 4 | # class GamingConsole(ABC): 5 | # @abstractmethod 6 | # def up(self): pass 7 | # 8 | # @abstractmethod 9 | # def down(self): pass 10 | # 11 | # @abstractmethod 12 | # def left(self): pass 13 | # 14 | # @abstractmethod 15 | # def right(self): pass 16 | 17 | 18 | class MarioGame: 19 | def up(self): print('jump') 20 | 21 | def down(self): print('goes into a hole') 22 | 23 | def left(self): pass 24 | 25 | def right(self): print('Go Forward') 26 | 27 | 28 | class ChessGame: 29 | def up(self): print('Move piece up') 30 | 31 | def down(self): print('Move piece down') 32 | 33 | def left(self): print('Move piece left') 34 | 35 | def right(self): print('Move piece right') 36 | 37 | 38 | # games = [ChessGame(), MarioGame()] 39 | # 40 | # for game in games: 41 | # game.up() 42 | # game.down() 43 | # game.left() 44 | # game.right() 45 | 46 | class Test1: 47 | def method(self): print("Test1") 48 | 49 | class Test2: 50 | def method(self): print("Test2") 51 | 52 | tests = [Test1(),Test2()] 53 | 54 | for test in tests: 55 | test.method() 56 | 57 | -------------------------------------------------------------------------------- /python-code/oops/book_example.py: -------------------------------------------------------------------------------- 1 | # MotorBike 2 | # gear, speed 3 | 4 | class Book: 5 | 6 | def __init__(self, name, copies): 7 | self.name = name 8 | self.copies = copies 9 | 10 | def __repr__(self): 11 | return repr((self.name, self.copies)) 12 | 13 | def increase_copies(self, how_much): 14 | self.copies += how_much 15 | 16 | def decrease_copies(self, how_much): 17 | self.copies -= how_much 18 | 19 | #set 20 | #get 21 | 22 | book1 = Book('Mastering Spring 5.0', 200) 23 | book1.increase_copies(50) 24 | 25 | book2 = Book('Mastering Python 3', 15) 26 | book2.decrease_copies(5) 27 | 28 | print(book1) 29 | print(book2) 30 | -------------------------------------------------------------------------------- /python-code/oops/encapsulation_examples.py: -------------------------------------------------------------------------------- 1 | class BookEnhanced: 2 | def __init__(self, name, copies): 3 | self.name = name 4 | self._copies = copies 5 | 6 | @property 7 | def copies(self): 8 | print('getter called') 9 | return self._copies 10 | 11 | @copies.setter 12 | def copies(self, copies): 13 | print('setter called') 14 | if(copies>=0): 15 | self._copies = copies 16 | 17 | microservices = BookEnhanced('Microservices',5) 18 | 19 | print(microservices.copies) 20 | 21 | microservices.copies = 10 22 | 23 | print(microservices.copies) -------------------------------------------------------------------------------- /python-code/oops/exception_handling_examples.py: -------------------------------------------------------------------------------- 1 | # try: 2 | # i = 0 3 | # number = 10/i 4 | # except ZeroDivisionError as error: 5 | # print(error) 6 | # number = 0 7 | # else: # else is execute when exception is not thrown 8 | # print('else') 9 | # finally: 10 | # print('finally') 11 | # 12 | # print(number) 13 | # 14 | 15 | class Amount: 16 | def __init__(self, currency, amount): 17 | self.currency = currency 18 | self.amount = amount 19 | 20 | def add(self, that): 21 | if(self.currency==that.currency): 22 | self.amount += that.amount 23 | else: 24 | raise CurrencyDoNotMatchException(self.currency + " " + that.currency) 25 | 26 | def __repr__(self): 27 | return repr((self.currency,self.amount)) 28 | 29 | class CurrencyDoNotMatchException(Exception): 30 | def __init__(self, message): 31 | super().__init__(message) 32 | 33 | 34 | amount1 = Amount('EUR',35) 35 | amount2 = Amount('INR',70) 36 | 37 | amount2.add(amount1) 38 | print(amount2) -------------------------------------------------------------------------------- /python-code/oops/inheritance_examples.py: -------------------------------------------------------------------------------- 1 | # Student(college,year,degree) 2 | # IS A Person(name, address) 3 | 4 | 5 | class Person: 6 | def __init__(self, name): 7 | self.name = name 8 | 9 | def __repr__(self): 10 | return repr((self.name)) 11 | 12 | 13 | class Student(Person): 14 | 15 | def __init__(self, name, college_name): 16 | super().__init__(name) 17 | self.college_name = college_name 18 | 19 | def __repr__(self): 20 | return repr((super().__repr__(),self.college_name)) 21 | 22 | 23 | person = Person('Ranga') 24 | 25 | student = Student('Ranga', 'Pondicherry Engg College') 26 | 27 | print(person) 28 | 29 | print(student) 30 | 31 | class Planet: 32 | pass 33 | 34 | earth = Planet() 35 | earth.__repr__() 36 | -------------------------------------------------------------------------------- /python-code/oops/motor_bike_example.py: -------------------------------------------------------------------------------- 1 | class MotorBike: 2 | 3 | def __init__(self, gear, speed): 4 | self.gear = gear 5 | self.speed = speed 6 | 7 | def __repr__(self): 8 | return repr((self.gear, self.speed)) 9 | 10 | 11 | # instance 1 or object 1 12 | honda = MotorBike(3, 50) 13 | 14 | # instance 2 or object 2 15 | ducati = MotorBike(1, 10) 16 | 17 | print(honda) 18 | print(ducati) -------------------------------------------------------------------------------- /python-code/oops/multiple_inheritance_examples.py: -------------------------------------------------------------------------------- 1 | class LandAnimal: 2 | def walk(self): 3 | print('walk') 4 | 5 | class WaterAnimal: 6 | def swim(self): 7 | print('swim') 8 | 9 | class Amphibian(LandAnimal, WaterAnimal): 10 | pass 11 | 12 | frog = Amphibian() 13 | 14 | frog.swim() 15 | frog.walk() 16 | 17 | -------------------------------------------------------------------------------- /python-code/oops/oops_in_depth.py: -------------------------------------------------------------------------------- 1 | class Planet: 2 | def __init__(self, name, distance_from_sun): 3 | self.name = name 4 | self.distance_from_sun = distance_from_sun 5 | 6 | earth = Planet('Earth', 200) 7 | mars = Planet('Mars', 500) 8 | 9 | earth.speed = 10000 10 | print(earth.speed) 11 | 12 | # mars.name = 'Mars' 13 | print(mars.name) -------------------------------------------------------------------------------- /python-code/oops/oops_puzzles.py: -------------------------------------------------------------------------------- 1 | class Country: 2 | # def __init__(self): 3 | # print('constuctor 1') 4 | 5 | def __init__(self, name="Default"): 6 | self.name = name 7 | print('constuctor 2') 8 | 9 | def instance_method(self): 10 | print('instance method') 11 | 12 | 13 | default_country = Country() 14 | india = Country('India') 15 | 16 | print(default_country.name) 17 | print(india.name) 18 | #TypeError: __init__() missing 1 required positional argument: 'name' 19 | -------------------------------------------------------------------------------- /python-code/oops/operator_overloading_examples.py: -------------------------------------------------------------------------------- 1 | from functools import total_ordering 2 | 3 | @total_ordering 4 | class Money: 5 | def __init__(self, currency, amount): 6 | self.currency = currency 7 | self.amount = amount 8 | 9 | def __add__(self, other): 10 | return Money(self.currency, self.amount + other.amount) 11 | 12 | def __sub__(self, other): 13 | return Money(self.currency, self.amount - other.amount) 14 | 15 | def __repr__(self): 16 | return repr((self.currency, self.amount)) 17 | 18 | def __eq__(self, other): 19 | return (self.currency, self.amount) == (other.currency,other.amount) 20 | 21 | def __le__(self, other): 22 | return (self.amount) <= (other.amount) 23 | 24 | amount1 = Money('EUR', 10) 25 | amount2 = Money('EUR', 20) 26 | amount3 = Money('EUR', 10) 27 | 28 | print(amount1 < amount2) 29 | print(amount2 < amount3) 30 | print(amount3 < amount1) 31 | 32 | print(amount3 <= amount1) 33 | print(amount3 >= amount1) 34 | 35 | # print(amount1 == amount2) 36 | # print(amount1 != amount2) 37 | # print(amount1 == amount3) 38 | # print(amount1 != amount3) 39 | 40 | # print(amount1 + amount2) 41 | # print(amount2 - amount1) 42 | 43 | 44 | 45 | # object.__add__(self, other) 46 | # object.__sub__(self, other) 47 | # object.__mul__(self, other) * 48 | # object.__matmul__(self, other) 49 | # object.__truediv__(self, other) \ 50 | # object.__floordiv__(self, other) \\ 51 | # object.__mod__(self, other) % 52 | # object.__pow__(self, other[, modulo]) ** 53 | # object.__and__(self, other) and 54 | # object.__xor__(self, other) ^ 55 | # object.__or__(self, other) or 56 | # 57 | # i methods 58 | -------------------------------------------------------------------------------- /python-code/oops/static_examples.py: -------------------------------------------------------------------------------- 1 | class Player: 2 | count = 0 3 | 4 | def __init__(self, name): 5 | self.name = name 6 | Player.count += 1 7 | 8 | @staticmethod 9 | def get_count(): 10 | return Player.count 11 | 12 | messi = Player('Messi') 13 | ronaldo = Player('Ronaldo') 14 | 15 | print(messi.get_count()) 16 | print(ronaldo.get_count()) 17 | print(Player.get_count()) 18 | 19 | # print(Player.count) 20 | # 21 | # print(messi.count) 22 | # print(ronaldo.count) 23 | # 24 | # Player.count = 100 25 | # 26 | # print(Player.count) 27 | # 28 | # print(messi.count) 29 | # print(ronaldo.count) 30 | 31 | # messi.count = 100 32 | # 33 | # print(Player.count)//2 34 | # 35 | # print(messi.count)//100 36 | # print(ronaldo.count)//2 37 | -------------------------------------------------------------------------------- /python-code/python-hello-world/first_method.py: -------------------------------------------------------------------------------- 1 | # print("Hello World") 2 | 3 | 4 | def print_hello_world_twice(): 5 | print("Hello World 1") 6 | print("Hello World 2") 7 | 8 | 9 | def print_hello_world_multiple_times(times): 10 | for i in range(1, times+1): 11 | print("Hello World") 12 | 13 | 14 | # print("Hello World 3") 15 | 16 | # print_hello_world_twice() 17 | 18 | print_hello_world_multiple_times(4) -------------------------------------------------------------------------------- /python-code/python-hello-world/for_loop_examples.py: -------------------------------------------------------------------------------- 1 | for i in range(1,10): 2 | print(i) 3 | print("Done") 4 | 5 | for i in range(1,10): 6 | print(i*i) 7 | 8 | print("Test") 9 | -------------------------------------------------------------------------------- /python-code/python-hello-world/for_loop_exercises.py: -------------------------------------------------------------------------------- 1 | 2 | def is_prime(number): 3 | 4 | if number < 2: 5 | return False 6 | 7 | for divisor in range(2,number): 8 | if number % divisor == 0: 9 | return False 10 | 11 | return True 12 | 13 | # print(is_prime(15)); 14 | 15 | 16 | def sum_upto_n(number): 17 | 18 | sum = 0 19 | 20 | for i in range(1, number+1): 21 | sum = sum + i 22 | 23 | return sum 24 | 25 | 26 | # print(sum_upto_n(6)) 27 | # print(sum_upto_n(10)) 28 | 29 | 30 | def calculate_sum_of_divisors(number): 31 | sum_of_divisors = 0 32 | 33 | for divisor in range(1,number+1): 34 | if number % divisor == 0: 35 | sum_of_divisors = sum_of_divisors + divisor 36 | 37 | return sum_of_divisors 38 | 39 | # print(calculate_sum_of_divisors(6)) 40 | # print(calculate_sum_of_divisors(15)) 41 | 42 | 43 | def print_a_number_triangle(number): 44 | for j in range(1, number + 1): 45 | for i in range(1, j + 1): 46 | print(i, end=' ') 47 | print() 48 | 49 | 50 | print_a_number_triangle(6) -------------------------------------------------------------------------------- /python-code/python-hello-world/hello_world.py: -------------------------------------------------------------------------------- 1 | print('Hello World') 2 | print("Hello World2") 3 | print("Hello World3") -------------------------------------------------------------------------------- /python-code/python-hello-world/if_examples.py: -------------------------------------------------------------------------------- 1 | x_string = input("Enter a Number") 2 | x = int(x_string) 3 | 4 | if x == 1: 5 | print(f"{x} is 1") 6 | print("this is part of if") 7 | elif x == 2: 8 | print(f"{x} is 2") 9 | print("this is part of elif") 10 | else: 11 | print(f"{x} is NOT 1 or 2") 12 | print("this is part of else") -------------------------------------------------------------------------------- /python-code/python-hello-world/math_basic.py: -------------------------------------------------------------------------------- 1 | def print_squares_of_numbers_upto(n): 2 | for i in range(1,n+1): 3 | print(i*i) 4 | 5 | 6 | def print_squares_of_even_numbers_upto(n): 7 | for i in range(2,n+1,2): 8 | print(i*i) 9 | 10 | 11 | def sum_of_two_numbers(number1,number2): 12 | sum = number1 + number2 13 | return sum 14 | 15 | 16 | def print_numbers_in_reverse(n): 17 | for i in range(n,0,-1): 18 | print(i) 19 | 20 | 21 | print(sum_of_two_numbers(5,6)) 22 | # print_squares_of_even_numbers_upto(10) 23 | # print_numbers_in_reverse(10) -------------------------------------------------------------------------------- /python-code/python-hello-world/menu_with_if.py: -------------------------------------------------------------------------------- 1 | number1 = int(input("Enter Number1:")) 2 | number2 = int(input("Enter Number2:")) 3 | 4 | print("Choices Available are ") 5 | print("1 - Add") 6 | print("2 - Subtract") 7 | print("3 - Divide") 8 | print("4 - Multiply") 9 | 10 | choice = int(input("Enter Choice: ")) 11 | 12 | print("Your Choices are") 13 | 14 | if choice == 1: 15 | print(f"Result = {number1 + number2}") 16 | elif choice == 2: 17 | print(f"Result = {number1 - number2}") 18 | elif choice == 3: 19 | print(f"Result = {number1 / number2}") 20 | elif choice == 4: 21 | print(f"Result = {number1 * number2}") 22 | else: 23 | print("Invalid Operation") -------------------------------------------------------------------------------- /python-code/python-hello-world/multiplication_table.py: -------------------------------------------------------------------------------- 1 | def print_multiplication_table(table=5, start=1, end=10): 2 | for i in range(start, end+1): 3 | print(f"{table} X {i} = {table*i}") 4 | 5 | 6 | print_multiplication_table() 7 | 8 | # print_multiplication_table(6) 9 | 10 | # print_multiplication_table(7, 31, 40) -------------------------------------------------------------------------------- /python-code/python-hello-world/oops_trials.py: -------------------------------------------------------------------------------- 1 | class Book: 2 | 3 | count = 0 4 | 5 | def __init__(self, name): 6 | self._name = name 7 | Book.count = Book.count + 1 8 | 9 | @property 10 | def name(self): 11 | print("Getter For Name Called") 12 | return self._name 13 | 14 | @name.setter 15 | def name(self, name): 16 | print("Setter For Name Called") 17 | self._name = name 18 | 19 | @staticmethod 20 | def static_method(): 21 | print("I'm static") 22 | 23 | def __setattr__(self, key, value): 24 | print(f'{key} - {value}') 25 | self.__dict__[key] = value 26 | 27 | 28 | # book1 = Book('Microservices') 29 | # print(book1.name) 30 | # book1.name = 'ABC' 31 | # print(book1.name) 32 | # book2 = Book('Web Services') 33 | 34 | # print(Book.count) 35 | # print(book1.count) 36 | # print(book2.count) 37 | # Book.static_method() 38 | # book1.static_method() 39 | 40 | # print(book1.name) 41 | 42 | def do_this_and_print(func,data): 43 | print(func(data)) 44 | 45 | 46 | def double(data): 47 | return data * 2 48 | 49 | def triple(data): 50 | return data * 3 51 | 52 | 53 | do_this_and_print(double,5) 54 | 55 | do_this_and_print(triple,5) 56 | 57 | do_this_and_print(lambda x : x*2, 5) 58 | 59 | do_this_and_print(lambda x : x*5, 5) -------------------------------------------------------------------------------- /python-code/python-hello-world/repeated_question.py: -------------------------------------------------------------------------------- 1 | number = int(input('Enter a number:')) 2 | 3 | while number >= 0: 4 | print(f'cube is {number ** 3}') 5 | number = int(input('Enter a number:')) 6 | -------------------------------------------------------------------------------- /python-code/python-hello-world/while_loop_examples.py: -------------------------------------------------------------------------------- 1 | i = 0 2 | 3 | while i<11: 4 | print(i) 5 | i += 1 6 | 7 | 8 | # print all the squares of numbers < 100 9 | # 1 4 9 .. 81 10 | def print_squares_of_numbers_below(limit): 11 | i = 1 12 | while i*i < limit : 13 | print(i*i, end=' ') 14 | i += 1 15 | print() 16 | 17 | print_squares_of_numbers_below(100) -------------------------------------------------------------------------------- /python-code/python-shell-extract.txt: -------------------------------------------------------------------------------- 1 | Last login: Mon Jun 18 17:36:38 on ttys002 2 | Rangas-MacBook-Pro:~ rangaraokaranam$ python3 3 | Python 3.6.5 (default, Mar 30 2018, 06:42:10) 4 | [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin 5 | Type "help", "copyright", "credits" or "license" for more information. 6 | >>> 34567890 7 | 34567890 8 | >>> type(34567890) 9 | 10 | >>> type(45.6) 11 | 12 | >>> type(45.6475894237589072348957938240) 13 | 14 | >>> type(True) 15 | 16 | >>> type(False) 17 | 18 | >>> type(false) 19 | Traceback (most recent call last): 20 | File "", line 1, in 21 | NameError: name 'false' is not defined 22 | >>> type(talse) 23 | Traceback (most recent call last): 24 | File "", line 1, in 25 | NameError: name 'talse' is not defined 26 | >>> type(true) 27 | Traceback (most recent call last): 28 | File "", line 1, in 29 | NameError: name 'true' is not defined 30 | >>> type("Text") 31 | 32 | >>> type("T") 33 | 34 | >>> type('T') 35 | 36 | >>> number1 = 10 37 | >>> number2 = 20 38 | >>> type(number1) 39 | 40 | >>> number1 + number2 41 | 30 42 | >>> number1 - number2 43 | -10 44 | >>> number1 * number2 45 | 200 46 | >>> number1 / number2 47 | 0.5 48 | >>> type(number1/number2) 49 | 50 | >>> number1 = 20 51 | >>> type(number1/number2) 52 | 53 | >>> number1/number2 54 | 1.0 55 | >>> number1=30 56 | >>> number1/number2 57 | 1.5 58 | >>> number1//number2 59 | 1 60 | >>> 10 ** 3 61 | 1000 62 | >>> 5 ** 3 63 | 125 64 | >>> pow(5,3) 65 | 125 66 | >>> number1++ 67 | File "", line 1 68 | number1++ 69 | ^ 70 | SyntaxError: invalid syntax 71 | >>> number1-- 72 | File "", line 1 73 | number1-- 74 | ^ 75 | SyntaxError: invalid syntax 76 | >>> number1 += 1 77 | >>> number1 = number1 + 1 78 | >>> max(2,4,3) 79 | 4 80 | >>> min(2,4,3) 81 | 2 82 | >>> round(5.6) 83 | 6 84 | >>> round(5.65643,3) 85 | 5.656 86 | >>> round(5.65663,3) 87 | 5.657 88 | >>> float(5) 89 | 5.0 90 | >>> int(5.5) 91 | 5 92 | >>> True 93 | True 94 | >>> False 95 | False 96 | >>> is_done = True 97 | >>> i = 6 98 | >>> i > 6 99 | False 100 | >>> True and True 101 | True 102 | >>> True and False 103 | False 104 | >>> False or False 105 | False 106 | >>> !True 107 | File "", line 1 108 | !True 109 | ^ 110 | SyntaxError: invalid syntax 111 | >>> not True 112 | False 113 | >>> not False 114 | True 115 | >>> True ^ True 116 | False 117 | >>> True ^ False 118 | True 119 | >>> False ^ False 120 | False 121 | >>> i = 5 122 | >>> i > 5 123 | False 124 | >>> i >= 5 125 | True 126 | >>> i <5 127 | False 128 | >>> i <= 5 129 | True 130 | >>> i == 5 131 | True 132 | >>> i != 6 133 | True 134 | >>> os.system('clear') 135 | 136 | 137 | 138 | 139 | 0 140 | >>> i = 45 141 | >>> if i: print("Something") 142 | ... 143 | Something 144 | >>> bool(45) 145 | True 146 | >>> bool(-45) 147 | True 148 | >>> bool(-1) 149 | True 150 | >>> bool(1) 151 | True 152 | >>> bool(0) 153 | False 154 | >>> i = 0 155 | >>> if i: print("Something") 156 | ... 157 | >>> bool(0.0) 158 | False 159 | >>> bool(-1.0) 160 | True 161 | >>> str = "Test" 162 | >>> bool(str) 163 | True 164 | >>> bool("") 165 | False 166 | >>> bool('') 167 | False 168 | >>> i = 45 169 | >>> if i%2 == 1: print("odd") 170 | ... 171 | odd 172 | >>> i = 44 173 | >>> if i%2 == 1: print("odd") 174 | ... 175 | >>> if i%2: print("odd") 176 | ... 177 | >>> i = 45 178 | >>> if i%2: print("odd") 179 | ... 180 | odd 181 | >>> for ch in 'Hello World': 182 | ... print(ch) 183 | ... 184 | H 185 | e 186 | l 187 | l 188 | o 189 | 190 | W 191 | o 192 | r 193 | l 194 | d 195 | >>> for word in 'Hello World'.split(): 196 | ... print(word) 197 | ... 198 | Hello 199 | World 200 | >>> for item in (3, 8, 9): 201 | ... print(item) 202 | ... 203 | 3 204 | 8 205 | 9 206 | >>> 1/0 207 | Traceback (most recent call last): 208 | File "", line 1, in 209 | ZeroDivisionError: division by zero 210 | >>> i = 0 211 | File "", line 1 212 | i = 0 213 | ^ 214 | IndentationError: unexpected indent 215 | >>> j = 10/i 216 | >>> 2 + '2' 217 | Traceback (most recent call last): 218 | File "", line 1, in 219 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 220 | >>> values = [1,'2'] 221 | >>> sum(values) 222 | Traceback (most recent call last): 223 | File "", line 1, in 224 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 225 | >>> value 226 | Traceback (most recent call last): 227 | File "", line 1, in 228 | NameError: name 'value' is not defined 229 | >>> values.non_existing 230 | Traceback (most recent call last): 231 | File "", line 1, in 232 | AttributeError: 'list' object has no attribute 'non_existing' 233 | >>> values.non_existing() 234 | Traceback (most recent call last): 235 | File "", line 1, in 236 | AttributeError: 'list' object has no attribute 'non_existing' 237 | >>> import builtins 238 | >>> 239 | >>> help(builtins) 240 | 241 | >>> 242 | >>> help(builtins) 243 | 244 | >>> k = 10/non_existing_variable 245 | Traceback (most recent call last): 246 | File "", line 1, in 247 | NameError: name 'non_existing_variable' is not defined 248 | >>> 10/0 249 | Traceback (most recent call last): 250 | File "", line 1, in 251 | ZeroDivisionError: division by zero 252 | >>> values = [1,'1'] 253 | >>> sum(values) 254 | Traceback (most recent call last): 255 | File "", line 1, in 256 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 257 | 258 | 0 259 | >>> def multiply_by_2(data): 260 | ... return data*2 261 | ... 262 | >>> multiply_by_2 263 | 264 | >>> def do_this_and_print(func, data): 265 | ... print(func(data)) 266 | ... 267 | >>> do_this_and_print(multiply_by_2, 125) 268 | 250 269 | >>> func_example_reference = multiply_by_2 270 | >>> func_example_reference(23) 271 | 46 272 | >>> def multiply_by_3(data): 273 | ... return data * 3 274 | ... 275 | >>> do_this_and_print(multiply_by_3, 125) 276 | 375 277 | >>> do_this_and_print(lambda data:data*3, 125) 278 | 375 279 | >>> do_this_and_print(lambda data:data*5, 125) 280 | 625 281 | >>> do_this_and_print(lambda data:data*data, 125) 282 | 15625 283 | >>> do_this_and_print(lambda data:data*data*data, 125) 284 | 1953125 285 | >>> do_this_and_print(lambda data:data ** 3, 125) 286 | 1953125 287 | >>> do_this_and_print(lambda data:len(data), 'Test') 288 | 4 289 | >>> numbers = [1,89,54,35] 290 | >>> filter( lambda x : x%2==1 ,numbers) 291 | 292 | >>> list(filter( lambda x : x%2==1 ,numbers)) 293 | [1, 89, 35] 294 | >>> list(filter( lambda x : x%2==0 ,numbers)) 295 | [54] 296 | >>> list(filter( lambda x : x%2 ,numbers)) 297 | [1, 89, 35] 298 | >>> words = ["Apple", "Ant", "Bat"] 299 | >>> list(filter(lambda x: x.endswith('at'), words)) 300 | ['Bat'] 301 | >>> list( filter( lambda x: x.endswith('at') , words ) ) 302 | ['Bat'] 303 | >>> list( filter( lambda x: len(x)==3 , words ) ) 304 | ['Ant', 'Bat'] 305 | >>> list( filter( lambda x: x.startswith('A') , words ) ) 306 | ['Apple', 'Ant'] 307 | >>> os.system('clear') 308 | 309 | 310 | 311 | 0 312 | >>> words = ["Apple", "Ant", "Bat"] 313 | >>> "Apple".upper 314 | 315 | >>> "Apple".upper() 316 | 'APPLE' 317 | >>> map(lambda x: x.upper() ,words) 318 | 319 | >>> list(map(lambda x: x.upper() ,words)) 320 | ['APPLE', 'ANT', 'BAT'] 321 | >>> list(map(lambda x: len(x) ,words)) 322 | [5, 3, 3] 323 | >>> number = [1, 5, 2 , 9] 324 | >>> numbers = [1, 5, 2 , 9] 325 | >>> list(map(lambda x: x*x ,numbers)) 326 | [1, 25, 4, 81] 327 | >>> list(map(lambda x: x*x ,range(1,11))) 328 | [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 329 | >>> list(map(lambda x: x ** 3 ,range(1,11))) 330 | [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 331 | >>> os.system('clear') 332 | 333 | 334 | 0 335 | >>> numbers = [3, 15,12,10] 336 | >>> sum(numbers) 337 | 40 338 | >>> max(numbers) 339 | 15 340 | >>> reduce(lambda x,y:x+y ,numbers ) 341 | 40 342 | >>> reduce(lambda x,y:x*y ,numbers ) 343 | 5400 344 | >>> reduce(lambda x,y:max(x,y) ,numbers ) 345 | 15 346 | >>> reduce(lambda x,y:min(x,y) ,numbers ) 347 | 3 348 | >>> words = ['Apple', 'Ant','Bat'] 349 | >>> reduce(lambda x,y: x if len(x)>len(y) else y ,words ) 350 | 'Apple' 351 | >>> os.system('clear') 352 | 353 | 354 | 355 | 356 | 357 | 0 358 | >>> numbers = [3, 7, 8, 15, 24, 35, 46] 359 | >>> list(filter(lambda x: x%2==0, numbers)) 360 | [8, 24, 46] 361 | >>> list(map( lambda x:x*x ,filter(lambda x: x%2==0, numbers)) ) 362 | [64, 576, 2116] 363 | >>> sum(map( lambda x:x*x ,filter(lambda x: x%2==0, numbers)) ) 364 | 2756 365 | >>> reduce(lambda x,y:x+y, map( lambda x:x*x ,filter(lambda x: x%2==0, numbers)) ) 366 | 2756 367 | >>> os.system('clear') 368 | 369 | >>> months = [('Jan',31),('Feb',28),('Mar',31)] 370 | >>> tuple_ex = ('Dec',31) 371 | >>> tuple_ex[0] 372 | 'Dec' 373 | >>> tuple_ex[1] 374 | 31 375 | >>> sum(map(lambda x:x[1] , months)) 376 | 90 377 | >>> reduce( lambda x,y : x if x[1]>> reduce( lambda x,y : x if x[1]>> (1,1) == (1,1) 384 | True 385 | >>> ('1',1) == ('1',1) 386 | True 387 | >>> ('1',1) == ('1',2) 388 | False 389 | >>> ('1',1) == ('2',1) 390 | False 391 | >>> (1,1) > (1,1) 392 | False 393 | >>> (1,1) > (0,1) 394 | True 395 | >>> (1,2) > (1,1) 396 | True 397 | >>> (1,2) > (1,3) 398 | False 399 | >>> (1,2) < (1,3) 400 | True 401 | >>> os.system('clear') 402 | 403 | 404 | 405 | >>> import datetime 406 | >>> datetime.datetime.today() 407 | datetime.datetime(2018, 6, 27, 17, 4, 2, 258274) 408 | >>> today = datetime.datetime.today() 409 | >>> today.__str__() 410 | '2018-06-27 17:04:12.850102' 411 | >>> today.__repr__() 412 | 'datetime.datetime(2018, 6, 27, 17, 4, 12, 850102)' 413 | >>> today2 = datetime.datetime(2018, 6, 27, 17, 4, 12, 850102) 414 | >>> os.system('clear') 415 | 416 | >>> import random 417 | >>> random.random() 418 | 0.08354021584691451 419 | >>> random.random() 420 | 0.7427402538127307 421 | >>> random.random() 422 | 0.18347949440543265 423 | >>> random.randint(1,10) 424 | 1 425 | >>> random.randint(1,10) 426 | 4 427 | >>> random.randint(1,10) 428 | 2 429 | >>> random.randint(1,10) 430 | 1 431 | >>> random.randrange(1,25,2) 432 | 17 433 | >>> random.randrange(1,25,2) 434 | 19 435 | >>> random.randrange(1,25,2) 436 | 19 437 | >>> random.randrange(0,30,3) 438 | 21 439 | >>> random.randrange(0,30,3) 440 | 18 441 | >>> list = [2, 7, 9,34,56] 442 | >>> random.choice(list) 443 | 7 444 | >>> random.choice(list) 445 | 34 446 | >>> random.choice(list) 447 | 9 448 | >>> random.choice(list) 449 | 56 450 | >>> random.choice(list) 451 | 34 452 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 453 | 'r' 454 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 455 | 'x' 456 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 457 | 'a' 458 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 459 | 's' 460 | >>> random.choice('abcdefghijklmnopqrstuvwxyz') 461 | 'q' 462 | >>> random.sample(list, 2) 463 | [34, 9] 464 | >>> random.sample(list, 3) 465 | [7, 2, 9] 466 | >>> random.sample(list, 5) 467 | [7, 2, 9, 34, 56] 468 | >>> def some_function(): 469 | ... return 1, 'string', 4.5 470 | ... 471 | >>> tuple1 = some_function() 472 | >>> tuple1[0] 473 | 1 474 | >>> tuple1[1] 475 | 'string' 476 | >>> 477 | >>> tuple1[2] 478 | 4.5 479 | >>> os.system('clear') 480 | 481 | >>> from collections import namedtuple 482 | >>> Point = namedtuple('Point',['x','y']) 483 | >>> point1 = Point(1,2) 484 | >>> point1.x 485 | 1 486 | >>> point1.y 487 | 2 488 | >>> 3DPoint = namedtuple('3DPoint',['x','y','z']) 489 | File "", line 1 490 | 3DPoint = namedtuple('3DPoint',['x','y','z']) 491 | ^ 492 | SyntaxError: invalid syntax 493 | >>> ThreeDPoint = namedtuple('ThreeDPoint',['x','y','z']) 494 | >>> point2 = ThreeDPoint(7, 4, 6) 495 | >>> point2.x 496 | 7 497 | >>> point2.z 498 | 6 499 | >>> 500 | 501 | >>> message = "Hello World" 502 | >>> message = 'Hello World' 503 | >>> message = 'Hello World" 504 | File "", line 1 505 | message = 'Hello World" 506 | ^ 507 | SyntaxError: EOL while scanning string literal 508 | >>> message = "Hello World" 509 | >>> type(message) 510 | 511 | >>> message.upper() 512 | 'HELLO WORLD' 513 | >>> message.lower() 514 | 'hello world' 515 | >>> message = "hello" 516 | >>> message.capitalize() 517 | 'Hello' 518 | >>> "hello".capitalize() 519 | 'Hello' 520 | >>> 'hello'.capitalize() 521 | 'Hello' 522 | >>> 'hello'.islower() 523 | True 524 | >>> 'Hello'.islower() 525 | False 526 | >>> 'Hello'.istitle() 527 | True 528 | >>> 'hello'.istitle() 529 | False 530 | >>> 'hello'.isupper() 531 | False 532 | >>> 'Hello'.isupper() 533 | False 534 | >>> 'HELLO'.isupper() 535 | True 536 | >>> '123'.isdigit() 537 | True 538 | >>> 'A23'.isdigit() 539 | False 540 | >>> '2 3'.isdigit() 541 | False 542 | >>> '23'.isdigit() 543 | True 544 | >>> '23'.isalpha() 545 | False 546 | >>> '2A'.isalpha() 547 | False 548 | >>> 'ABC'.isalpha() 549 | True 550 | >>> 'ABC123'.isalnum() 551 | True 552 | >>> 'ABC 123'.isalnum() 553 | False 554 | >>> 'Hello World'.endswith('World') 555 | True 556 | >>> 'Hello World'.endswith('ld') 557 | True 558 | >>> 'Hello World'.endswith('old') 559 | False 560 | >>> 'Hello World'.endswith('Wo') 561 | False 562 | >>> 'Hello World'.startswith('Wo') 563 | False 564 | >>> 'Hello World'.startswith('He') 565 | True 566 | >>> 'Hello World'.startswith('Hell0') 567 | False 568 | >>> 'Hello World'.startswith('Hello') 569 | True 570 | >>> 'Hello World'.find('Hello') 571 | 0 572 | >>> 'Hello World'.find('ello') 573 | 1 574 | >>> 'Hello World'.find('Ello') 575 | -1 576 | >>> 'Hello World'.find('bello') 577 | -1 578 | >>> 'Hello World'.find('Ello') 579 | -1 580 | >>> os.system('clear') 581 | Traceback (most recent call last): 582 | File "", line 1, in 583 | NameError: name 'os' is not defined 584 | >>> import os 585 | >>> os.system('clear') 586 | 587 | 0 588 | >>> str(True) 589 | 'True' 590 | >>> bool('True') 591 | True 592 | >>> bool('true') 593 | True 594 | >>> bool('tru') 595 | True 596 | >>> bool('false') 597 | True 598 | >>> bool('False') 599 | True 600 | >>> bool('') 601 | False 602 | >>> str(123) 603 | '123' 604 | >>> str(12345) 605 | '12345' 606 | >>> str(12345.45678) 607 | '12345.45678' 608 | >>> int('45') 609 | 45 610 | >>> int('45.56') 611 | Traceback (most recent call last): 612 | File "", line 1, in 613 | ValueError: invalid literal for int() with base 10: '45.56' 614 | >>> int('45dfsafk') 615 | Traceback (most recent call last): 616 | File "", line 1, in 617 | ValueError: invalid literal for int() with base 10: '45dfsafk' 618 | >>> int('45abc',16) 619 | 285372 620 | >>> int('a',16) 621 | 10 622 | >>> int('b',16) 623 | 11 624 | >>> int('c',16) 625 | 12 626 | >>> int('f',16) 627 | 15 628 | >>> int('g',16) 629 | Traceback (most recent call last): 630 | File "", line 1, in 631 | ValueError: invalid literal for int() with base 16: 'g' 632 | >>> float("34.43") 633 | 34.43 634 | >>> float("34.43rer") 635 | Traceback (most recent call last): 636 | File "", line 1, in 637 | ValueError: could not convert string to float: '34.43rer' 638 | >>> os.system('clear') 639 | 640 | 0 641 | >>> message = "Hello" 642 | >>> message.upper() 643 | 'HELLO' 644 | >>> message 645 | 'Hello' 646 | >>> message = message.upper() 647 | >>> message 648 | 'HELLO' 649 | >>> message = "Hello" 650 | >>> message.upper() 651 | 'HELLO' 652 | >>> message_upper = message.upper() 653 | >>> message = "ABC" 654 | >>> message = message.lowercase() 655 | Traceback (most recent call last): 656 | File "", line 1, in 657 | AttributeError: 'str' object has no attribute 'lowercase' 658 | >>> message = message.lower() 659 | >>> os.system('clear') 660 | 661 | 662 | 0 663 | >>> message = "Hello World" 664 | >>> message[0] 665 | 'H' 666 | >>> type(message[0]) 667 | 668 | >>> type(message) 669 | 670 | >>> message[0] 671 | 'H' 672 | >>> message[1] 673 | 'e' 674 | >>> message[2] 675 | 'l' 676 | >>> message[3] 677 | 'l' 678 | >>> message[100] 679 | Traceback (most recent call last): 680 | File "", line 1, in 681 | IndexError: string index out of range 682 | >>> for ch in message: 683 | ... print(ch) 684 | ... 685 | H 686 | e 687 | l 688 | l 689 | o 690 | 691 | W 692 | o 693 | r 694 | l 695 | d 696 | >>> os.system('clear') 697 | 698 | 0 699 | >>> import string 700 | >>> string. 701 | string.Formatter( string.ascii_uppercase string.octdigits 702 | string.Template( string.capwords( string.printable 703 | string.ascii_letters string.digits string.punctuation 704 | string.ascii_lowercase string.hexdigits string.whitespace 705 | >>> string.ascii_letters 706 | 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 707 | >>> string.ascii_lowercase 708 | 'abcdefghijklmnopqrstuvwxyz' 709 | >>> string.ascii_uppercase 710 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 711 | >>> string.digits 712 | '0123456789' 713 | >>> string.hexdigits 714 | '0123456789abcdefABCDEF' 715 | >>> string.punctuation 716 | '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' 717 | >>> 'a' in string.ascii_letters 718 | True 719 | >>> string.ascii_letters 720 | 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 721 | >>> 'ab' in string.ascii_letters 722 | True 723 | >>> 'abc' in string.ascii_letters 724 | True 725 | >>> 'a' in string.ascii_letters 726 | True 727 | >>> '1' in '13579' 728 | True 729 | >>> '2' in '13579' 730 | False 731 | >>> '4' in '13579' 732 | False 733 | >>> char = 'a' 734 | >>> vowel_string = 'aeiouAEIOU' 735 | >>> char in vowel_string 736 | True 737 | >>> char = 'b' 738 | >>> char in vowel_string 739 | False 740 | >>> vowel_string = 'AEIOU' 741 | >>> char.upper() in vowel_string 742 | False 743 | >>> char = 'a' 744 | >>> char.upper() in vowel_string 745 | True 746 | >>> vowel_string = 'aeiou' 747 | >>> char.lower() in vowel_string 748 | True 749 | >>> char = 'A' 750 | >>> char.lower() in vowel_string 751 | True 752 | >>> import string 753 | >>> string. 754 | string.Formatter( string.ascii_uppercase string.octdigits 755 | string.Template( string.capwords( string.printable 756 | string.ascii_letters string.digits string.punctuation 757 | string.ascii_lowercase string.hexdigits string.whitespace 758 | >>> string.ascii_uppercase 759 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 760 | >>> for char in string.ascii_uppercase: 761 | ... print(char) 762 | ... 763 | A 764 | B 765 | C 766 | D 767 | E 768 | F 769 | G 770 | H 771 | I 772 | J 773 | K 774 | L 775 | M 776 | N 777 | O 778 | P 779 | Q 780 | R 781 | S 782 | T 783 | U 784 | V 785 | W 786 | X 787 | Y 788 | Z 789 | >>> for char in string.ascii_lowercase: 790 | ... print(char) 791 | ... 792 | a 793 | b 794 | c 795 | d 796 | e 797 | f 798 | g 799 | h 800 | i 801 | j 802 | k 803 | l 804 | m 805 | n 806 | o 807 | p 808 | q 809 | r 810 | s 811 | t 812 | u 813 | v 814 | w 815 | x 816 | y 817 | z 818 | >>> for char in string. 819 | string.Formatter( string.ascii_uppercase string.octdigits 820 | string.Template( string.capwords( string.printable 821 | string.ascii_letters string.digits string.punctuation 822 | string.ascii_lowercase string.hexdigits string.whitespace 823 | >>> for char in string.digits: 824 | ... print(char) 825 | ... 826 | 0 827 | 1 828 | 2 829 | 3 830 | 4 831 | 5 832 | 6 833 | 7 834 | 8 835 | 9 836 | >>> vowel_string = 'aeiou' 837 | >>> char.lower() in vowel_string 838 | False 839 | >>> 'b'.lower() not in vowel_string 840 | True 841 | >>> 'a'.lower() not in vowel_string 842 | False 843 | >>> '1'.lower() not in vowel_string 844 | True 845 | >>> '1'.isalpha() and '1'.lower() not in vowel_string 846 | False 847 | >>> char.isalpha() and char.lower() not in vowel_string 848 | True 849 | >>> char 850 | 'b' 851 | >>> char = '1' 852 | >>> char.isalpha() and char.lower() not in vowel_string 853 | False 854 | >>> os.system('clear') 855 | 856 | 0 857 | >>> string_example = "This is a great thing" 858 | >>> string_example. 859 | string_example.capitalize( string_example.join( 860 | string_example.casefold( string_example.ljust( 861 | string_example.center( string_example.lower( 862 | string_example.count( string_example.lstrip( 863 | string_example.encode( string_example.maketrans( 864 | string_example.endswith( string_example.partition( 865 | string_example.expandtabs( string_example.replace( 866 | string_example.find( string_example.rfind( 867 | string_example.format( string_example.rindex( 868 | string_example.format_map( string_example.rjust( 869 | string_example.index( string_example.rpartition( 870 | string_example.isalnum( string_example.rsplit( 871 | string_example.isalpha( string_example.rstrip( 872 | string_example.isdecimal( string_example.split( 873 | string_example.isdigit( string_example.splitlines( 874 | string_example.isidentifier( string_example.startswith( 875 | string_example.islower( string_example.strip( 876 | string_example.isnumeric( string_example.swapcase( 877 | string_example.isprintable( string_example.title( 878 | string_example.isspace( string_example.translate( 879 | string_example.istitle( string_example.upper( 880 | string_example.isupper( string_example.zfill( 881 | >>> string_example.split() 882 | ['This', 'is', 'a', 'great', 'thing'] 883 | >>> for word in string_example.split(): 884 | ... print(word) 885 | ... 886 | This 887 | is 888 | a 889 | great 890 | thing 891 | >>> string_example = "This\nis\n\ngreat\nthing" 892 | >>> print(string_example) 893 | This 894 | is 895 | 896 | great 897 | thing 898 | >>> string_example = "This\nis\na\ngreat\nthing" 899 | >>> print(string_example) 900 | This 901 | is 902 | a 903 | great 904 | thing 905 | >>> string_example.split 906 | string_example.split( string_example.splitlines( 907 | >>> string_example.splitlines() 908 | ['This', 'is', 'a', 'great', 'thing'] 909 | >>> 1 + 2 910 | 3 911 | >>> "1" + "2" 912 | '12' 913 | >>> "1" + 1 914 | Traceback (most recent call last): 915 | File "", line 1, in 916 | TypeError: must be str, not int 917 | >>> "ABC" + "DEF" 918 | 'ABCDEF' 919 | >>> 1 * 20 920 | 20 921 | >>> '1' * 20 922 | '11111111111111111111' 923 | >>> 'A' * 10 924 | 'AAAAAAAAAA' 925 | >>> str = "test" 926 | >>> str2 = "test1" 927 | >>> str == str2 928 | False 929 | >>> str2 = "test" 930 | >>> str == str2 931 | True 932 | >>> 933 | 934 | Last login: Fri May 18 14:08:00 on ttys004 935 | Rangas-MacBook-Pro:~ rangaraokaranam$ python3 936 | Python 3.6.5 (default, Mar 30 2018, 06:42:10) 937 | [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin 938 | Type "help", "copyright", "credits" or "license" for more information. 939 | >>> mark1 = 45 940 | >>> mark2 = 54 941 | >>> mark3 = 80 942 | >>> mark1 + mark2 + mark3 943 | 179 944 | >>> (mark1 + mark2 + mark3)/3 945 | 59.666666666666664 946 | >>> mark4 = 43 947 | >>> (mark1 + mark2 + mark3 + mark4)/3 948 | 74.0 949 | >>> (mark1 + mark2 + mark3 + mark4)/4 950 | 55.5 951 | >>> marks = [45, 54, 80] 952 | >>> sum(marks) 953 | 179 954 | >>> sum(marks)/len(marks) 955 | 59.666666666666664 956 | >>> marks.append(43) 957 | >>> sum(marks)/len(marks) 958 | 55.5 959 | >>> type(marks) 960 | 961 | >>> import os 962 | >>> os.system('clear') 963 | 964 | 0 965 | >>> marks = [23,56,67] 966 | >>> sum(marks) 967 | 146 968 | >>> max(marks) 969 | 67 970 | >>> min(marks) 971 | 23 972 | >>> len(marks) 973 | 3 974 | >>> marks.append(76) 975 | >>> marks 976 | [23, 56, 67, 76] 977 | >>> marks.insert(2, 60) 978 | >>> marks 979 | [23, 56, 60, 67, 76] 980 | >>> marks.remove(60) 981 | >>> 55 in marks 982 | False 983 | >>> 56 in marks 984 | True 985 | >>> marks.index(67) 986 | 2 987 | >>> marks 988 | [23, 56, 67, 76] 989 | >>> marks.index(69) 990 | Traceback (most recent call last): 991 | File "", line 1, in 992 | ValueError: 69 is not in list 993 | >>> for mark in marks: 994 | ... print(mark) 995 | ... 996 | 23 997 | 56 998 | 67 999 | 76 1000 | >>> os.system('clear') 1001 | 1002 | 0 1003 | >>> animals = ['Cat', 'Dog','Elephant'] 1004 | >>> len(animals) 1005 | 3 1006 | >>> sum(animals) 1007 | Traceback (most recent call last): 1008 | File "", line 1, in 1009 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 1010 | >>> animals.append('Fish') 1011 | >>> animals 1012 | ['Cat', 'Dog', 'Elephant', 'Fish'] 1013 | >>> animals.remove('Dog') 1014 | >>> animals 1015 | ['Cat', 'Elephant', 'Fish'] 1016 | >>> animals[2] 1017 | 'Fish' 1018 | >>> animals[1] 1019 | 'Elephant' 1020 | >>> animals[0] 1021 | 'Cat' 1022 | >>> animals[4] 1023 | Traceback (most recent call last): 1024 | File "", line 1, in 1025 | IndexError: list index out of range 1026 | >>> del animals[2] 1027 | >>> animals 1028 | ['Cat', 'Elephant'] 1029 | >>> animals.extend('Fish') 1030 | >>> animals 1031 | ['Cat', 'Elephant', 'F', 'i', 's', 'h'] 1032 | >>> animals.append('Fish') 1033 | >>> animals 1034 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish'] 1035 | >>> animals.extend(['Giraffe', 'Horse']) 1036 | >>> animals 1037 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse'] 1038 | >>> animals = animals + ['Jackal','Kangaroo'] 1039 | >>> animals 1040 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal', 'Kangaroo'] 1041 | >>> animals += ['Lion','Monkey'] 1042 | >>> animals 1043 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal', 'Kangaroo', 'Lion', 'Monkey'] 1044 | >>> animals.append(10) 1045 | >>> animals 1046 | ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal', 'Kangaroo', 'Lion', 'Monkey', 10] 1047 | >>> os.system('clear') 1048 | 1049 | 0 1050 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1051 | >>> len(numbers) 1052 | 10 1053 | >>> number[2] 1054 | Traceback (most recent call last): 1055 | File "", line 1, in 1056 | NameError: name 'number' is not defined 1057 | >>> numbers[2] 1058 | 'Two' 1059 | >>> numbers[2:6] 1060 | ['Two', 'Three', 'Four', 'Five'] 1061 | >>> numbers[:6] 1062 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five'] 1063 | >>> numbers[3:] 1064 | ['Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1065 | >>> numbers[1:8:2] 1066 | ['One', 'Three', 'Five', 'Seven'] 1067 | >>> numbers[1:8:3] 1068 | ['One', 'Four', 'Seven'] 1069 | >>> numbers[::3] 1070 | ['Zero', 'Three', 'Six', 'Nine'] 1071 | >>> numbers[::-1] 1072 | ['Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'Zero'] 1073 | >>> numbers[::-3] 1074 | ['Nine', 'Six', 'Three', 'Zero'] 1075 | >>> del numbers[3:] 1076 | >>> numbers 1077 | ['Zero', 'One', 'Two'] 1078 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1079 | >>> del numbers[5:7] 1080 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1081 | >>> numbers[3:7] = [3,4,5,6] 1082 | >>> numbers 1083 | ['Zero', 'One', 'Two', 3, 4, 5, 6, 'Seven', 'Eight', 'Nine'] 1084 | >>> os.system('clear') 1085 | 1086 | 1087 | 1088 | 1089 | 1090 | 1091 | 1092 | 0 1093 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1094 | >>> numbers.reverse() 1095 | >>> numbers 1096 | ['Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'Zero'] 1097 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1098 | >>> numbers 1099 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1100 | >>> reversed(numbers) 1101 | 1102 | >>> for number in reversed(numbers): 1103 | ... print(number) 1104 | ... 1105 | Nine 1106 | Eight 1107 | Seven 1108 | Six 1109 | Five 1110 | Four 1111 | Three 1112 | Two 1113 | One 1114 | Zero 1115 | >>> numbers 1116 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1117 | >>> numbers.sort() 1118 | >>> numbers 1119 | ['Eight', 'Five', 'Four', 'Nine', 'One', 'Seven', 'Six', 'Three', 'Two', 'Zero'] 1120 | >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] 1121 | >>> for number in sorted(numbers): 1122 | ... print(number) 1123 | ... 1124 | Eight 1125 | Five 1126 | Four 1127 | Nine 1128 | One 1129 | Seven 1130 | Six 1131 | Three 1132 | Two 1133 | Zero 1134 | >>> numbers 1135 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1136 | >>> for number in sorted(numbers, key=len): 1137 | ... print(number) 1138 | ... 1139 | One 1140 | Two 1141 | Six 1142 | Zero 1143 | Four 1144 | Five 1145 | Nine 1146 | Three 1147 | Seven 1148 | Eight 1149 | >>> for number in sorted(numbers, key=len, reverse=True): 1150 | ... print(number) 1151 | ... 1152 | Three 1153 | Seven 1154 | Eight 1155 | Zero 1156 | Four 1157 | Five 1158 | Nine 1159 | One 1160 | Two 1161 | Six 1162 | >>> numbers.sort(key=len) 1163 | >>> numbers 1164 | ['One', 'Two', 'Six', 'Zero', 'Four', 'Five', 'Nine', 'Three', 'Seven', 'Eight'] 1165 | >>> numbers.sort(key=len, reverse=True) 1166 | >>> numbers 1167 | ['Three', 'Seven', 'Eight', 'Zero', 'Four', 'Five', 'Nine', 'One', 'Two', 'Six'] 1168 | >>> os.system('clear') 1169 | 1170 | 0 1171 | >>> numbers = [] 1172 | >>> numbers.append(1) 1173 | >>> numbers.append(2) 1174 | >>> numbers.append(3) 1175 | >>> numbers.append(4) 1176 | >>> numbers.pop() 1177 | 4 1178 | >>> numbers 1179 | [1, 2, 3] 1180 | >>> numbers.pop() 1181 | 3 1182 | >>> numbers 1183 | [1, 2] 1184 | >>> numbers.append(10) 1185 | >>> numbers.pop() 1186 | 10 1187 | >>> numbers 1188 | [1, 2] 1189 | >>> numbers = [] 1190 | >>> numbers.append(1) 1191 | >>> numbers.append(2) 1192 | >>> numbers.append(3) 1193 | >>> numbers.append(4) 1194 | >>> numbers.pop(0) 1195 | 1 1196 | >>> numbers 1197 | [2, 3, 4] 1198 | >>> numbers.pop(0) 1199 | 2 1200 | >>> numbers 1201 | [3, 4] 1202 | >>> numbers.append(10) 1203 | >>> numbers.pop(0) 1204 | 3 1205 | >>> numbers.pop(0) 1206 | 4 1207 | >>> numbers.pop(0) 1208 | 10 1209 | >>> numbers 1210 | [] 1211 | >>> os.system('clear') 1212 | 1213 | 0 1214 | >>> numbers = ['Zero', 'One','Two','Three','Four','Five','Six','Seven', 'Eight','Nine'] 1215 | >>> numbers_length_four=[] 1216 | >>> for number in numbers: 1217 | ... if len(number)== 4: 1218 | ... numbers_length_four.append(number) 1219 | ... 1220 | >>> numbers_length_four 1221 | ['Zero', 'Four', 'Five', 'Nine'] 1222 | >>> numbers_length_four = [ number for number in numbers ] 1223 | >>> numbers_length_four 1224 | ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] 1225 | >>> numbers_length_four = [ len(number) for number in numbers ] 1226 | >>> numbers_length_four 1227 | [4, 3, 3, 5, 4, 4, 3, 5, 5, 4] 1228 | >>> numbers_length_four = [ number.upper() for number in numbers ] 1229 | >>> numbers_length_four 1230 | ['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE'] 1231 | >>> numbers_length_four = [ number for number in numbers if len(number)==4 ] 1232 | >>> numbers_length_four 1233 | ['Zero', 'Four', 'Five', 'Nine'] 1234 | >>> values = [3, 6, 9, 1, 4, 15, 6, 3] 1235 | >>> values_even = [ value for value in values if value%2==0] 1236 | >>> values_even 1237 | [6, 4, 6] 1238 | >>> values_odd = [ value for value in values if value%2==1] 1239 | >>> values_odd 1240 | [3, 9, 1, 15, 3] 1241 | >>> os.system('clear') 1242 | 1243 | 0 1244 | >>> numbers = [1,2,3,2,1] 1245 | >>> numbers 1246 | [1, 2, 3, 2, 1] 1247 | >>> numbers_set = set(numbers) 1248 | >>> numbers_set 1249 | {1, 2, 3} 1250 | >>> numbers_set.add(3) 1251 | >>> numbers_set 1252 | {1, 2, 3} 1253 | >>> numbers_set.add(4) 1254 | >>> numbers_set 1255 | {1, 2, 3, 4} 1256 | >>> numbers_set.add(0) 1257 | >>> numbers_set 1258 | {0, 1, 2, 3, 4} 1259 | >>> numbers_set.remove(0) 1260 | >>> numbers_set 1261 | {1, 2, 3, 4} 1262 | >>> numbers_set[0] 1263 | Traceback (most recent call last): 1264 | File "", line 1, in 1265 | TypeError: 'set' object does not support indexing 1266 | >>> 1 in numbers_set 1267 | True 1268 | >>> 5 in numbers_set 1269 | False 1270 | >>> min(numbers_set) 1271 | 1 1272 | >>> max(numbers_set) 1273 | 4 1274 | >>> sum(numbers_set) 1275 | 10 1276 | >>> len(numbers_set) 1277 | 4 1278 | >>> numbers_1_to_5_set = set(range(1,6)) 1279 | >>> numbers_1_to_5_set 1280 | {1, 2, 3, 4, 5} 1281 | >>> numbers_4_to_10_set = set(range(4,11)) 1282 | >>> numbers_4_to_10_set 1283 | {4, 5, 6, 7, 8, 9, 10} 1284 | >>> numbers_1_to_5_set + numbers_4_to_10_set 1285 | Traceback (most recent call last): 1286 | File "", line 1, in 1287 | TypeError: unsupported operand type(s) for +: 'set' and 'set' 1288 | >>> numbers_1_to_5_set | numbers_4_to_10_set 1289 | {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 1290 | >>> numbers_1_to_5_set & numbers_4_to_10_set 1291 | {4, 5} 1292 | >>> numbers_1_to_5_set - numbers_4_to_10_set 1293 | {1, 2, 3} 1294 | >>> numbers_4_to_10_set - numbers_1_to_5_set 1295 | {6, 7, 8, 9, 10} 1296 | >>> os.system('clear') 1297 | 1298 | 0 1299 | >>> occurances = dict(a=5 b=6 c=8) 1300 | File "", line 1 1301 | occurances = dict(a=5 b=6 c=8) 1302 | ^ 1303 | SyntaxError: invalid syntax 1304 | >>> occurances = dict(a=5,b=6,c=8) 1305 | >>> occurances 1306 | {'a': 5, 'b': 6, 'c': 8} 1307 | >>> type(occurances) 1308 | 1309 | >>> occurances['d'] = 15 1310 | >>> occurances 1311 | {'a': 5, 'b': 6, 'c': 8, 'd': 15} 1312 | >>> occurances['d'] = 10 1313 | >>> occurances 1314 | {'a': 5, 'b': 6, 'c': 8, 'd': 10} 1315 | >>> occurances['d'] 1316 | 10 1317 | >>> occurances['e'] 1318 | Traceback (most recent call last): 1319 | File "", line 1, in 1320 | KeyError: 'e' 1321 | >>> occurances.get('d') 1322 | 10 1323 | >>> occurances.get('e') 1324 | >>> occurances.get('e', 10) 1325 | 10 1326 | >>> occurances 1327 | {'a': 5, 'b': 6, 'c': 8, 'd': 10} 1328 | >>> occurances.keys() 1329 | dict_keys(['a', 'b', 'c', 'd']) 1330 | >>> occurances.values() 1331 | dict_values([5, 6, 8, 10]) 1332 | >>> occurances.items() 1333 | dict_items([('a', 5), ('b', 6), ('c', 8), ('d', 10)]) 1334 | >>> for (key,value) in occurances.items(): 1335 | ... print(f"{key} {value}") 1336 | ... 1337 | a 5 1338 | b 6 1339 | c 8 1340 | d 10 1341 | >>> occurances['a']=0 1342 | >>> occurances 1343 | {'a': 0, 'b': 6, 'c': 8, 'd': 10} 1344 | >>> del occurances['a'] 1345 | >>> occurances 1346 | {'b': 6, 'c': 8, 'd': 10} 1347 | >>> os.system('clear' 1348 | ... ) 1349 | 1350 | 1351 | 1352 | 1353 | 1354 | 1355 | 1356 | 1357 | 1358 | 0 1359 | >>> str = "This is an awesome occasion. This has never happened before." 1360 | >>> squares_first_ten_numbers = [ i*i for i in range(1,11) ] 1361 | >>> type(squares_first_ten_numbers) 1362 | 1363 | >>> squares_first_ten_numbers_set = set(squares_of_first_10_numbers) 1364 | >>> squares_first_ten_numbers_set = { i*i for i in range(1,11)} 1365 | >>> type(squares_first_ten_numbers_set) 1366 | 1367 | >>> squares_first_ten_numbers_dict = { i:i*i for i in range(1,11)} 1368 | >>> type(squares_first_ten_numbers_dict) 1369 | 1370 | >>> squares_first_ten_numbers_dict 1371 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} 1372 | >>> type([]) 1373 | 1374 | >>> type({}) 1375 | 1376 | >>> type(set()) 1377 | 1378 | >>> type({1}) 1379 | 1380 | >>> type({'A':5}) 1381 | 1382 | >>> type(()) 1383 | 1384 | >>> type((1,2,3)) 1385 | 1386 | >>> 1387 | 1388 | 1389 | >>> print(4.5 - 3.2) 1390 | 1.2999999999999998 1391 | >>> value1 = Decimal('4.5') 1392 | Traceback (most recent call last): 1393 | File "", line 1, in 1394 | NameError: name 'Decimal' is not defined 1395 | >>> import decimal 1396 | >>> from decimal import Decimal 1397 | >>> value1 = Decimal('4.5') 1398 | >>> value2 = Decimal('3.2') 1399 | >>> value1 - value2 1400 | Decimal('1.3') 1401 | >>> import math 1402 | >>> math. 1403 | math.acos( math.erf( math.inf math.pi 1404 | math.acosh( math.erfc( math.isclose( math.pow( 1405 | math.asin( math.exp( math.isfinite( math.radians( 1406 | math.asinh( math.expm1( math.isinf( math.sin( 1407 | math.atan( math.fabs( math.isnan( math.sinh( 1408 | math.atan2( math.factorial( math.ldexp( math.sqrt( 1409 | math.atanh( math.floor( math.lgamma( math.tan( 1410 | math.ceil( math.fmod( math.log( math.tanh( 1411 | math.copysign( math.frexp( math.log10( math.tau 1412 | math.cos( math.fsum( math.log1p( math.trunc( 1413 | math.cosh( math.gamma( math.log2( 1414 | math.degrees( math.gcd( math.modf( 1415 | math.e math.hypot( math.nan 1416 | >>> math.pi 1417 | 3.141592653589793 1418 | >>> math.e 1419 | 2.718281828459045 1420 | >>> help(math.factorial) 1421 | 1422 | >>> help(math.ceil) 1423 | 1424 | >>> math.ceil(5.5) 1425 | 6 1426 | >>> math.ceil(-5.5) 1427 | -5 1428 | >>> import os 1429 | >>> os.system('clear') 1430 | 1431 | 0 1432 | >>> import statistics 1433 | >>> statistics. 1434 | statistics.Decimal( statistics.mean( 1435 | statistics.Fraction( statistics.median( 1436 | statistics.StatisticsError( statistics.median_grouped( 1437 | statistics.bisect_left( statistics.median_high( 1438 | statistics.bisect_right( statistics.median_low( 1439 | statistics.chain( statistics.mode( 1440 | statistics.collections statistics.numbers 1441 | statistics.decimal statistics.pstdev( 1442 | statistics.groupby( statistics.pvariance( 1443 | statistics.harmonic_mean( statistics.stdev( 1444 | statistics.math statistics.variance( 1445 | >>> marks = [1, 6, 9, 23, 2] 1446 | >>> statistics.mean(marks) 1447 | 8.2 1448 | >>> statistics.median(marks) 1449 | 6 1450 | >>> marks = [1, 6, 9, 23, 2, 7] 1451 | >>> statistics.median(marks) 1452 | 6.5 1453 | >>> statistics.median_high(marks) 1454 | 7 1455 | >>> statistics.median_low(marks) 1456 | 6 1457 | >>> statistics.variance(marks) 1458 | 63.2 1459 | >>> os.system('clear') 1460 | 1461 | 0 1462 | >>> from collections import deque 1463 | >>> queue = deque(['Zero','One','Two']) 1464 | >>> queue.pop() 1465 | 'Two' 1466 | >>> queue.append('Three') 1467 | >>> queue 1468 | deque(['Zero', 'One', 'Three']) 1469 | >>> queue.append('Four') 1470 | >>> queue.append('Five') 1471 | >>> queue.appendLeft('Minus One') 1472 | Traceback (most recent call last): 1473 | File "", line 1, in 1474 | AttributeError: 'collections.deque' object has no attribute 'appendLeft' 1475 | >>> queue.append 1476 | queue.append( queue.appendleft( 1477 | >>> queue.appendleft('Minus One') 1478 | >>> queue 1479 | deque(['Minus One', 'Zero', 'One', 'Three', 'Four', 'Five']) 1480 | >>> queue.pop() 1481 | 'Five' 1482 | >>> queue.popleft() 1483 | 'Minus One' 1484 | >>> os.system('clear') 1485 | 1486 | 0 1487 | >>> import datetime 1488 | >>> datetime.datetime.today() 1489 | datetime.datetime(2018, 5, 21, 9, 59, 57, 450683) 1490 | >>> today_date = datetime.datetime.today() 1491 | >>> today_date 1492 | datetime.datetime(2018, 5, 21, 10, 0, 39, 732463) 1493 | >>> today_date.year 1494 | 2018 1495 | >>> today_date.month 1496 | 5 1497 | >>> today_date.day 1498 | 21 1499 | >>> today_date.hour 1500 | 10 1501 | >>> today_date.minute 1502 | 0 1503 | >>> today_date.second 1504 | 39 1505 | >>> some_date = datetime.datetime(2019, 5, 27) 1506 | >>> some_date 1507 | datetime.datetime(2019, 5, 27, 0, 0) 1508 | >>> some_date = datetime.datetime(2019, 5, 27, 9, 5,25) 1509 | >>> some_date 1510 | datetime.datetime(2019, 5, 27, 9, 5, 25) 1511 | >>> some_date = datetime.datetime(2019, 5, 27, 9, 5,25, 234567) 1512 | >>> some_date 1513 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 1514 | >>> some_date.date() 1515 | datetime.date(2019, 5, 27) 1516 | >>> some_date.time() 1517 | datetime.time(9, 5, 25, 234567) 1518 | >>> some_date 1519 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 1520 | >>> day = some_date 1521 | >>> day 1522 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 1523 | >>> day + time.timedelta(day=90) 1524 | Traceback (most recent call last): 1525 | File "", line 1, in 1526 | NameError: name 'time' is not defined 1527 | >>> day + datetime.timedelta(day=90) 1528 | Traceback (most recent call last): 1529 | File "", line 1, in 1530 | TypeError: 'day' is an invalid keyword argument for this function 1531 | >>> day + datetime.timedelta(days=90) 1532 | datetime.datetime(2019, 8, 25, 9, 5, 25, 234567) 1533 | >>> day 1534 | datetime.datetime(2019, 5, 27, 9, 5, 25, 234567) 1535 | >>> day + datetime.timedelta(days=90) 1536 | datetime.datetime(2019, 8, 25, 9, 5, 25, 234567) 1537 | >>> day + datetime.timedelta(weeks=3) 1538 | datetime.datetime(2019, 6, 17, 9, 5, 25, 234567) 1539 | >>> day + datetime.timedelta(hours=48) 1540 | datetime.datetime(2019, 5, 29, 9, 5, 25, 234567) 1541 | >>> os.system('clear') 1542 | 1543 | 0 1544 | >>> import math 1545 | >>> math. 1546 | math.acos( math.erf( math.inf math.pi 1547 | math.acosh( math.erfc( math.isclose( math.pow( 1548 | math.asin( math.exp( math.isfinite( math.radians( 1549 | math.asinh( math.expm1( math.isinf( math.sin( 1550 | math.atan( math.fabs( math.isnan( math.sinh( 1551 | math.atan2( math.factorial( math.ldexp( math.sqrt( 1552 | math.atanh( math.floor( math.lgamma( math.tan( 1553 | math.ceil( math.fmod( math.log( math.tanh( 1554 | math.copysign( math.frexp( math.log10( math.tau 1555 | math.cos( math.fsum( math.log1p( math.trunc( 1556 | math.cosh( math.gamma( math.log2( 1557 | math.degrees( math.gcd( math.modf( 1558 | math.e math.hypot( math.nan 1559 | >>> math.floor(4.5) 1560 | 4 1561 | >>> help(math.floor) 1562 | 1563 | >>> help(math) 1564 | 1565 | >>> 1566 | >>> from math import * 1567 | >>> floor(5) 1568 | 5 1569 | >>> gcd(34,56) 1570 | 2 1571 | >>> from math import gcd 1572 | >>> gcd(56,68) 1573 | 4 1574 | >>> os.system('clear') 1575 | 1576 | 1577 | 1578 | 1579 | 1580 | 0 1581 | >>> numbers = [1,4,6,3,4] 1582 | >>> for number in numbers: 1583 | ... print(number) 1584 | ... 1585 | 1 1586 | 4 1587 | 6 1588 | 3 1589 | 4 1590 | >>> for index,number in enumerate(numbers): 1591 | ... print(f'{index} - {number}') 1592 | ... 1593 | 0 - 1 1594 | 1 - 4 1595 | 2 - 6 1596 | 3 - 3 1597 | 4 - 4 1598 | >>> values = list('aeiou') 1599 | >>> values 1600 | ['a', 'e', 'i', 'o', 'u'] 1601 | >>> for index, vowel in enumerate(values): 1602 | ... printf(f'{index} - {vowel}') 1603 | ... 1604 | Traceback (most recent call last): 1605 | File "", line 2, in 1606 | NameError: name 'printf' is not defined 1607 | >>> for index, vowel in enumerate(values): 1608 | ... print(f'{index} - {vowel}') 1609 | ... 1610 | 0 - a 1611 | 1 - e 1612 | 2 - i 1613 | 3 - o 1614 | 4 - u 1615 | >>> import os 1616 | >>> os.system('clear') 1617 | 1618 | 0 1619 | >>> number = 5 1620 | >>> if(number%2==0): 1621 | ... isEven = True 1622 | ... else: 1623 | ... isEven = False 1624 | ... 1625 | >>> isEven = True if number%2==0 else False 1626 | >>> isEven 1627 | False 1628 | >>> number = 6 1629 | >>> isEven = True if number%2==0 else False 1630 | >>> isEven 1631 | True 1632 | >>> isEven = number%2==0 1633 | >>> isEven = "Yes" if number%2==0 else "No" 1634 | >>> isEven 1635 | 'Yes' 1636 | >>> os.system('clear') 1637 | 1638 | 1639 | 1640 | 0 1641 | >>> a = 1 1642 | >>> len(1) 1643 | Traceback (most recent call last): 1644 | File "", line 1, in 1645 | TypeError: object of type 'int' has no len() 1646 | >>> type(a) 1647 | 1648 | >>> str = "Value" 1649 | >>> str.upper() 1650 | 'VALUE' 1651 | >>> a.upper() 1652 | Traceback (most recent call last): 1653 | File "", line 1, in 1654 | AttributeError: 'int' object has no attribute 'upper' 1655 | >>> type(1) 1656 | 1657 | >>> type(1.5) 1658 | 1659 | >>> type("1.5") 1660 | 1661 | >>> type(True) 1662 | 1663 | >>> type(str) 1664 | 1665 | >>> str = 1 1666 | >>> type(str) 1667 | 1668 | >>> str = True 1669 | >>> type(str) 1670 | 1671 | >>> str = [1,2] 1672 | >>> type(str) 1673 | 1674 | >>> os.system('clear') 1675 | 1676 | 0 1677 | >>> def create_ranga(): 1678 | ... return 'Ranga',1981,'India' 1679 | ... 1680 | >>> ranga = create_ranga() 1681 | >>> type(ranga) 1682 | 1683 | >>> name, year, country = ranga 1684 | >>> ranga 1685 | ('Ranga', 1981, 'India') 1686 | >>> name 1687 | 'Ranga' 1688 | >>> year 1689 | 1981 1690 | >>> country 1691 | 'India' 1692 | >>> len(ranga) 1693 | 3 1694 | >>> ranga[0] 1695 | 'Ranga' 1696 | >>> ranga[1] 1697 | 1981 1698 | >>> ranga[2] 1699 | 'India' 1700 | >>> ranga[1] = 1991 1701 | Traceback (most recent call last): 1702 | File "", line 1, in 1703 | TypeError: 'tuple' object does not support item assignment 1704 | >>> person = ('Ranga', 5, 'India') 1705 | >>> person = 'Ranga', 5, 'India' 1706 | >>> type(person) 1707 | 1708 | >>> name, age, country = person 1709 | >>> name, age = person 1710 | Traceback (most recent call last): 1711 | File "", line 1, in 1712 | ValueError: too many values to unpack (expected 2) 1713 | >>> x = 0 1714 | >>> y = 1 1715 | >>> x, y = 0, 1 1716 | >>> x, y = y, x 1717 | >>> x 1718 | 1 1719 | >>> y 1720 | 0 1721 | >>> x = (0) 1722 | >>> type(x) 1723 | 1724 | >>> x = (0,) 1725 | >>> x = 1, 1726 | >>> type(x) 1727 | 1728 | >>> os.system('clear') 1729 | 1730 | 1731 | 1732 | 1733 | 1734 | 1735 | 1736 | 1737 | 1738 | 1739 | 0 1740 | >>> 1741 | 1742 | 1743 | 1744 | 1745 | 1746 | 1747 | 1748 | 1749 | 1750 | 1751 | 1752 | 1753 | >>> sum 1754 | 1755 | >>> sum([12,34,56]) 1756 | 102 1757 | >>> number1 = 10 1758 | >>> number2 = 20 1759 | >>> sum = number1 + number2 1760 | >>> sum 1761 | 30 1762 | >>> sum([12,34,56]) 1763 | Traceback (most recent call last): 1764 | File "", line 1, in 1765 | TypeError: 'int' object is not callable 1766 | >>> sum_ = number1 + number2 1767 | >>> del sum 1768 | >>> sum 1769 | 1770 | >>> sum([12,34,56]) 1771 | 102 1772 | >>> os.system('clear') 1773 | Traceback (most recent call last): 1774 | File "", line 1, in 1775 | NameError: name 'os' is not defined 1776 | >>> import os 1777 | >>> os.system('clear') 1778 | 1779 | 0 1780 | >>> None 1781 | >>> type(None) 1782 | 1783 | >>> def email(subject, content, to , cc , bcc): 1784 | ... print(f" {subject}, {content}, {to}, {cc}, " 1785 | ... ) 1786 | ... 1787 | >>> email("subject", "great work", in28minutes@gmail.com) 1788 | Traceback (most recent call last): 1789 | File "", line 1, in 1790 | NameError: name 'in28minutes' is not defined 1791 | >>> email("subject", "great work", "in28minutes@gmail.com") 1792 | Traceback (most recent call last): 1793 | File "", line 1, in 1794 | TypeError: email() missing 2 required positional arguments: 'cc' and 'bcc' 1795 | >>> def email(subject, content, to , cc=None , bcc=None): 1796 | ... print(f" {subject}, {content}, {to}, {cc}, {bcc}"); 1797 | ... 1798 | >>> email("subject", "great work", "in28minutes@gmail.com") 1799 | subject, great work, in28minutes@gmail.com, None, None 1800 | >>> email("subject", "great work", "in28minutes@gmail.com", None, None) 1801 | subject, great work, in28minutes@gmail.com, None, None 1802 | >>> email(None, "great work", "in28minutes@gmail.com", None, None) 1803 | None, great work, in28minutes@gmail.com, None, None 1804 | >>> var = "123" 1805 | >>> if var is None : print ("do something"); 1806 | ... 1807 | >>> var = None 1808 | >>> if var is None : print ("do something"); 1809 | ... 1810 | do something 1811 | >>> os.system('clear') 1812 | 1813 | 0 1814 | >>> class Student: pass 1815 | ... 1816 | >>> student1 = Student() 1817 | >>> student2 = Student() 1818 | >>> id(student1) 1819 | 4554811768 1820 | >>> id(student2) 1821 | 4554811992 1822 | >>> student1 is student2 1823 | False 1824 | >>> student3 = student1 1825 | >>> id(student3) 1826 | 4554811768 1827 | >>> student1 is student3 1828 | True 1829 | >>> student1 == student2 1830 | False 1831 | >>> student1 == student3 1832 | True 1833 | >>> class Student: 1834 | ... def __init__(self, id): 1835 | ... self.id = id 1836 | ... 1837 | >>> student1 = Student(1) 1838 | >>> student2 = Student(2) 1839 | >>> student3 = Student(1) 1840 | >>> student4 = student1 1841 | >>> id(student1) 1842 | 4554812160 1843 | >>> id(student4) 1844 | 4554812160 1845 | >>> student1 is student4 1846 | True 1847 | >>> student1 is student2 1848 | False 1849 | >>> student1 is student3 1850 | False 1851 | >>> student1 == student3 1852 | False 1853 | >>> class Student: 1854 | ... def __init__(self, id): 1855 | ... self.id = id 1856 | ... def __eq__(self, other): 1857 | ... return self.id == other.id 1858 | ... 1859 | >>> student1 = Student(1) 1860 | >>> student2 = Student(2) 1861 | >>> student3 = Student(1) 1862 | >>> student4 = student1 1863 | >>> student4 == student1 1864 | True 1865 | >>> student2 == student1 1866 | False 1867 | >>> student3 == student1 1868 | True 1869 | >>> os.system('clear') 1870 | 1871 | 0 1872 | >>> i=1 1873 | File "", line 1 1874 | i=1 1875 | ^ 1876 | IndentationError: unexpected indent 1877 | >>> i=3 1878 | File "", line 1 1879 | i=3 1880 | ^ 1881 | IndentationError: unexpected indent 1882 | >>> i=1 1883 | >>> if(i==3): 1884 | ... print('somethin') 1885 | File "", line 2 1886 | print('somethin') 1887 | ^ 1888 | IndentationError: expected an indented block 1889 | >>> if(i==3): 1890 | ... print('something') 1891 | ... print('') 1892 | File "", line 3 1893 | print('') 1894 | ^ 1895 | IndentationError: unindent does not match any outer indentation level 1896 | >>> os.system('clear') 1897 | 1898 | 0 1899 | >>> import this 1900 | The Zen of Python, by Tim Peters 1901 | 1902 | Beautiful is better than ugly. 1903 | Explicit is better than implicit. 1904 | Simple is better than complex. 1905 | Complex is better than complicated. 1906 | Flat is better than nested. 1907 | Sparse is better than dense. 1908 | Readability counts. 1909 | Special cases aren't special enough to break the rules. 1910 | Although practicality beats purity. 1911 | Errors should never pass silently. 1912 | Unless explicitly silenced. 1913 | In the face of ambiguity, refuse the temptation to guess. 1914 | There should be one-- and preferably only one --obvious way to do it. 1915 | Although that way may not be obvious at first unless you're Dutch. 1916 | Now is better than never. 1917 | Although never is often better than *right* now. 1918 | If the implementation is hard to explain, it's a bad idea. 1919 | If the implementation is easy to explain, it may be a good idea. 1920 | Namespaces are one honking great idea -- let's do more of those! 1921 | >>> 1922 | 1923 | >>> 1/0 1924 | Traceback (most recent call last): 1925 | File "", line 1, in 1926 | ZeroDivisionError: division by zero 1927 | >>> i = 0 1928 | >>> j = 10/i 1929 | Traceback (most recent call last): 1930 | File "", line 1, in 1931 | ZeroDivisionError: division by zero 1932 | >>> 2 + '2' 1933 | Traceback (most recent call last): 1934 | File "", line 1, in 1935 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 1936 | >>> values = [1,'2'] 1937 | >>> sum(values) 1938 | Traceback (most recent call last): 1939 | File "", line 1, in 1940 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 1941 | >>> value 1942 | Traceback (most recent call last): 1943 | File "", line 1, in 1944 | NameError: name 'value' is not defined 1945 | >>> values.non_existing 1946 | Traceback (most recent call last): 1947 | File "", line 1, in 1948 | AttributeError: 'list' object has no attribute 'non_existing' 1949 | >>> values.non_existing() 1950 | Traceback (most recent call last): 1951 | File "", line 1, in 1952 | AttributeError: 'list' object has no attribute 'non_existing' 1953 | >>> import builtins 1954 | >>> help(builtins) 1955 | 1956 | >>> help(builtins) 1957 | 1958 | >>> k = 10/non_existing_variable 1959 | Traceback (most recent call last): 1960 | File "", line 1, in 1961 | NameError: name 'non_existing_variable' is not defined 1962 | >>> 10/0 1963 | Traceback (most recent call last): 1964 | File "", line 1, in 1965 | ZeroDivisionError: division by zero 1966 | >>> values = [1,'1'] 1967 | File "", line 1 1968 | values = [1,'1'] 1969 | ^ 1970 | IndentationError: unexpected indent 1971 | >>> sum(values) 1972 | File "", line 1 1973 | sum(values) 1974 | ^ 1975 | IndentationError: unexpected indent 1976 | >>> values = [1,'1'] 1977 | >>> sum(values) 1978 | Traceback (most recent call last): 1979 | File "", line 1, in 1980 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 1981 | >>> import builtins 1982 | >>> help(builtins) 1983 | 1984 | >>> 1985 | -------------------------------------------------------------------------------- /python-code/tips/all_about_methods.py: -------------------------------------------------------------------------------- 1 | def example_method(mandatory_parameter, default_parameter="Default" 2 | , *args, **kwargs): 3 | print(f""" 4 | mandatory_parameter = {mandatory_parameter} {type(mandatory_parameter)} 5 | default_parameter = {default_parameter} {type(default_parameter)} 6 | args = {args} {type(args)} 7 | kwargs = {kwargs} {type(kwargs)} 8 | """) 9 | 10 | # example_method() #example_method() missing 1 required positional argument 11 | # example_method(mandatory_parameter=15) #example_method(15) 12 | # example_method(25,"Some String") 13 | # example_method(25,"String 1","String 2","String 3") 14 | # example_method(25,"String 1","String 2","String 3","String 4","String 5") 15 | # example_method(25,"String 1","String 2","String 3",key1='a', key2='b') 16 | #example_method(25,"String 1",key1='a', key2='b') 17 | # example_method(key1='a', key2='b',mandatory_parameter=25,default_parameter="String 1") 18 | # example_method(25,"String 1",key1='a', key2='b') 19 | example_list = [1,2,3,4,5,6] 20 | # example_method(*example_list) 21 | example_dict = {'a':'1', 'b':'2'} 22 | example_method(*example_list, **example_dict) -------------------------------------------------------------------------------- /python-code/tips/enum_examples.py: -------------------------------------------------------------------------------- 1 | # Currency - USD EUR INR 2 | from enum import Enum 3 | 4 | 5 | class Currency(Enum): 6 | USD = 1 7 | EUR = 2 8 | INR = 3 9 | 10 | # for currency in Currency: 11 | # print(currency) 12 | 13 | print(Currency(1)) 14 | 15 | print(Currency(1).name) 16 | print(Currency(1).value) 17 | 18 | 19 | # print(Currency.USD) 20 | # print(Currency.INR) -------------------------------------------------------------------------------- /python-code/tips/module_1.py: -------------------------------------------------------------------------------- 1 | def method_1(): 2 | print("method 1") 3 | 4 | class ClassA: 5 | def class_method_1(self): 6 | print("class_method_1 method 1") 7 | 8 | # print(__name__) 9 | 10 | if __name__ == '__main__': 11 | method_1() 12 | ClassA().class_method_1() -------------------------------------------------------------------------------- /python-code/tips/module_2.py: -------------------------------------------------------------------------------- 1 | import module_1 2 | 3 | module_1.method_1() 4 | module_1.ClassA().class_method_1() -------------------------------------------------------------------------------- /python-code/tips/switch_alternatives.py: -------------------------------------------------------------------------------- 1 | week_days = { 2 | 0 : 'Sunday', 3 | 1 : 'Monday', 4 | 2 : 'Tuesday' 5 | # You can fill rest of the stuff 6 | } 7 | 8 | print(week_days.get(7,'Invalid_day')) 9 | --------------------------------------------------------------------------------