Ch2 Variables
Chapter 2: Understanding Variables in Python¶
Welcome to Chapter 2 of our Python programming course! In this chapter, we'll delve into one of the foundational concepts of programming in Python: variables
.
Understanding variables is crucial as they are the basic units for storing data in any programming language.
In Python, variables are even more interesting due to the language's dynamic nature.
Python is often described as a weakly typed
or dynamically typed
language. This means two things in practice:
- You don't need to declare variables before using them. You simply create them when you assign a value to them.
- The type of a variable can change over time, as you assign new values of different types to the same variable.
This flexibility makes Python an extremely user-friendly language, especially for beginners. However, it's essential to understand how to use this flexibility to your advantage while writing clear and error-free code.
In this chapter, we will cover:
- How to use comments to make your code more readable.
- The basics of variables in Python, including naming conventions and assignment.
- Different types of variables available in Python, such as
integers
,strings
,floats
, and more complex types likelists
,tuples
,sets
,dictionaries
, andbytes
. - How to work with each type of variable, including operations you can perform on them.
0. The naming rule for variables¶
- It could contain numbers, letters, underline. but not start with numbers.
- Could not contain space
- Could not be reserved characters of python, such as
False
1. Comments in Python¶
Comments are not executed by the Python interpreter. They are meant for programmers to leave notes, explanations, or comments within the code for human readers. Comments are crucial for maintaining code, especially when working in teams or when you return to your own code after some time.
1.1 Single-line Comments¶
Single-line comments start with a #
symbol. Anything following the # on that line is considered a comment and is ignored by Python.
# This is a single-line comment
print("Hello, World!") # This is a comment following a statement
Hello, World!
1.2 Multi-line Comments¶
For comments that extend over multiple lines, you can either use the # symbol at the beginning of each line or use triple quotes ('''
or """
). Although not technically a comment, triple quotes are often used as multi-line comments in Python.
'''
This is a multi-line comment
spanning multiple lines
'''
# This is another way to
# write multi-line comments
'\nThis is a multi-line comment\nspanning multiple lines\n'
a = 5
a,type(a)
(5, int)
a = 'Hello,Charlie'
a,type(a)
('Hello,Charlie', str)
2.2 Use print()
to print the output¶
user_name = 'Charlie'
user_age = 8
print("Reader name:",user_name, "Age:",user_age)
Reader name: Charlie Age: 8
print(f"Reader name: {user_name}, Age:{user_age}")
Reader name: Charlie, Age:8
Using the given characters as the delimiter
print("Reader name",user_name, "Age",user_age,sep= ' : ')
Reader name : Charlie : Age : 8
Setting the end
parameter
print(40,'\t',end = '')
print(50,'\t',end = '')
40 50
2.3 Print the output into a file¶
with open("poem.txt","w") as f:
print('In the end she just wanted the house',file = f)
print('and a horse not much more what',file = f)
print('if he didn’t own the house or worse',file = f)
print('not even a horse how do we',file = f)
with open("poem.txt", "r") as file:
content = file.read()
content
'In the end she just wanted the house\nand a horse not much more what\nif \u200ahe didn’t own the house or worse\nnot even a horse how do we\n'
3. Numeric Type¶
Python supports various numeric types, including integers (int), floating-point numbers (float), and complex numbers (complex)
3.1 int type¶
The int
type variables in python have four forms
- Decimal Number
Binary
Number: Start with '0b' or '0B'Octal
Number: Start with '0o' or '0O'Hex
Number: Start with '0x' or '0X', and usea~f
to represent10-15
a = 56
print(a)
# set a as a very large number
a = 9999999999999999999999
print(a)
print(type(a))
56 9999999999999999999999 <class 'int'>
hex_value1 = 0x13
bin_val = 0b111
oct_val = 0o54
print('Binary Number:',bin_val)
print('Hex Number:',hex_value1)
print('Octal Number:',oct_val)
Binary Number: 7 Hex Number: 19 Octal Number: 44
In Python, the underscore _
used within a number is a digit separator that has been available since Python 3.6.
It allows for better readability of large numbers by grouping digits in a way similar to how some cultures use commas, periods, or spaces.
one_million = 1_000_000
print(one_million)
1000000
3.1 Float type¶
Floating-point numbers (float
) represent real numbers and can include a decimal point.
af1 = 5.234556
print(af1)
af2 = 25.2345
print(af2)
print(type(af2))
5.234556 25.2345 <class 'float'>
f1 = 5.12e2
f2 = 5e3
print('f1:',f1,'Type:',type(f1))
print('f2:',f2,'Type:',type(f2))
f1: 512.0 Type: <class 'float'> f2: 5000.0 Type: <class 'float'>
4. String Type and Operations¶
Strings in Python are created by enclosing characters in quotes. You can use either single quotes ('
) or double quotes ("
), depending on what suits your needs. Once you have created a string, there are several basic operations you can perform on it, such as concatenation
, repetition
, and more.
4.1 Creating Strings¶
To create a string, simply enclose your text in single or double quotes. Python treats both equally, allowing you to choose based on convenience and readability.
# Single quotes
single_quoted_string = 'Hello, Python!'
# Double quotes
double_quoted_string = "Hello, Python!"
If you type 2 strings close with each other, python would merge them automatically
s1 = "Hello," 'Charlie'
print(s1)
Hello,Charlie
4.2 Concatenation¶
You can join two or more strings into one using the +
operator. This operation is known as concatenation.
# Concatenating two strings
greeting = "Hello, "
name = "Python!"
welcome_message = greeting + name
print(welcome_message) # Output: Hello, Python!
Hello, Python!
4.3 Repetition¶
Strings can be repeated a specified number of times using the *
operator, providing a simple way to repeat a string.
# Repeating a string
laugh = "Ha"
laughing = laugh * 3
print(laughing) # Output: HaHaHa
HaHaHa
4.4 Escape character¶
The escape character allows you to use characters that are otherwise impossible to put into a string, such as a newline
, tab
, or even the backslash
itself.
\n
: Inserts a newline in the text at this point.\t
: Inserts a tab in the text at this point.\\
: Inserts a backslash (\
) in the text at this point.\"
: Inserts a double quote character in the text at this point, which is particularly useful in strings that are surrounded by double quotes.\'
: Inserts a single quote character in the text at this point, which is useful in strings that are surrounded by single quotes.
print("Hello\nWorld!") # This will print "Hello" and "World!" on two separate lines.
print("This is a tab\texample.") # This will include a tab space between "a" and "tab".
print("This is a double quote \" symbol inside a string.") # This will include a double quote in the string.
print('This is a single quote \' symbol inside a string.') # This will include a single quote in the string.
print("This is a backslash \\ symbol inside a string.") # This will include a backslash in the string.
Hello World! This is a tab example. This is a double quote " symbol inside a string. This is a single quote ' symbol inside a string. This is a backslash \ symbol inside a string.
4.5 Type cast from numeric to string¶
Python does not allow us to combine numeric type with strings, for doing that, we should use repr()
or str()
to transfer numeric to string.
s1 = 'The price of this book is:'
p = 99.8
# Could not work
print(s1 + p)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[13], line 4 2 p = 99.8 3 # Could not work ----> 4 print(s1 + p) TypeError: can only concatenate str (not "float") to str
In the next sections, we will delve into more complex operations and techniques to manipulate strings, enhancing your ability to handle text data effectively in Python.
print(s1 + str(p))
The price of this book is:99.8
print(s1 + repr(p))
The price of this book is:99.8
repr
would also transfer strings to a expression
st = 'I love python'
print(st)
print(repr(st))
I love python 'I love python'
4.6 Raw String¶
Raw string start with r
, within this string, \
could not be treated as escape characters
.
raw_string = r"This is a raw string, so \n and \t won't be interpreted as escape characters."
print(raw_string)
This is a raw string, so \n and \t won't be interpreted as escape characters.
Raw strings are particularly useful when dealing with regular expressions
, file paths
, URLs
, and other scenarios where backslashes frequently occur and are intended to be interpreted literally:
# Using a raw string for a Windows file path
file_path = r"C:\Users\Username\Documents\File.txt"
print(file_path)
C:\Users\Username\Documents\File.txt