0% found this document useful (0 votes)
12 views19 pages

Python Basics: A Beginner's Guide

Uploaded by

Janner Pareja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views19 pages

Python Basics: A Beginner's Guide

Uploaded by

Janner Pareja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

20/11/2020 Python Tutorial For Beginners.

ipynb - Colaboratory

PYTHON TUTORIAL FOR BEGINNERS

class Python:

def programin_with_mosh:

#here my code..

Transcribed by: Janner Pareja

Author: Mosh Hamedani

Date: 16 sep. 2020

[Link] 1/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

TABLE OF CONTENT

1. Introduction

2. What You Can Do With Python

3. My First Python Program

4. Variables

5. Receiving Input

6. Type Conversion

7. Strings

8. Arithmetic Operators

9. Operator Precedence

10. Comparison Operators

11. Logical Operators

12. If Statements

13. Exercise

14. While Loops

15. Lists

16. List Methods

17. For Loops

18. The range() Function

19. Tuples

[Link] 2/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

Introduction
Python (programming language)
Python is an interpreted, high-level and general-purpose programming language. Python's design
philosophy emphasizes code readability with its notable use of signi cant whitespace. Its
language constructs and object-oriented approach aim to help programmers write clear, logical
code for small and large-scale projects.[28]

Python is dynamically typed and garbage-collected. It supports multiple programming paradigms,


including structured (particularly, procedural), object-oriented, and functional programming. Python
is often described as a "batteries included" language due to its comprehensive standard library.[29]

Python was created in the late 1980s, and rst released in 1991, by Guido van Rossum as a
successor to the ABC programming language. Python 2.0, released in 2000, introduced new
features, such as list comprehensions, and a garbage collection system with reference counting. It
was discontinued as version 2.7 in 2020.[30] Python 3.0, released in 2008, was a major revision of
the language that is not completely backward-compatible and much Python 2 code does not run
unmodi ed on Python 3.

Python interpreters are available for many operating systems. A global community of programmers
develops and maintains CPython, a free and open-source[31] reference implementation. A non-
pro t organization, the Python Software Foundation, manages and directs resources for Python
and CPython development.

History
Python was conceived in the late 1980s[32] by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands as a successor to the ABC programming language, which was
inspired by SETL),[33] capable of exception handling and interfacing with the Amoeba operating
system.[8] Its implementation began in December 1989.[34] Van Rossum shouldered sole
responsibility for the project, as the lead developer, until 12 July 2018, when he announced his
"permanent vacation" from his responsibilities as Python's Benevolent Dictator For Life, a title the
Python community bestowed upon him to re ect his long-term commitment as the project's chief
decision-maker.[35] He now shares his leadership as a member of a ve-person steering council.
[36][37][38] In January 2019, active Python core developers elected Brett Cannon, Nick Coghlan,
Barry Warsaw, Carol Willing and Van Rossum to a ve-member "Steering Council" to lead the
project.[39] Guido van Rossum has since then withdrawn his nomination for the 2020 Steering
council.[40]

Python 2.0 was released on 16 October 2000 with many major new features, including a cycle-
detecting garbage collector and support for Unicode.[41] More

[Link] 3/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

What You Can Do With Python

[Link] 4/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

My First Python Program

1 #Mi primer programa en Python


2 print("Hello World")

Hello World

Variables

Variables are the names you give to computer memory locations which are used to store values in
a computer program.

1 age = 20 #integer
2 price = 19.95 #Float
3 first_name = "Janner" #String
4 is_online = False #Boolean
5
6 print(age)
7 print(price)
8 print(first_name)
9 print(is_online)

20
19.95
Janner
False

Receiving Input

Input and output is terminology referring to the communication between a computer program and
its user. Input is the user giving something to the program, and output is the program giving
something to the user.

1 #input data (input)


[Link] 5/19
20/11/2020 Python Tutorial For [Link] - Colaboratory
put data ( put)
2 name = input("What is your name? ")
3 #We join the variable "name" to a new string and print
4 print("Hello " + name)

What is your name? Janner


Hello Janner

Type Conversion

In computer science, type conversion or typecasting refers to changing an entity of one datatype
into another.

Ops! the program crash

1 birth_year = input("Enter your birth year: ")


2 age = 2020 - birth_year #Here we have an Error!
3 # age = 2020 - "1981"
4 print(age)

Enter your birth year: 1981


