0% found this document useful (0 votes)
44 views6 pages

Python Basics

This document discusses Python basics including variables, data types, strings, and conditional statements. It begins by explaining that variables allow programs to store and refer to different types of data like numbers, text, and more. Common data types in Python include numeric, string, boolean, list, tuple, dictionary, and set. The document then explores string operations such as concatenation, length, slicing, and methods. Finally, it covers conditional statements like if, if-else, and elif that allow programs to make decisions based on different conditions.

Uploaded by

Kacper Wojtowicz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
44 views6 pages

Python Basics

This document discusses Python basics including variables, data types, strings, and conditional statements. It begins by explaining that variables allow programs to store and refer to different types of data like numbers, text, and more. Common data types in Python include numeric, string, boolean, list, tuple, dictionary, and set. The document then explores string operations such as concatenation, length, slicing, and methods. Finally, it covers conditional statements like if, if-else, and elif that allow programs to make decisions based on different conditions.

Uploaded by

Kacper Wojtowicz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 6

Chapter 2

Python Basics

Variables
Let's talk about something super important in programming: variables. They're like little
containers that can hold different types of information. Think of them as sticky notes where
you can jot down important things and refer back to them whenever you need.

Creating a variable is easy peasy. You just give it a name and assign a value to it. For
example, let's say you want to remember your age. You can create a variable called "age" and
assign your actual age to it:

age = 25

Now, whenever you want to refer to your age in your program, you can just use the variable
"age" instead of typing the number over and over again.

The cool thing is that variables can hold different types of data. Besides numbers, you can
also store text in a variable. Let's say you want to store your name. You can create a variable
called "name" and assign your name to it:

name = "John"

See how we used quotes this time? That's because we're dealing with text, and in Python, we
use quotes to indicate that something is a piece of text, also known as a string.

Now, imagine your age changes (hello, time traveler!). No worries! You can simply update
the value of the "age" variable like this:

age = 30

Ta-da! Your variable now holds the new value. Easy as pie!

So, why bother with variables? Well, they make your code easier to read and understand.
Instead of using random numbers or text all over the place, you can give them meaningful
names. It's like having sticky notes that tell you exactly what each piece of information
represents. So, remember, variables are your friends in programming. They help you store and
manage different types of information, making your code more organized and readable.

Common Data Types in Python

Let's dive into some common data types in Python. They're like different flavors of ice cream
that you can use to store and work with different kinds of information. Exciting, right? So,
let's explore some of these data types together!
 Numeric Data Types: These are like numbers in real life. We have a few different types
in Python:
o Integers: These are whole numbers without any decimal points. For example, 5
and -2 are integers.
o Floating-Point Numbers: These are numbers with decimal points. For example,
3.14 and -0.5 are floating-point numbers.
o Complex Numbers: These are numbers with a real part and an imaginary part.
Don't worry if you're not familiar with them just yet. We won't go too deep into
complex numbers for now.
 Strings: Ah, strings! They're like a collection of characters put together. You can think of
them as words, sentences, or even entire stories. To create a string, you simply enclose
some text in quotes. For example:

name = "Alice"

In this case, we created a string variable called "name" and assigned it the value "Alice".

 Booleans: These are like little truth detectives. They can have one of two values: True or
False. Booleans are often used for making decisions and performing logical operations.
For example:

is_sunny = True

Here, we created a boolean variable called "is_sunny" and set it to True. It's like saying, "Yes,
it's sunny today!"

 Lists: Imagine having a grocery list or a playlist. Lists are like ordered collections of
items. You can put different values inside a list, and they can be of different types. For
example:

fruits = ["apple", "banana", "orange"]

In this case, we created a list called "fruits" with three elements: "apple", "banana", and
"orange".

 Tuples: Tuples are quite similar to lists, but with one key difference: they're immutable.
Once you create a tuple, you can't change its elements. They're like snapshots of
information that stay the same. For example:

coordinates = (10, 20)

Here, we created a tuple called "coordinates" with two elements: 10 and 20.

 Dictionaries: Dictionaries are like real-life dictionaries, where you can look up a word to
find its definition. In Python, dictionaries hold key-value pairs. You use a key to look up
its corresponding value. For example:

person = {"name": "Alice", "age": 25}


In this case, we created a dictionary called "person" with two key-value pairs: "name" and
"age".

 Sets: Sets are like a unique collection of items. They don't allow duplicates, and their
order doesn't matter. They can be handy when you want to keep track of unique elements.
For example:

unique_numbers = {1, 2, 3, 4, 5}

Here, we created a set called "unique_numbers" with five unique elements.

By understanding these common data types, you'll have a solid foundation for working with
different kinds of information in Python. It's like having a toolbox full of useful tools to tackle
various programming challenges. So, let's keep exploring and learning together!

Playing with Strings


Let's have some fun playing with strings in Python. Strings are like a playground for text
manipulation and exploration. So, put on your coding hat, and let's dive into the exciting
world of string operations!

 String Concatenation: Imagine you have two strings and you want to combine them
