MENU

Python Basic _ Variable & Examples 70


Variable
  

You can learn and practice Python variables through various basic examples.

目次

Variable and Data Types

Variable
  • Variable are storage containers for holding values.
  • Variable are identified by names, and you can assign values to them.
  • Variable names can consist of letters, numbers, and underscores ( _ ), but they cannot start with a number.
Data Types
  1. Integer (int) : Represents integer data.
     Example : 3 42
  2. Float (float) : Represents numbers with a decimal point.
     Example : 3.14 0.5
  3. String (string) : Represents text data.
     Example : ‘Hello’, “Python”
  4. List (list) : A data type for storing multiple items in an ordered sequence.
     Example : [1, 2, 3], [‘apple’, ‘banana’, ‘strawberry’]
  5. Tuple (tuple) : Similar to a list but is an immutable data type.
     Example : (1, 2, 3)
  6. Dictionary (dictionary) : Stores data in key-value pairs.
     Example : {‘name’ : ‘John’, ‘age’ : 25}
  7. Boolean (boolean) : Contains only True or False values and is primarily used in conditional expressions.

Variable Declaration and Assignment

Variable Declaration

It is the process of defining a variable and specifying the name to be used.
For example, to declare a variable called my_variable, you would write it as follows.


my_variable = None # You can assign an initial value, or assign a value later
  

None meaning “empty”
Functions that do not have a return value, such as the print function, return None.

Variable Assignment

Storing a value in a variable. After declaring a variable, you assign a value to it. For example, to assign the integer 42 to my_variable, you would write it as follows


my_variable = 42
  

Examples

Integer Variable(10)

Click to see the results ^^|

1 Integer variable

number = 10
print(number)

10

2 Integer variable

number1 = 42
print(number1)

42

3 Integer variable

number2 = 123
print(number2)

123

4 negative integer variable

negative_number = -5
print(negative_number)

-5

5 large integer variable

big_number = 1000000
print(big_number)

1000000

6 Adding two integers

sum_of_numbers = 42 + 123
print(“Sum :”, sum_of_numbers)

Sum : 165

7 Integer variables and mathematical operations

result = 42 * 2 + 123
print(“Result :”, result)

Result : 207

8 Integer variables and squaring operation

square = 42 ** 2
print(“Square :”, square)

Square : 1764

9 Integer variable and division operation

division = 42 / 5
print ( “Division result :”, division)

Division result : 8.4

10 Declaration of two integer variables and performing division

number1 = 120
number2 = 40
division_result = number1 / number2
print (“The result of dividing {} by {} is {}”.format(number1, number2, division_result))

The result of dividing 120 by 40 is 3.0

Floating-Point Variable(5)

Click to see the results〜 ^^|

1 floating-point variable

x = 3.14
print (“Value : {} ” .format(x))

Value : 3.14

2 Approximation of Pi

pi_approximation = 21/7
print( f “Approximation of Pi : {pi_approximation} ” )

Approximation of Pi : 3.0

3 Temperature (Celsius)

temperature_celsius = 25.5
print( f “Temperature (Celsius) : {temperature_celsius}°C ” )

Temperature (Celsius) : 25.5°C

4 Exchange Rate

exchange_rate = 1.20
print( f “Exchange Rate : {exchange_rate} USD/EUR” )

Exchange Rate : 1.2 USD/EUR

5 Average Score

average_score = 87.5
print( f “Average Score : {average_score}” )

Average Score: 87.5

String Variable (10)

Click to see the results〜 ^^|

1 String variable

text = “Hello, World!”
print(text)

Hello, World!

2 String variables

name = “Tom”
greeting = “Hello, ” + name + “!”
print(greeting)

Hello, Tom!

3 Using triple quotes

message = “””This is a
multi-line
message.”””
print(message)

This is a
multi-line
message.

4 Using special characters

special_chars = “This is a newline\nand a tab \t in the string.”
print(special_chars)

This is a newline
and a tab in the string.

5 String concatenation

department = “Development”
position = “Engineer”
invitation = “You are invited as a ” + position + ” in the ” + department + ” department.”
print(invitation)

You are invited as a Engineer in the Development department.

6 String Formatting

name = “Tom”
age = 30
greeting = “{}, your age is {} years.”.format(name, age)
print(greeting)

Tom, your age is 30 years.

7 String Slicing

original_string = “Python programming”
substring = original_string[6:12]
print(substring)

progr

8 String Methods

text = “Python is a fun language.”
uppercase = text.upper()
lowercase = text.lower()
print(“Uppercase: {} \nLowercase: {}”.format(uppercase, lowercase))