---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-368c2c04ef45> in <module>()
1 birth_year = input("Enter your birth year: ")
----> 2 age = 2020 - birth_year #Here we have an Error!
3 # age = 2020 - "1981"
4 print(age)

TypeError: unsupported operand type(s) for -: 'int' and 'str'

SEARCH STACK OVERFLOW

Solution!

1 birth_year = input("Enter your birth year: ")


2 age = 2020 - int(birth_year)
3 print(age)

Enter your birth year: 1981


39

[Link] 6/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

Functions For Conversions

int(): Integer data

float(): Decimal data

bool(): A binary variable, having two possible values called “true” and “false.”.

str(): Text strings

Practice

First: 10.1
Second: 20
Sum: 30.1

1 #Apparently something happens here!


2 first = input("First: ")
3 #first = "10"
4 second = input("Second: ")
5 #second = "20"
6 sum = first + second
7 #sum = "10" + "20"
8 # "1020"
9 print(sum)

First: 10
Second: 20
1020

1 #This is better!
2 #Using int() function
3 first = input("First: ")
4 second = input("Second: ")
5 sum = int(first) + int(second)
6 print(sum)

First: 10
Second: 20
30

[Link] 7/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

Ops! the program crash

1 first = input("First: ")


2 second = input("Second: ")
3 sum = int(first) + int(second)
4 print(sum)

First: 10.1
Second: 20
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-21-366f4dcbface> in <module>()
1 first = input("First: ")
2 second = input("Second: ")
----> 3 sum = int(first) + int(second)
4 print(sum)

ValueError: invalid literal for int() with base 10: '10.1'

SEARCH STACK OVERFLOW

Solution!

1 #Using float() function


2 first = input("First: ")
3 second = input("Second: ")
4 sum = float(first) + float(second)
5 print("Sum: " + str(sum))

First: 10.1
Second: 20
Sum: 30.1

Other solution!

1 #Using float() function


2 first = input("First: ")
3 second = input("Second: ")
4 sum = float(first) + float(second)
5 print("Sum: " + str(sum))

[Link] 8/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

Strings

In computer programming, a string is traditionally a sequence of characters, either as a literal


constant or as some kind of variable.

1 # Python for Beginners


2 # 0123456789..
3 course = 'Python for Beginners'
4
5 #text formatting
6 print([Link]())
7 print([Link]())
8 print(course)
9
10 #find
11 print([Link]('y'))
12 print([Link]('for'))
13
14 #replace
15 print([Link]('for', '4'))
16
17 #boolean
18 print('Python' in course)

PYTHON FOR BEGINNERS


python for beginners
Python for Beginners
1
7
Python 4 Beginners
True

Arithmetic Operators

The basic arithmetic operations are addition, subtraction, multiplication, and division. Arithmetic is
performed according to an order of operations.

1 #sum
2 print(10 + 3)
3 #subtraction
4 print(10 - 3)
[Link] 9/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

5 #division with decimals


