Jens Braun - Learn Python quick

Здесь есть возможность читать онлайн «Jens Braun - Learn Python quick» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Learn Python quick: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Learn Python quick»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

learn Python quick is the world's best-selling guide to the Python programming language. This good introduction to programming with Python will have you writing programs, solving problems, and building things that work in no time.You'll learn basic programming concepts like variables, lists, classes, and loops, and practice writing clean code with exercises on each topic. You'll also learn how to make your programs interactive and how to safely test your code before incorporating it into a project.

Learn Python quick — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Learn Python quick», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

#This is a comment

#This is also a comment

#This is yet another comment

Alternatively, we can also use three single quotes (or three double quotes) for multiline comments, like this:

’’’

This is a comment

This is also a comment

This is yet another comment

’’’

Now click File > Save As… to save your code. Make sure you save it with the .py extension.

Done? Voilà! You have just successfully written your first Python program.

Finally click on Run > Run Module to execute the program (or press F5). You should see the words Hello World printed on your Python Shell.

To see these steps in action, you can check out this excellent tutorial by mybringback:

https://www.youtube.com/watch?v=pEFr1eYIePw.

However, note that he used Python 2 in the video, so some commands will give you an error. If you want to try his codes, you need to add ( ) for the print statements. Instead of writing print ‘Hello World’, you have to write print (‘Hello World’). In addition, you have to change raw_input() to input(). We’ll cover print() and input() in Chapter 5.

Chapter 3: The World of Variables and Operators

Now that we’re done with the introductory stuff, let’s get down to the real stuff. In this chapter, you’ll learn all about variables and operators. Specifically, you’ll learn what variables are and how to name and declare them. We’ll also learn about the common operations that we can perform on them. Ready? Let’s go.

What are variables?

Variables are names given to data that we need to store and manipulate in our programs. For instance, suppose your program needs to store the age of a user. To do that, we can name this data userAge and define the variable userAge using the following statement.

userAge = 0

After you define the variable userAge, your program will allocate a certain area of your computer's storage space to store this data. You can then access and modify this data by referring to it by its name, userAge. Every time you declare a new variable, you need to give it an initial value. In this example, we gave it the value 0. We can always change this value in our program later.

We can also define multiple variables at one go. To do that simply write

userAge, userName = 30, ‘Peter’

This is equivalent to

userAge = 30

userName = ‘Peter’

Naming a Variable

A variable name in Python can only contain letters (a - z, A - B), numbers or underscores (_). However, the first character cannot be a number. Hence, you can name your variables userName, user_name or userName2 but not 2userName.

In addition, there are some reserved words that you cannot use as a variable name because they already have preassigned meanings in Python. These reserved words include words like print, input, if, while etc. We’ll learn about each of them in subsequent chapters.

Finally, variable names are case sensitive. username is not the same as userName.

There are two conventions when naming a variable in Python. We can either use the camel case notation or use underscores. Camel case is the practice of writing compound words with mixed casing (e.g. thisIsAVariableName). This is the convention that we’ll be using in the rest of the book. Alternatively, another common practice is to use underscores (_) to separate the words. If you prefer, you can name your variables like this: this_is_a_variable_name.

The Assignment Sign

Note that the = sign in the statement userAge = 0 has a different meaning from the = sign we learned in Math. In programming, the = sign is known as an assignment sign. It means we are assigning the value on the right side of the = sign to the variable on the left. A good way to understand the statement userAge = 0 is to think of it as userAge <- 0.

The statements x = y and y = x have very different meanings in programming.

Confused? An example will likely clear this up.

Type the following code into your IDLE editor and save it.

x = 5

y = 10

x = y

print ("x = ", x)

print ("y = ", y)

Now run the program. You should get this output:

x = 10

y = 10

Although x has an initial value of 5 (declared on the first line), the third line x = y assigns the value of y to x (x <- y), hence changing the value of x to 10 while the value of y remains unchanged.

Next, modify the program by changing ONLY ONE statement: Change the third line from x = y to y = x. Mathematically, x = y and y = x mean the same thing. However, this is not so in programming.

Run the second program. You will now get

x = 5

y = 5

You can see that in this example, the x value remains as 5, but the value of y is changed to 5. This is because the statement y = x assigns the value of x to y (y <- x). y becomes 5 while x remains unchanged as 5.

Basic Operators

Besides assigning a variable an initial value, we can also perform the usual mathematical operations on variables. Basic operators in Python include +, -, *, /, //, % and ** which represent addition, subtraction, multiplication, division, floor division, modulus and exponent respectively.

Example:

Suppose x = 5, y = 2

Addition:

x + y = 7

Subtraction:

x - y = 3

Multiplication:

x*y = 10

Division:

x/y = 2.5

Floor Division:

x//y = 2 (rounds down the answer to the nearest whole number)

Modulus:

x%y = 1 (gives the remainder when 5 is divided by 2)

Exponent:

x**y = 25 (5 to the power of 2)

More Assignment Operators

Besides the = sign, there are a few more assignment operators in Python (and most programming languages). These include operators like +=, -= and *=.

Suppose we have the variable x, with an initial value of 10. If we want to increment x by 2, we can write

x = x + 2

The program will first evaluate the expression on the right (x + 2) and assign the answer to the left. So eventually the statement above becomes x <- 12.

Instead of writing x = x + 2, we can also write x += 2 to express the same meaning. The += sign is actually a shorthand that combines the assignment sign with the addition operator. Hence, x += 2 simply means x = x + 2.

Similarly, if we want to do a subtraction, we can write x = x - 2 or x -= 2. The same works for all the 7 operators mentioned in the section above.

Chapter 4: Data Types in Python

In this chapter, we’ll first look at some basic data types in Python, specifically the integer, float and string. Next, we’ll explore the concept of type casting. Finally, we’ll discuss three more advanced data types in Python: the list, tuple and dictionary.

Integers

Integers are numbers with no decimal parts, such as -5, -4, -3, 0, 5, 7 etc.

To declare an integer in Python, simply write variableName = initial value

Example:

userAge = 20, mobileNumber = 12398724

Float

Float refers to numbers that have decimal parts, such as 1.234, -0.023, 12.01.

To declare a float in Python, we write variableName = initial value

Example:

userHeight = 1.82, userWeight = 67.2

String

String refers to text.

To declare a string, you can either use variableName = ‘initial value’ (single quotes) or variableName = “initial value” (double quotes)

Example:

userName = ‘Peter’, userSpouseName = “Janet”, userAge = ‘30’

In the last example, because we wrote userAge = ‘30’, userAge is a string. In contrast, if you wrote userAge = 30 (without quotes), userAge is an integer.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Learn Python quick»

Представляем Вашему вниманию похожие книги на «Learn Python quick» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Learn Python quick»

Обсуждение, отзывы о книге «Learn Python quick» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x