Uppercase: PYTHON IS A FUN LANGUAGE.
Lowercase: python is a fun language.

9 Special Characters and Escaping

sentence = “This is \”Python\” example.”
print(sentence)

This is “Python” example.

10 String Concatenation and Splitting

part1 = “Hello”
part2 = “World”
concatenation = part1 + ” ” + part2
splitting = concatenation.split()
print(concatenation)
print(splitting)

Hello World
[‘Hello’, ‘World’]

List Variable (15)

Click to see the results〜 ^^|

1 Numeric List

number_list = [1, 2, 3, 4, 5]
print(number_list)

[1, 2, 3, 4, 5]

2 String List

fruit_list = [“apple”, “banana”, “orange”]
print(fruit_list)

[‘apple’, ‘banana’, ‘orange’]

3 Accessing List Elements

alphabet = [“A”, “B”, “C”, “D”, “E”]
element = alphabet[2]
print( f “The 3rd alphabet : {element}” )

The 3rd alphabet : C

4 Modifying and Adding to a List

number_list = [1, 2, 3, 4, 5]
number_list[2] = 6
number_list.append(7)
print(number_list)

[1, 2, 6, 4, 5, 7]

5 List Concatenation and Slicing

list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated = list1 + list2
sliced = concatenated[1:4]
print(concatenated)
print(sliced)

[1, 2, 3, 4, 5, 6]
[2, 3, 4]

6 List Comprehension

even_list = [x for x in range(10) if x % 2 == 0]
print(even_list)

[0, 2, 4, 6, 8]

7 2D List

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix)

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

8 Removing List Elements

color_list = [“red”, “green”, “blue”]
color_to_remove = “green”
color_list.remove(color_to_remove)
print(color_list)

[‘red’, ‘blue’]

9 Sorting a List

number_list = [5, 1, 3, 2, 4]
number_list.sort()
print(number_list)

[1, 2, 3, 4, 5]

10 List Concatenation and Extension

existing_list = [1, 2, 3]
new_list = [4, 5, 6]
existing_list.extend(new_list)
print(existing_list)

[1, 2, 3, 4, 5, 6]

11 Sum of a Numeric List

number_list = [1, 2, 3, 4, 5]
total = sum(number_list)
print(“Total: {}”.format(total))

Total: 15

12 Sum of Floating-Point Numbers in a List

float_list = [1.1, 2.2, 3.3, 4.4, 5.5]
total = sum(float_list)
print(“Total: {}”.format(total))

Total: 16.5

13 Length of a List of Strings

string_list = [“apple”, “banana”, “orange”]
length = len(string_list)
print(f”Length of the list: {length}”)

Length of the list: 3

14 Sum of a 2D List

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = sum(sum(row) for row in matrix)
print(f”Total: {total}”)

Total: 45

15 Sum of String Lengths in a List

string_list = [“apple”, “banana”, “orange”]
total_length = sum(len(word) for word in string_list)
print(f”Total length of strings: {total_length}”)

Total length of strings: 17

Tuple Variable (10)

Click to see the results〜 ^^|

1 Numeric Tuple

number_tuple = (1, 2, 3, 4, 5)
print(number_tuple)

(1, 2, 3, 4, 5)

2 String Tuple

fruit_tuple = (“apple”, “banana”, “orange”)
print(fruit_tuple)

(‘apple’, ‘banana’, ‘orange’)

3 Accessing Tuple Elements

alphabet = (“A”, “B”, “C”, “D”, “E”)
element = alphabet[2]
print( f “3rd alphabet : {element}” )

3rd alphabet : C

4 Immutable Nature of Tuples

color_tuple = (“red”, “green”, “blue”)
color_tuple[1] = “yellow” # Error – Tuples are immutable
print(color_tuple)

—————————————————————————
TypeError Traceback (most recent call last)
Cell In[33], line 2
1 color_tuple = (“red”, “green”, “blue”)
—-> 2 color_tuple[1] = “yellow” # Error – Tuples are immutable
3 print(color_tuple)

TypeError: ‘tuple’ object does not support item assignment

5 Concatenating Tuples

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated = tuple1 + tuple2
print(concatenated)

(1, 2, 3, 4, 5, 6)

6 Tuple of Tuples

subtuple1 = (1, 2)
subtuple2 = (3, 4)
parent_tuple = (subtuple1, subtuple2)
print(parent_tuple)

((1, 2), (3, 4))

7 Indexing and Slicing of Tuples

number_tuple = (1, 2, 3, 4, 5)
first_element = number_tuple[0]
last_two_elements = number_tuple[-2:]
print(f”First element: {first_element}”)
print(f”Last two elements: {last_two_elements}”)

