1. Trang chủ
  2. » Tất cả

PYTHON BASICS AND c CODING EXAMPLES: PROGRAMMING FOR BEGINNERS

80 4 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Python Basics and C# Coding Examples: Programming for Beginners
Tác giả J King
Chuyên ngành Programming for Beginners
Định dạng
Số trang 80
Dung lượng 589,83 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

PYTHON BASICS AND C CODING EXAMPLES PROGRAMMING FOR BEGINNERS PYTHON BASICS AND C CODING EXAMPLES PROGRAMMING FOR BEGINNERS J KING PYTHON INTRODUCTION PYTHON HISTORY AND VERSIONS FIRST PYTHON PROGRA. Python (phát âm tiếng Anh: ˈpaɪθɑːn) là một ngôn ngữ lập trình bậc cao cho các mục đích lập trình đa năng, do Guido van Rossum tạo ra và lần đầu ra mắt vào năm 1991. Python được thiết kế với ưu điểm mạnh là dễ đọc, dễ học và dễ nhớ. Python là ngôn ngữ có hình thức rất sáng sủa, cấu trúc rõ ràng, thuận tiện cho người mới học lập trình và là ngôn ngữ lập trình dễ học; được dùng rộng rãi trong phát triển trí tuệ nhân tạo. Cấu trúc của Python còn cho phép người sử dụng viết mã lệnh với số lần gõ phím tối thiểu.25 Vào tháng 7 năm 2018, van Rossum đã từ chức lãnh đạo trong cộng đồng ngôn ngữ Python sau 30 năm làm việc.2627 Python hoàn toàn tạo kiểu động và dùng cơ chế cấp phát bộ nhớ tự động; do vậy nó tương tự như Perl, Ruby, Scheme, Smalltalk, và Tcl. Python được phát triển trong một dự án mã mở, do tổ chức phi lợi nhuận Python Software Foundation quản lý.28

Trang 2

PYTHON BASICS

AND C# CODING EXAMPLES

PROGRAMMING FOR BEGINNERS

J KING

Trang 3

PYTHON INTRODUCTION

PYTHON HISTORY AND VERSIONS

FIRST PYTHON PROGRAM

PYTHON FOR LOOP

PYTHON WHILE LOOP

PYTHON BREAK STATEMENT

PYTHON CONTINUE STATEMENT

PYTHON STRING

PYTHON TUPLE

C# | PRINT MESSAGES/TEXT (PROGRAM TO PRINT HELLO WORLD)

C# PROGRAM TO PRINT A NEW LINE

C# PROGRAM TO PRINT SIZE OF VARIOUS DATA TYPES

TYPE CONVERSION FROM DOUBLE TO INT IN C# PROGRAM

DEFINE VARIOUS TYPES OF CONSTANTS

C# PROGRAM TO DEMONSTRATE EXAMPLE OF ARITHMETIC OPERATORS PROGRAM TO DEMONSTRATE EXAMPLE OF BITWISE OPERATORS

PROGRAM TO DEMONSTRATE EXAMPLE OF RELATIONAL OPERATORS FIND THE ADDITION OF TWO INTEGER NUMBERS

PROGRAM TO SWAP TWO NUMBERS

PROGRAM TO DEMONSTRATE EXAMPLE OF SIMPLE IF ELSE STATEMENT EXAMPLE OF MULTIPLE IF ELSE STATEMENT

Trang 4

C# PROGRAM OF CONDITIONAL OPERATOR

C# PROGRAM EXAMPLE OF SWITCH STATEMENT

C# PROGRAM TO FIND LARGEST OF TWO NUMBERS

PRINT NUMBERS FROM 1 TO 15 USING WHILE LOOP

PRINT NUMBERS FROM 1 TO 15 USING DO WHILE LOOP

PROGRAM TO FIND OUT THE PRIME NUMBERS AMONG 2 TO 30

Trang 5

PYTHON BASICS

PROGRAMMING FOR BEGINNERS

J KING

Trang 6

PYTHON INTRODUCTION

Python is a programming language that is general purpose, dynamic , high level, and interpreted To developapplications, it supports Object-Oriented programming approach Learning is simple and easy, and provides lots ofhigh-level data structures

Python is yet a powerful and versatile scripting language that is easy to learn, making it attractive for applicationdevelopment

With its interpreted nature, Python's syntax and dynamic typing make it an ideal language for scripting and quickapplication development

Python supports multiple styles of programming including object-oriented, imperative, and functional or proceduralstyles

Python is not intended to operate in a given area, such as web programming This is why it is known as the language

of multipurpose programming because it can be used with web, enterprise, 3D CAD etc

We don't have to use data types to declare variable because it's typed dynamically so that we can write a=10 toassign an integer value in an integer variable

Python Features

