четверг, 21 февраля 2019 г.

№ 4 Conditionals & Control Flow.

Давно же я не садилась за код)) Прошло почти полгода или даже более. Первое задание заставило мои мозги скрипеть от натуги.
2**3 = 8 = 2^3
А, еще помню, оказывается! Есть ещё порох в пороховницах! И ещё вспомню-ка кое-что:
x / yДеление
x // yПолучение целой части от деления
x % yОстаток от деления
-xСмена знака числа
abs(x)Модуль числа
divmod(x, y)Пара (x // y, x % y)
x ** yВозведение в степень
pow(x, y[, z])xy по модулю (если модуль задан)

Ну, наверное, матрицу истинности для оператора OR напоминать не надо, да? С первым заданием справилась легко, после того, как пораскинула мозгами:

Time to practice with or!
  1. Set bool_one equal to the result of2**3 == 108 % 100 or 'Cleese' == 'King Arthur'
  2. Set bool_two equal to the result ofTrue or False
  3. Set bool_three equal to the result of 100**0.5 >= 50 or False
  4. Set bool_four equal to the result ofTrue or True
  5. Set bool_five equal to the result of1**100 == 100**1 or 3 * 2 * 1 != 3 + 21
bool_one:
2**3=2^3=8; 108%100=8   -> 8=8   => true; 'Cleese' is not equal to 'King Artur'.
true or false = true

bool_two = bool_one

bool_three:
100**0.5=sqrt(100)=10;  10<50 -> False
False or False = False
bool_four has the same logic as bool_three:
true or true = 1
falsa or false = 0
The same shit!

bool_five = 0
1**100=1;  100**1 = 100; 1 not equal 100 => false
3*2*1=6; 3+2+1=6; 6=6 => false

У! Как я таблицы истинности забыла! Позор мне на мою голову!
0 и 0 = 0                                                           0 или 0 = 0
0 и 1 = 1 и 0 = 0                                               1 или 0 = 0 или 1 = 1
1 и 1 = 1                                                            1 или 1 = 1

Not  возвращает для правды значение 0, для лжи значение - 1

Немного про if и прочие операторы условий


elif == "else if"

Conditionals & Control Flow или условия и управление потоком (видимо, потоковым выводом)

Ну что ж, как мы все в курсе, питончик-то наш скриптовый язык) А посему смоделируем ситуацию выбора:
def clinic():
    print "You've just entered the clinic!"
    print "Do you take the door on the left or the right?"
    answer = raw_input("Type left or right and hit 'Enter'.").lower()
    if answer == "left" or answer == "l":
        print "This is the Verbal Abuse Room, you heap of parrot droppings!"
    elif answer == "right" or answer == "r":
        print "Of course this is the Argument Room, I've told you that already!"
    else:
        print "You didn't pick left or right! Try again."
        clinic()

clinic()

среда, 20 февраля 2019 г.

Как я все это говно настраивала под винду

питон под винду должен гореть в аду  настраиваться нормально, а не через ебанную многоходовочку

1) анаконда
которая по идее содержит в себе питон и прогах появляется  вот эта хуйня, что внизу, но это не позволяет установить нужные пакеты!

Поэтому бужет выдавать ошибку:
А,ну и запускаем всю эту хуйню от имени  одмина. Куда ж без то .




2) качаем отдельно питон с python.org .
Нахуй общие настройки -  кастомизируем по максимуму (хе, мне просто директория не понравилась и выебываться я тоже люблю), короче, поставила галочки везде, кроме последней хуйни, где в скобках (VS).

Ну и в конце ничего там не расширяла -  а то не дай богиня опять все наебнется и пойдет по хую -  нахуй надо!

2) Потом из командной строки от админа  установила пакеты.  pandas,numpy и тд.

3) осталось доставить кегловские пакеты и упоротого кролика, но это потом. Сейчас по идее все должно работать.Вот

среда, 24 августа 2016 г.

Boolean functions. This and That (or This, But Not That!)

Продолжаем изучение Питона спуятся пару месяцев (кажется, три)

This and That (or This, But Not That!) 
Приоритеты у операторов следующие:
1. Not
2. And
3. Or
Менять приоритеты можно скобками. Все как в дискретке.  Например: 

False or not (True and True) =  False

# Use boolean expressions as appropriate on the lines below!

# Make me false!
bool_one = (2 <= 2) and "Alpha" == "Bravo"  # We did this one for you!

# Make me true!
bool_two = (2 <= 2) and not ("Alpha" == "Bravo")

# Make me false!
bool_three = not (2 <= 2) and "Alpha" == "Bravo"

# Make me true!
bool_four = (2 <= 2) or "Alpha" == "Bravo"