First element: 1
Last two elements: (4, 5)

8 Unpacking Tuples

tuple = (“John”, “Doe”, 30)
first_name, last_name, age = tuple
print( f “First name : {first_name}, Last name : {last_name}, Age : {age}” )

First name : John, Last name : Doe, Age : 30

9 Using Tuples as Dictionary Keys

points = {(10, 20): “A”, (30, 40): “B”}
key = (10, 20)
value = points[key]
print( f “Value associated with key {key} : {value}” )

Value associated with key (10, 20) : A

10 Iterating Over a Tuple

fruit_tuple = (“apple”, “banana”, “orange”)
for fruit in fruit_tuple:
print(fruit)

apple
banana
orange

Dictionary Variable(10)

Click to see the results〜 ^^|

1 Dictionary Declaration

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
print(fruit_dictionary)

{‘apple’: 100, ‘banana’: 50, ‘orange’: 80}

2 Accessing Values Using Keys

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
value = fruit_dictionary[“banana”]
print(f”Price of a banana: {value} yen”)

Price of a banana: 50 yen

3 Adding Elements to a Dictionary

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
fruit_dictionary[“strawberry”] = 120
print(fruit_dictionary)

{‘apple’: 100, ‘banana’: 50, ‘orange’: 80, ‘strawberry’: 120}

4 Checking Key Existence

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
key = “kiwi”
exists = key in fruit_dictionary
print( f “Does {key} exist in the dictionary? {exists}” )

Does kiwi exist in the dictionary? False

5 Iterating Over a Dictionary

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
for key, value in fruit_dictionary.items():
print( f “{key} : {value} dollar” )

apple: 100 yen
banana: 50 yen
orange: 80 yen

6 Removing Elements from a Dictionary

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
del fruit_dictionary[“banana”]
print(fruit_dictionary)

{‘apple’: 100, ‘orange’: 80}

7 Separating Dictionary Keys and Values

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
key_list = list(fruit_dictionary.keys())
value_list = list(fruit_dictionary.values())
print(f”Key list: {key_list}”)
print(f”Value list: {value_list}”)

Key list: [‘apple’, ‘banana’, ‘orange’]
Value list: [100, 50, 80]

8 Nested Dictionaries

student_dictionary = {
  ”John”: {“Math”: 90, “Science”: 85},
  ”Alice”: {“Math”: 88, “Science”: 92}
}
print(student_dictionary)

{‘John’: {‘Math’: 90, ‘Science’: 85}, ‘Alice’: {‘Math’: 88, ‘Science’: 92}}

9 Updating Dictionary Elements

fruit_dictionary = {“apple”: 100, “banana”: 50, “orange”: 80}
fruit_dictionary[“apple”] = 120   # Update the price of apples
print(fruit_dictionary)

{‘apple’: 120, ‘banana’: 50, ‘orange’: 80}

10 Looping Through Dictionary Keys

student_dictionary = {
  ”John”: 85,
  ”Alice”: 92,
  ”Bob”: 78
}
for student in student_dictionary:
print(f”Grade of {student}: {student_dictionary[student]}”)

Grade of John: 85
Grade of Alice: 92
Grade of Bob: 78

Boolean Variable(10)

Click to see the results〜 ^^|

1 Declaring Boolean Values

true = True
false = False
print(true)
print(false)

True
False

2 Using Comparison Operators

number1 = 10
number2 = 5
comparison = number1 > number2
print(comparison)

True

3 Using Conditional Statements

age = 18
is_minor = age < 20
print(is_minor)

True

4 Result of Boolean Operations

A = True
B = False
logical_or = A or B
logical_and = A and B
print(f”Logical OR: {logical_or}, Logical AND: {logical_and}”)

Logical OR: True, Logical AND: False

5 Obtaining Boolean Values Using Conditional Expressions

number = 15
is_even_or_odd = number % 2 == 0
print(is_even_or_odd)

False

6 Using Complex Conditional Expressions

age = 25
has_license = True
is_eligible_to_vote = age >= 18 and has_license
print(is_eligible_to_vote)

True

7 Understanding Boolean Operations and Precedence

A = True
B = False
C = True
complex_condition = A and B or C
print(complex_condition)

True

8 Comparing with None (Null Value)

value = None
is_value_present = value is not None
print(is_value_present)

False

9 Inverting Boolean Values

truth = False
inverted = not truth
print(inverted)

True

10 Controlling Flow Using Boolean Values

logged_in = True
if logged_in:
print(“Welcome!”)
else:
print(“Please log in”)

Welcome!

  • URLをコピーしました!
目次