Python makes the development and debugging fast because the compilation step is not included in the development

of Python, and the edit-test-debug cycle is very fast

Compared with other programming languages Python is easy to learn Its syntax is direct and much the same as theEnglish language The semicolon or curly-bracket is not used, and the indentation defines the block of code It is therecommended language for beginners in the programming

Using a few lines of code Python can perform complex tasks A simple example, you simply type print("HelloWorld”) to the hello world program It'll take one line to execute, while Java or C will take multiple lines

Trang 7

Python History and Versions

Guido Van Rossum at CWI in The Netherlands began implementing Python in December 1989

Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources in February 1991

Python 1.0 was released in 1994, with new features such as lambda, map, filter, and reduce

Python 2.0 has added new features such as list understandings and garbage collection systems

Python 3.0 (also called "Py3 K") was released on December 3, 2008 It had been designed to correct the language'sfundamental flaw

Python Version List

Python

Version

Released Date

Trang 8

First Python Program

In this section, we 're going to discuss Python 's basic syntax, and run a simple program to print Hello World on theconsole

Python provides us with two modes of running a program:

Using Interactive interpreter prompt

Using a script file

Interactive interpreter prompt

Python gives us the functionality to execute the Python statement at the interactive prompt one by one In the casewhere we are concerned about the output of every line of our Python programme

Open the terminal (or command prompt) and type python (python3, if you have both Python2 and Python3 installed

on your system)

It will open the following prompt where we can execute the statement in Python and check its impact on the console

Using a script file

The interpreters prompt is good at running the individual code statements We can't write the code on the terminalanytime

Our code must be written into a file that can be executed later To do this, open a notepad editor, create a file namedfirst.py (Python used the.py extension) and write the following code into it

print ( "hello world" ); #here, we have used print() function to print the message on the console

Run the following command on the terminal

$ python3 first.py

Trang 10

Python Variables

Variable is a name used to refer to the location of a memory Also known as an identifier and used for holding value

In Python, we don't need to specify the variable type, because Python is an inferior language and is smart enough toget the type of variable

Variable names can be a group of letters and digits, but must start with a letter or an underscore

Using lowercase letters for name of the variable is recommended Rahul and rahul are both two different variables

Identifier Naming

Variables - example of identifiers To identify the literals used in the program an Identifier is used The rules fornaming an identifier are set out below

The variable must have an alphabet or underscore (_) as its first character

All characters except the first character can be lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9)

alphabets

The name of the identifier shall not contain any white space or any special character!, (@,#,%,^, &, *)

The name of the identifier must not be similar to any keyword set in the language

Identifier names are case sensitive; my name, for example, and MyName is not identical

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before we use it in the app It enables us to create a variable in the timerequired

In Python we do not need to declare explicitly variable That variable is declared automatically when we assign anyvalue to the variable

The operator equal (=) is used to assign value to a variable

Trang 11

We've already discussed how to declare the valid variable Variable names may be uppercase, lowercase (A to Z, a

to z), digit (0-9), and underscore ( ) Consider the following example of names for the valid variables

Trang 13

Python Data Types

Variables can hold values, with each value having a data-type Python is a dynamically typed language; thereforewhen declaring it, we don't need to define the type of variable Implicitly the interpreter binds the value to their type

Standard data types

A variable can hold a variety of values For instance, the name of a person has to be stored as a string while its Idhas to be stored as an integer

Python provides different standard data types on each of them which define the storage method Below you will findthe data types defined in Python

Python creates Number objects when a variable has a number assigned For instance;

print("The type of c", type(c))

print(" c is a complex number", isinstance(1+3j,complex))

OUTPUT

The type of a <class 'int'>

Trang 14

The type of b <class 'float'>

The type of c <class 'complex'>

c is complex number: True

str1 = 'hello learnpython'#string str1

str2 = ' how are you'#string str2

print (str1[0:2]) #printing first two character using slice operator

print (str1[4]) #printing 4th character of the string

print (str1*2) #printing the string twice

print (str1 + str2) #printing the concatenation of str1 and str2

OUTPUT

he

o

hello learnpythonhello learnpython

hello learnpython how are you

list1 = [1, "hi", "Python", 2]

#Checking type of given list

print(type(list1))

#Printing the list1

Trang 15

# List Concatenation using + operator

print (list1 + list1)

# List repetation using * operator

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

tup = ("hi", "Python", 2)

# Checking type of tup

# Tuple concatenation using + operator

print (tup + tup)

# Tuple repatation using * operator

('hi', 'Python', 2, 'hi', 'Python', 2)