# Make me true!
bool_five = (2 <= 2) and  not ("Alpha" == "Bravo")

вторник, 10 ноября 2015 г.

№3 Библиотека datetime

Очевидно из названия, для чего она используется.

Видимо, так мы подключаем пакеты необходимые нам.

from datetime import datetime
The first line imports the datetimelibrary so that we can use it.
We can use a function calleddatetime.now() to retrieve the current date and time.
Extracting Information
Notice how the output looks like 2013-11-25 23:45:14.317454. What if you don't want the entire date and time?
from datetime import datetime
now = datetime.now()

current_year = now.year
current_month = now.month
current_day = now.day
You already have the first two lines.
In the third line, we take the year (and only the year) from the variable nowand store it in current_year.

Чтобы поиграться с форматами вывода данных воспользуемся волшебным опрератором  %(оператором же или кто он?) %s*, где на месте *будет стоять любой символ, который будет разделять данные
from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % ( now.month, now.day, now.year)
11/10/2015

Тоже самое можно делать и с часами, минутами и секундами: 
from datetime import datetime
now = datetime.now()

print '%s:%s:%s' % ( now.hour, now.minute, now.second)

print '%s/%s/%s %s:%s:%s' % ( now.month, now.day, now.year,now.hour, now.minute, now.second)
Выводит: 
11/10/2015 2:38

четверг, 8 октября 2015 г.

№2 Строки

Escaping characters
There are some characters that cause problems. For example:
'There's a snake in my boot!'
This code breaks because Python thinks the apostrophe in 'There's'ends the string. We can use the backslash to fix the problem, like this:

'There\'s a snake in my boot!'        

# The string below is broken. Fix it using the escape backslash
'This isn\'t flying, this is falling with style!'  

"""
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:

+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
  0   1   2   3   4   5

So if you wanted "Y", you could just type
"PYTHON"[1] (always start counting from 0!)
"""
fifth_letter = "MONTY"[5]
print fifth_letter     

String methods
Great work! Now that we know how to store strings, let's see how we can change them using string methods.
String methods let you perform specific tasks for strings.
We'll focus on four string methods:
  1. len()
  2. lower()
  3. upper()
  4. str()
Let's start with len(), which gets the length (the number of characters) of a string!                                      
parrot = "Norwegian Blue"
print len(parrot)

>14

Now let's look at str(), which is a little less straightforward. The str()method turns non-strings into strings! For example would turn 2 into "2"."""Declare and assign your variable on line 4,
then call your method on line 5!"""

pi = 3.14
print str(pi)
3.14

Dot Notation
Let's take a closer look at why you uselen(string) and str(object), but dot notation (such as "String".upper()) for the rest.
lion = "roar"
len(lion)
lion.upper()
Methods that use dot notation only work with strings.
On the other hand, len() and str()can work on other data types.
ministry = "The Ministry of Silly Walks"
print len(ministry)
print ministry.upper()
>27 >THE MINISTRY OF SILLY WALKS
The area where we've been writing our code is called the editor.
The console (the window in the upper right) is where the results of your code is shown.
print simply displays your code in the console.
String Concatenation
You know about strings, and you know about arithmetic operators. Now let's combine the two!
print "Life " + "of " + "Brian"
This will print out the phrase Life of Brian.
The + operator between strings will 'add' them together, one after the other. Notice that there are spaces inside the quotation marks after Lifeand of so that we can make the combined string look like 3 words.
Combining strings together like this is called concatenation. Let's try concatenating a few strings together now!
Make sure you include the spaces after"Spam " and "and ".

# Print the concatenation of "Spam and eggs" on line 3!


print "spam " + "and " + "eggs"
String Formatting with %, 
Remember, we used the % operator to replace the %s placeholders with the variables in parentheses ( круглая скобка или парентеза, вводное слово) Remember, we used the % operator to replace the %s placeholders with the variables in parentheses.
name = "Mike"
print "Hello %s" % (name)
You need the same number of %sterms in a string as the number of variables in parentheses:
print "The %s who %s %s!" % ("Knights", "say", "Ni")
# This will print "The Knights who say
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is  %s, " \
"and your favorite color is %s." % (name, quest, color)




And Now, For Something Completely Familiar
Great job! You've learned a lot in this unit, including:
Three ways to create strings
'Alpha'
"Bravo"
str(3)
String methods
len("Charlie")
"Delta".upper()
"Echo".lower()
Printing a string
print "Foxtrot"
Advanced printing techniques
g = "Golf"
h = "Hotel"
print "%s, %s" % (g, h)
# Write your code below, starting on line 3! my_string = "Buuuuchneva" print len(my_string) print my_string.upper()