together. Well, you can do that with a process called concatenation. It's like joining two
pieces of a puzzle. Take a look at this example:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name

In this case, we created two string variables called "first_name" and "last_name". By using the
"+" operator, we can concatenate them with a space in between to form the "full_name"
string.

 String Length: Have you ever wondered how long a string is? Python has a nifty function
called "len()" that can give you the length of a string. Check out this example:

message = "Hello, World!"


length = len(message)

Here, we created a string variable called "message". By using the "len()" function, we can
find out the length of the string and store it in the "length" variable.

 String Slicing: Sometimes, you may want to extract a portion of a string. That's where
string slicing comes in handy. It's like cutting a delicious pizza into smaller, bite-sized
pieces. Take a look at this example:

message = "Hello, World!"


sliced_message = message[7:12]
In this case, we have a string variable called "message". By using the square brackets
and specifying the start and end indices, we can extract a slice of the string. The
"sliced_message" variable will hold the value "World".

 String Methods: Python provides a variety of built-in methods that you can use to
manipulate and transform strings. These methods are like magical spells that can perform
specific tasks. Let's explore a couple of examples:

 Upper and Lower Case: You can convert a string to uppercase or lowercase using the
"upper()" and "lower()" methods, respectively. Check it out:

message = "Hello, World!"


upper_message = message.upper()
lower_message = message.lower()

In this example, the "upper()" method converts the string to uppercase, while the "lower()"
method converts it to lowercase.

 Replacing Substrings: You can replace specific substrings within a string using the
"replace()" method. It's like having a magic wand to change words. Take a look:

message = "Hello, World!"


new_message = message.replace("Hello", "Hi")

In this case, the "replace()" method replaces the word "Hello" with "Hi" in the string,
resulting in the "new_message" variable holding the value "Hi, World!".

With these string operations at your disposal, you can have a blast manipulating and exploring
text in your Python programs. So, grab your favorite string and start experimenting!

Making Decisions with Conditional Statements

Sometimes in programming, you need to make decisions based on certain conditions. That's
where conditional statements come into play. They allow your program to choose different
paths and perform specific actions based on those choices. Let's explore conditional
statements together!

1. if Statement: The "if" statement is like a gatekeeper. It checks if a condition is true,


and if it is, it executes a block of code. Here's an example:

age = 16
if age >= 18:
print("You're old enough to vote!")

In this case, we check if the "age" variable is greater than or equal to 18. If it is, the
message "You're old enough to vote!" is printed.
2. if-else Statement: Sometimes, you need to provide an alternative action when the
condition is not met. That's where the "if-else" statement comes in. Check out this
example:

age = 16
if age >= 18:
print("You're old enough to vote!")
else:
print("Sorry, you're too young to vote.")

Here, if the condition is true (age is greater than or equal to 18), the first block of code
executes. Otherwise, the second block of code executes.

3. elif Statement: What if you have multiple conditions to check? The "elif" statement is
your friend. It allows you to add additional conditions to the decision-making process.
Take a look:

python
3. age = 16
4. if age < 18:
5. print("Sorry, you're too young to vote.")
6. elif age == 18:
7. print("Congratulations! You're old enough to vote for the first
time!")
8. else:
9. print("You're experienced in voting.")

10. In this case, if the age is less than 18, the first block of code executes. If the age is
exactly 18, the second block of code executes. Otherwise, the third block of code
executes.

Conditional statements are powerful tools that allow your program to adapt and make
decisions based on specific conditions. With these statements in your programming toolbox,
you can create dynamic and responsive programs. So, embrace the power of decisions and let
your code choose its own path!

Loops: Repeating Actions with While


Get ready to dive into the fascinating world of loops. They're like magical tools that allow
your code to repeat actions over and over again. It's a bit like a never-ending dance, but in a
totally awesome way!

Remember what Einstein once said: "Insanity is doing the same thing over and over again and
expecting different results." Well, in programming, we're not insane—we're smart! We use
loops to perform repetitive tasks without driving ourselves crazy. How cool is that?

Now, let's get to know one of our loop buddies called while. It's a loop that keeps going as
long as a certain condition remains true. Check out the super simple syntax:

arduino
while condition:
# code to be repeated

Here's how it works: before each loop iteration, the condition is checked. If it's true, the code
inside the loop is executed. Then, the loop goes back and checks the condition again. It
continues until the condition finally becomes false.

To see it in action, let's try a fun example together:

python
count = 0
while count < 5:
print("Hello, friend!")
count += 1

In this case, we start with count = 0, and our loop will repeat the code inside it as long as
count is less than 5. So, we get to see "Hello, friend!" printed five times. Feel the power of
repetition!

Just remember, my friend, when using loops, it's important to have a condition that can
eventually become false. Otherwise, we might end up in an infinite loop, and that's not what
we want!

Now that you've dipped your toes into the world of while loops, get ready for more exciting
loop adventures up ahead. Let's keep dancing to the beat of repetition and explore what's next!

You might also like