Python căn bản (4): Variables (cont)

  Bài trước: Python căn bản (3): Variables

-----

[Từ điển]

4. Python Variables (cont)

4.1 Assign Multiple Values

Many Values to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example

x, y, z = "Orange", "Banana", "Cherry"

print(x)

print(y)

print(z)

Note: Make sure the number of variables matches the number of values, or else you will get an error.

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

Example

x = y = z = "Orange"

print(x)

print(y)

print(z)

Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking.

Example

Unpack a list:

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

x, y, z = fruits

print(x)

print(y)

print(z)

4.2 Output Variables

The Python print() function is often used to output variables.

Example

x = "Python is awesome"

print(x)

In the print() function, you output multiple variables, separated by a comma:

Example

x = "Python"

y = "is"

z = "awesome"

print(x, y, z)

You can also use the + operator to output multiple variables:

Example

x = "Python "

y = "is "

z = "awesome"

print(x + y + z)

Notice the space character after "Python " and "is ", without them the result would be "Pythonisawesome".

For numbers, the + character works as a mathematical operator:

Example

x = 5

y = 10

print(x + y)

In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error:

Example

x = 5

y = "John"

print(x + y)

The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types:

Example

x = 5

y = "John"

print(x, y)

4.3 Global Variables

Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example

Create a variable outside of a function, and use it inside the function

x = "awesome"

 

def myfunc():

  print("Python is " + x)

 

myfunc()

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Example

Create a variable inside a function, with the same name as the global variable

x = "awesome"

 

def myfunc():

  x = "fantastic"

  print("Python is " + x)

 

myfunc()

 

print("Python is " + x)

The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example

If you use the global keyword, the variable belongs to the global scope:

def myfunc():

  global x

  x = "fantastic"

 

myfunc()

 

print("Python is " + x)

Also, use the global keyword if you want to change a global variable inside a function.

Example

To change the value of a global variable inside a function, refer to the variable by using the global keyword:

x = "awesome"

 

def myfunc():

  global x

  x = "fantastic"

 

myfunc()

 

print("Python is " + x)

4.4 Exercise

1. What is the correct syntax to add the value 'Hello World', to 3 values in one statement?

A. x, y, z = 'Hello World'

B. x = y = z = 'Hello World'

C. x|y|z = 'Hello World'

D. 'x' = 'y' = 'z' = 'Hello World'

2. What is the correct syntax to assign values to multiple variables in one line?

A. x, y, z = "Orange", "Banana", "Cherry"

B. x = y = z = "Orange", "Banana", "Cherry"

C. x|y|z = "Orange", "Banana", "Cherry"

D. 'x' = 'y' = 'z' = "Orange", "Banana", "Cherry"

3. Consider the following code:

fruits = ['apple', 'banana', 'cherry']

a, b, c = fruits

print(a)

What will be the result of a?

A. apple

B. banana

C. cherry

D. True

4. Consider the following code:

print('Hello', 'World')

What will be the printed result?

A. Hello, World

B. Hello World

C. HelloWorld

D. 'Hello', 'World'

5. Consider the following code:

a = 'Hello'

b = 'World'

print(a + b)

What will be the printed result?

A. a + b

B. Hello World

C. HelloWorld

D. 'Hello''World'

6. Consider the following code:

a = 4

b = 5

print(a + b)

What will be the printed result?

A. 45

B. 9

C. 4 + 5

D. Error

7. Consider the following code:

x = 'awesome'

def myfunc():

  x = 'fantastic'

myfunc()

print('Python is ' + x)

What will be the printed result?

A. Python is awesome

B. Python is fantastic

C. Python is x

D. Python is + x

8. Insert the correct keyword to make the variable x belong to the global scope.

  ______x

  x = "fantastic"

A. global variable 

B. global

C. Global

D. “Global” 

9. Consider the following code:

x = 'awesome'

def myfunc():

  global x

  x = 'fantastic'

myfunc()

print('Python is ' + x)

What will be the printed result?