('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Trang 16

Traceback (most recent call last):

File "main.py", line 14, in <module>

The dictionary items are separated by the comma(,) and enclosed within the curly braces{}

Trang 17

# Creating Empty set

set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value

Trang 18

Python Keywords

Python Keywords are special, reserved words that convey the compiler / interpreter a special meaning Each

keyword has a particular meaning and a particular operation You can't use those keywords as a variable The List ofPython Keywords follows

True False None and as

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocalin not is lambda

Traceback (most recent call last):

File "/home/40545678b342ce3b70beb1224bed345f.py", line 4, in

assert b != 0, "Divide by 0 error"

AssertionError: Divide by 0 error

Trang 19

elif(marks<90 and marks>=75):

print("Very Good")

elif(marks<75 and marks>=60):

print("Good")

else:

print("Average")

Trang 20

Python Literals

Python Literals can be defined as data given in a constant or a variable

Python supports the following literals:

Python supports two types of Strings:

a.Single line strings- Single line strings ended in a single line are known as Single line strings

Example:

text1='hello'

B) Multi-line Line-A piece of text written in several lines is called multi-line series

Multiline strings can be formed by two ways:

1) Adding black slash at the end of each line.

Numeric Literals are unchangeable

Example - Numeric Literals

Trang 21

print(x, y, z, u)

print(float_1, float_2)

print(a, a.imag, a.real)

A Boolean literal can have one of these two values: True or False

Example - Boolean Literals

Python has one special literal, that is None

None is used to indicate the field is not generated within the field This is also used in Python for finishing lists

Example - Special Literals

The List includes items of different types of data Lists are also mutable, i.e modifiable

Example - List literals

list=['John',678,20.4,'Peter']

Trang 22

In key-value pair, Python dictionary stores the data.

It's enclosed by curly-braces{} and the commas(,) separates each pair

Example: - Set Literals

set = {'apple','grapes','guava','papaya'}

print(set)

Output:

{'guava', 'apple', 'papaya', 'grapes'}

Trang 23

Python Operators

You may describe the operator as a symbol that is responsible for a specific operation between two operands.Operators are the foundations of a system on which a particular programming language constructs the logic Pythonoffers a range of operators, described as follows

+ (Addition) It is used to add two operands For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand If the first operand is

less than the second operand, the value results negative For example, if a = 20, b = 10

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= If the first operand is less than or equal to the second operand, then the condition

Trang 24

= It assigns the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right operand and assigns

the modified value back to left operand For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and assigns

the modified value back to left operand For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assigns

the modified value back to then the left operand For example, if a = 10, b = 20 => a* =

b will be equal to a = a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and assigns the

reminder back to the left operand For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.

^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit will be

0.

Trang 25

will be 1 and vice versa.

<< (left shift) The left operand value is moved left by the number of bits present in the right operand.

>> (right shift) The left operand is moved right by the number of bits present in the right operand.

Logical Operators

The logical operators are used primarily for making a decision in the expression evaluation Python supports thelogical operators which follow

Operator Description

and If both the expression are true, then the condition will be true If a and b are the two

expressions, a → true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true If a and b are the two

expressions, a → true, b → false => a or b → true.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators

Within a Python data structure, Python membership operators are used to verify the value membership If the value

in the data structure is present otherwise the resulting value is true else it will be false

Trang 26

Operator Description

** The exponent operator is given priority over all the others used in the expression.

~ + - The negation, unary plus, and minus.

* / % // The multiplication, divide, modules, reminder, and floor division.

+ - Binary plus, and minus

>> << Left shift and right shift

^ | Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater than, greater then

is is not Identity operators

in not in Membership operators

not or and Logical operators

Trang 27

Python Comments

Python Comment is a very important tool for programmers Commonly, comments are used to explain the code.Whether it has a clear definition we can quickly grasp the message A smart programmer has to use the comments ifsomebody wishes to change the code in the future as well as add the new module; so it can be done quickly