6 print(10 / 3)
7 #division without decimals
8 print(10 // 3)
9 #module
10 print(10 % 3)
11 #exponentiation
12 print(10 ** 3)
13
14 #assignment operator
15 x = 10
16 x = x + 3
17 #x += 3
18 #x -= 3
19 #x *= 3
20 print(x)

13
7
3.3333333333333335
3
1
1000
13

Operator Precedence

In mathematics and computer programming, the order of operations (or operator precedence) is a
collection of rules that re ect conventions about which procedures to perform rst in order to
evaluate a given mathematical expression.

1 x = 10 + 3 * 2
2 x = (10 + 3) * 2
3 print(x)

26

Comparison Operators

[Link] 10/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

Operators that compare values and return true or false . The operators include: > , < , >= , <= , === ,
and !== .

Haz doble clic (o pulsa Intro) para editar

1 x = 3 > 2 #greater than


2 #x = 3 >= 2 #greater than or equal to
3 #x = 3 < 2 #less than
4 #x = 3 <= 2 #less than or equal to
5 #x = 3 == 2 #equal to
6 #x = 3 != 2 #not equal to
7
8 print(x)

True

Logical Operators

A logical operator is a symbol or word used to connect two or more expressions such that the
value of the compound expression produced depends only on that of the original expressions and
on the meaning of the operator.

# and (both)

# or (at least one)

# not (negation)

1 price = 25
2 print(price > 10 and price < 30)
3 print(price > 10 or price < 30)
4 print(not price > 10)

True
True
False

[Link] 11/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

If Statements

The if statement allows you to control if a program enters a section of code or not based on
whether a given condition is true or false. One of the important functions of the if statement is that
it allows the program to select an action based upon the user's input.

1 #If condition
2 temperature = 35
3
4 if temperature > 30:
5 print("It's a hot day")
6 print("Drink plenty of water")

It's a hot day


Drink plenty of water

1 #¿what happen here?


2 temperature = 25
3
4 if temperature > 30:
5 print("It's a hot day")
6 print("Drink plenty of water")

1 #Ok, is done!
2 temperature = 25
3
4 if temperature > 30:
5 print("It's a hot day")
6 print("Drink plenty of water")
7 print("Done")

Done

1 #elif / else
2 temperature = 25
3
4 if temperature > 30:
5 print("It's a hot day")
6 print("Drink plenty of water")
7 elif temperature > 20: # (21, 30]
8 print("It's a nice day")
9 elif temperature > 10: # (11, 20)
[Link] 12/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

10 print("It's a bit cold")


11 else:
12 print("It's cold")
13 print("Done")

It's a nice day


Done

Exercise

Weight: 170
(K)g or (L)bs: l
Weight in Kg: 76.5

Response

1 weight = int(input("Weight: "))


2 unit = input("(K)g or (L)bs: ")
3
4 if [Link]() == "K":
5 converted = weight / 0.45
6 print("Weight in Lbs: " + str(converted))
7 else:
8 converted = weight * 0.45
9 print("Weight in Kgs: " + str(converted))
10

Weight: 170
(K)g or (L)bs: l
Weight in Kgs: 76.5

While Loops

In most computer programming languages, a while loop is a control ow statement that allows
code to be executed repeatedly based on a given Boolean condition.

1 print("1")
2 print("2")
3 print("3")
4 print("4")
[Link] 13/19
20/11/2020 Python Tutorial For [Link] - Colaboratory
4 print( 4 )
5 print("5")

1 i = 1
2 while i <= 5:
3 print(i)
4 i += 1

1
2
3
4
5

1 i = 1
2 while i <= 10:
3 print(i * '*')
4 i += 1

*
**
***
****
*****
******
*******
********
*********
**********

Lists

List is the most versatile data type available in functional programming languages used to store a
collection of similar data items. The concept is similar to arrays in object-oriented programming.
List items can be written in a square bracket separated by commas.

1
1.1
True
'a'

1 names = ["John", "Bob", "Mosh", "Sam", "Mary"]


[Link] 14/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

2 print(names)
3 print(names[0])
4 print(names[-1])
5 print(names[-2])
6 names[0] = "Jon"
7 print(names)
8 print(names[0:3])

['John', 'Bob', 'Mosh', 'Sam', 'Mary']


John
Mary
Sam
['Jon', 'Bob', 'Mosh', 'Sam', 'Mary']
['Jon', 'Bob', 'Mosh']

List Methods

1 numbers = [1, 2, 3, 4, 5]
2 #The append() method appends an element to the end of the list.
3 [Link](6)
4 print(numbers)
5 #The list insert() method inserts an element to the list at the specified index.
6 [Link](0, -1)
7 print(numbers)
8 #Remove() searches for the given element in the list and removes the first matching elemen
9 [Link](3)
10 print(numbers)
11 #The clear() method removes all items from the list.
12 [Link]()
13 print(numbers)

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

1 numbers = [1, 2, 3, 4, 5]
2 print(1 in numbers)
3 #The len() function returns the number of items in an object
4 print(len(numbers))

True
5

[Link] 15/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

For Loops

In computer science, a for-loop (or simply for loop) is a control ow statement for specifying
iteration, which allows code to be executed repeatedly. ... For-loops are typically used when the
number of iterations is known before entering the loop.

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

[1, 2, 3, 4, 5]

1 numbers = [1, 2, 3, 4, 5]
2 for item in numbers:
3 print(item)

1
2
3
4
5

1 i = 0
2 while i < len(numbers):
3 print(numbers[i])
4 i += 1

1
2
3
4
5

The range() Function

Range() function generates a list of numbers between the given start integer to the stop integer.

1 numbers = range(5)
2 print(numbers)

range(0, 5)
[Link] 16/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

1 for number in numbers:


2 print(number)

0
1
2
3
4

1 numbers = range(5, 10)


2 for number in numbers:
3 print(number)

5
6
7
8
9

1 numbers = range(5, 10, 2)


2 for number in numbers:
3 print(number)

5
7
9

1 for number in range(5):


2 print(number)

0
1
2
3
4

Tuples

A tuple is a collection of objects which ordered and immutable

1 numbers = (1, 2, 3)
2 numbers[0] = 10

[Link] 17/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-51-465a0d58e464> in <module>()
1 numbers = (1, 2, 3)
----> 2 numbers[0] = 10

TypeError: 'tuple' object does not support item assignment

SEARCH STACK OVERFLOW

1 numbers = (1, 2, 3, 3)
2 print([Link](3))
3 print([Link](2))

2
1

[Link] 18/19
20/11/2020 Python Tutorial For [Link] - Colaboratory

Python Tutorial - Python for Beginners [2020]

Reference link

[Link] 19/19

Common questions

Powered by AI

Lists and tuples in Python differ primarily in terms of mutability. Lists are mutable, meaning they can be modified after creation through operations like appending, removing, or reassigning elements. In contrast, tuples are immutable, meaning their elements cannot be changed once set. Thus, lists are suited for collections of data that need to change over time, while tuples are used for fixed collections of items where immutability is advantageous for performance and reliability .

Python 2.0 introduced features like a cycle-detecting garbage collector and Unicode support, while Python 3.0, which is a major revision, is not backward-compatible with Python 2. Programmers migrating code from Python 2 to Python 3 face challenges such as incompatible syntax and libraries, differences in integer division, and changes in built-in functions and modules. These changes require modifications to make Python 2 code run in Python 3, such as adjusting print statements, string handling, and division operations .

The Python Software Foundation is a non-profit organization that manages and directs resources for Python and CPython development. It plays a crucial role in the global development community by providing support in terms of resources and infrastructure, ensuring that Python remains free and open-source, and guiding its future direction through governance structures like the Steering Council .

Arithmetic operators in Python follow a specific order of operations known as operator precedence, which determines the order in which parts of a mathematical expression are evaluated. For example, multiplication and division have higher precedence than addition and subtraction. This means that in an expression like '10 + 3 * 2', multiplication is performed before addition, resulting in a value of 16. Correctly applying these rules is crucial for achieving the intended outcomes of arithmetic expressions .

The Steering Council was introduced to distribute decision-making responsibilities and guide Python's future development following Guido van Rossum's retirement from his role as Python's Benevolent Dictator For Life. The council consists of five members, elected for their experience and contributions to the community, representing a collective approach to governance that can address diverse challenges while maintaining the language's integrity and development pace .

Logical operators in Python are used to combine conditional statements. They include 'and', 'or', and 'not'. 'And' returns True if both operands are true, 'or' returns True if at least one operand is true, and 'not' negates the truth value. For example, the statement 'if price > 10 and price < 30:' evaluates as true only if the variable 'price' holds a value between 10 and 30 .

The 'range' function in Python generates a sequence of numbers and is commonly used in for loops to iterate over a set of numbers. It takes start, stop, and step arguments to determine the sequence's bounds and interval, enabling loops to run a specific number of iterations without manually tracking iteration counters. This simplifies code needed for repetitive tasks, ensuring that loops can run efficiently over specified numeric ranges .

Python's design philosophy emphasizes code readability, encouraging programmers to write clean and logical code, which is facilitated by its emphasis on significant whitespace. In Python, whitespace is used to define the structure of the code, such as the delimitation of blocks instead of using braces or semicolons found in other languages. This leads to more readable and maintainable code as it enforces a consistent visual structure .

Python requires explicit type conversion for operations between incompatible data types, such as subtracting a string from an integer. If not handled properly, such operations can cause a TypeError as seen when subtracting input-derived strings from integers during arithmetic operations. Proper type conversion is essential, using functions like int(), float(), and str() to avoid errors and ensure the correct program behavior .

Python's if-elif-else statements offer a way to execute specific blocks of code based on the evaluation of conditions. The 'if' statement checks a condition and executes its block if true. If false, the program proceeds to the 'elif' conditions (if any), each having its own block, until one is true or finalizing with the 'else' block, ensuring one segment of code is executed even if prior conditions fail. This structure greatly enhances control flow by allowing decision-making processes to be expressed clearly and logically .

You might also like