A. Python is awesome

B. Python is fantastic

C. Python is True

D. Python is False

-----

Bài sau: Python căn bản (5): Data Types

-----

Bạn muốn học Python căn bản tại Đà Lạt, liên hệ

Python căn bản (3): Variables

Bài trước: Python căn bản (2): Syntax

-----

[Từ điển]

3. Python Variables

3.1 Variables

Variables are containers for storing data values.

Creating variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Example

x = 5

y = "John"

print(x)

print(y)

Variables do not need to be declared with any particular type, and can even change type after they have been set.

Example

x = 4       # x is of type int

x = "Sally" # x is now of type str

print(x)

Casting

If you want to specify the data type of a variable, this can be done with casting.

Example

x = str(3)    # x will be '3'

y = int(3)    # y will be 3

z = float(3)  # z will be 3.0

Get the type

You can get the data type of a variable with the type() function.

Example

x = 5

y = "John"

print(type(x))

print(type(y))

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

Example

x = "John"

# is the same as

x = 'John'

print(x)

Case-Sensitive

Variable names are case-sensitive.

Example

This will create two variables:

a = 4

A = "Sally"

#A will not overwrite a

print(a)

print(A)

3.2 Variable Name

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:

- A variable name must start with a letter or the underscore character

- A variable name cannot start with a number

- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

- Variable names are case-sensitive (age, Age and AGE are three different variables)

- A variable name cannot be any of the Python keywords.

Example

Legal variable names:

myvar = "John"

my_var = "John"

_my_var = "John"

myVar = "John"

MYVAR = "John"

myvar2 = "John"

Example

Illegal variable names:

2myvar = "John"

my-var = "John"

my var = "John"

Multi Words Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Camel Case

Each word, except the first, starts with a capital letter:

Example

myVariableName = "John"

Pascal Case

Each word starts with a capital letter:

Example

MyVariableName = "John"

Snake Case

Each word is separated by an underscore character:

Example

my_variable_name = "John"

3.3 Input data from the keyboard

The input() function is the simplest way to get keyboard data from the user in Python. 

When called, it asks the user for input with a prompt that you specify, and it waits for the user to type a response and press the Enter key.

Example

name = input("Your name: ")

print(name)

3.4 Exercise

1. What is a correct way to declare a Python variable?

A. var x = 5 

B. #x = 5

C. x = 5

D. $x = 5

2. True or False:

You can declare string variables with single or double quotes.

x = "John"

# is the same as

x = 'John'

A. True

B. False

3. True or False:

Variable names are not case-sensitive.

a = 5

# is the same as

A = 5

A. True

B. False

4. Which is NOT a legal variable name?

A. my-var = 20

B. my_var = 20

C. Myvar = 20

D. _myvar = 20

5. Create a variable named carname and assign the value Volvo to it. Which is correct?

A. carname = Volvo

B. “carname” = “Volvo”

C. carname = “Volvo”

D. “carname” = Volvo

6. Create a variable named x and assign the value 50 to it. Which is correct?

A. x  = “50”

B. x = 50

C. “x” = “50”

D. “x” = 50

7. Creating two variables to store your age and your full name. Print values of two variables out screen. Hints: variables named myAge, myFullname.

Expected output:

11 Nguyen Van Teo

8. Using input() function to get data from the keyboard. Example:

myAge = input(“So tuoi cua ban la: “)

Write the program to get the: full name, age, phone number, address from the keyboard, then print out the screen.

Expected output:

Ho ten cua ban la: Nguyen Van Teo

Tuoi cua ban la:10

So dien thoai cua ban la:0988765432

Dia giao hang la:12 Bui Thi Xuan - Dalat

Thong tin cua ban:

 

 Nguyen Van Teo 10 0988765432 12 Bui Thi Xuan - Dalat

----- Cập nhật 16/9/2024 -----

Bài sau: Python căn bản (4): Variables (cont)

-----

Bạn muốn học Python căn bản tại Đà Lạt, liên hệ