At the beginning of the statement or code we use the hash (#) to apply the comment in the code

EXAMPLE

# This is the print statement

print("Hello Python")

Here we used the hash (#) to write comment about the print statement It won't impact our print statement

Multiline Python Comment

To apply the multiline Python comment, we need to use the hash(#) at the beginning of each line of code Findscenario below

# First line of the comment

# Second line of the comment

# Third line of the comment

EXAMPLE

# Variable a holds value 5

# Variable b holds value 10

# Variable c holds sum of a and b

# Print the result

The sum is: 15

The code above is really clear even though the absolute beginners can see what is happening in each line of codeunder that This is the advantage

Docstrings Python Comment

The comment on docstring is mainly used in the module, function, class, or method In additional tutorials we willclarify the class / process

Trang 28

Python If-else statements

The decision-making aspect of almost all the programming languages is the most important As the name implies,decision-making enables us to run a specific block of code for a given decision The conclusions on the legitimacy

of the specified conditions are taken here The foundation of decision-making is condition checking

In python, the following clauses are used to make choices

Statement Description

If Statement The if statement is used to test a specific condition If the condition is true, a

block of code (if-block) will be executed.

If - else

Statement

The if-else statement is identical to if statement except that, it also includes the code block for the condition to be verified in the false case If the condition provided in the if statement is false, then the other statement is executed.

In general , four spaces are provided for indenting statements which are a standard amount of python indentation.Indentation is the most commonly used aspect of the python language, since it defines the code block All one blockstatements are meant to be at the same degree of indentation We'll see how the actual indentation occurs in pythondecision making and other stuff

The if statement

The if statement is used to test a particular condition and executes a block of code when the condition is true

Trang 29

if a>b and a>c:

print("a is largest");

Trang 30

The if-else statement

The if-else statement provides another block in conjunction with the if statement, which is executed in the condition's false case

If the condition is true then perform the if-block The else-block is executed, otherwise

SYNTAX

if condition:

#block of statements

else:

#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.

age = int (input("Enter your age? "))

Enter your age? 90

You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

num = int(input("enter the number?"))

if num%2 == 0:

print("Number is even ")

Trang 31

The elif statement

The elif statement helps one to test different conditions and execute the relevant set of statements based on their truestate Based on our requirement we will include any amount of elif statements in our program

The elif statement functions as if-else-if ladder statement in C

The elif declaration syntax is given below

Trang 32

Enter the number?15

number is not equal to 10, 50 or 100

EXAMPLE 2

marks = int(input("Enter the marks? "))

f marks > 85 and marks <= 100:

print("Congrats ! you scored grade A ") lif marks > 60 and marks <= 85:

print("You scored grade B + ")

Trang 33

lif marks > 40 and marks <= 60:

print("You scored grade B ") lif (marks > 30 and marks <= 40):

print("You scored grade C ") lse:

print("Sorry you are fail ?")

Trang 34

Python Loops

By example, the flow of programs written into every programming language is sequential Sometimes, we mightneed to change the program's flow You can need to repeat many numbers of times to execute a particular code.The programming languages provide various types of loops for this purpose which are capable of repeating severalnumbers of times a certain specific code Consider the diagram below to understand what a loop statement works

Why use loops

The looping simplifies the difficult issues into the easy ones It allows us to change the program flow so that we canrepeat the same code for a finite number of times instead of writing the same code again and again For example, if

we need to print the first 10 natural numbers then we can print inside a loop that runs up to 10 iterations instead of

10 times using the print statement

Advantages of loops

1 It gives reusability of code

2 We don't have to write the same code again and again, using loops

3 We can traverse the elements of the data structures (array or linked lists) using loops

Loop

Statement

Description

for loop The for loop is used in case we need to execute some part of the code until the condition

is fulfilled The for loop is also known as a per-tested loop If the amount of iteration is specified in advance it is easier to use it for loop.

Trang 35

condition stated in the while loop is satisfied It is also referred to as a pretested loop.

do-while loop The do-while loop continues until a given condition satisfies It is also called post tested

loop It is used when it is necessary to execute the loop at least once (mostly menu driven programs).

Trang 36

Python for loop

In Python the for loop is used many times to iterate the statements or a portion of the program This is also used tonavigate data structures such as the list, tuple, or dictionary

The syntax in python for loop is provided below

for iterating_var in sequence:

statement(s)

For Loop Flow Chart

For loop Using Sequence

Example-1: Iterating string using for loop

Trang 37

The sum is: 183

Nested for loop in python

Python enables us to nest any number of for loop inside a for loop For each iteration of the outer loop the innerloop is executed n number of times The syntax is listed below

for iterating_var1 in sequence: #outer loop

for iterating_var2 in sequence: #inner loop

#block of statements

#Other statements

Example- 1: Nested for loop

# User input for number of rows

rows = int(input("Enter the rows:"))

# Outer loop will print number of rows

Trang 38

Enter the rows:5

Example-2: Program to number pyramid

rows = int(input("Enter the rows"))

Using else statement with for loop

UnLike other languages such as C, C++, or Java, Python helps one to use the other sentence with the loop that canonly be executed if all iterations are completed

else:print("for loop is exhausted");

print("The loop is broken due to break statement came out of the loop")

Output:

0

Trang 39

Python While loop

The Python while loop enables execution of a part of the code until the given condition returns false It is alsoreferred to as a pretested loop

If we don't know the number of iterations then using the while loop is the most efficient

The following syntax is given

Trang 40

Infinite while loop

If the condition is given in the while loop never becomes false, then the while loop never ends and turns into theinfinite while looping

Any non-zero value in the while loop implies a state that is always valid, while null implies the state that is alwaysfalse This kind of methodology is helpful if we want our system to run continuously without interruption in theloop

Example 1

Ngày đăng: 27/11/2022, 21:29