Download Python programming (basics)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
PYTHON
-no semicolons (;)
-No brackets for test condition
-after each condition put two dots (:)
INPUT & OUTPUT
-
If you want to input something always use input function input_raw doesn t work in the
latest compilers!
EXAMPLE:
n= input(„Enter a number:“)
print(n) // prints out the entered number that is stored inside n
or for inputing a string in python 2.7 // (python >2.7 doesn't need raw_input just input());
n=raw_input()
-the same goes for inputing a string.
- printing a string and int together:
>>> a=n+5
>>> print("Uneseni broj je %d" %a) // nema zareza nakon stringa
If you want to print out anything you must use normal
braces () not matter what your input is.
MATH
Some built in functions wich do not require import statement
-
to the power :pow(a,b) or a**b
abs(a),abs(-a)
Some built in functions wich require import statement (import math)
Or cal lit like this: from math import *
-
math.floor(decimal_number)
-
math.sqrt(float number)
You can also assing functions to variables like this( number=math.floor())
and use it like this: number(18.7)
-
sometimes you need to put the number to only dwo decimal points
print("%.2f"%c)
STRINGS
-
no difference between „ “ OR ' ' both work the same
/  escape character
Concatenate a=afd b=sdf  a+b=afdsdf
Two ways to convert to a string (we have to convert in order to display in on the console)
1.num=str(8); //converts to string or
2. `number` example print ("my mos is " +`num`)
Always use the first one because the second doesn t work in some compilers versions.
ARRAYS
-
Array declaration: array=[„sdf“, „asd“,“sdf“] 0,1,2
Printing an array: array[2]
Example:
numbers=[1,2,3,4,5,6]
numbers[4:]  Prints out 5 and 6 (startin from indeks 4 and going to the end
-another example: example[0:6:2]  starting rom 0 to 6 and going up on index by two.
-another example: example[::-2]  going from the top of the array to the bottom by two values
ARRAY BUILT IN FUNCTIONS
.append(value)
.count(argument_to_count)
.extend(array)  concatenates array to an array
.index(parameter)
.insert(indeks_int,value_appropriate)
.pop(index_int) m returns the value of the indeks
.remove (object_value)
.reverse()
-sorted(„string_param“)  cuts the string into characters ,, improvized array)
CONTINUING ARRAYS
>>> bucky="hey there %s hows your %s"
>>> varb=("betty", "foot")  using C logic
>>> print (bucky %varb)
Output: hey there betty hows your foot
Populating array with integer numbers:
numbers=[]
z=0
for x in range(0,5):
i=input()
numbers.append(i)
for y in numbers:
print(y)
Printing array in reverse with indexes:
polje=[1,2,3,4,5,6]
for i in range(len(polje)-1,-1,-1):
print(polje[i])
STRING METHODS
Find Method  gets the index of the starting word character
>>> example="hey now asvasdfaf"
>>> example.find('c')
-1
>>> example.find("now")
4
Join method .string.join(array)
>>> seperator='hoss'
>>> sequence=[]
>>> sequence=["hey","there","bessie","maro"]
>>> sequence
['hey', 'there', 'bessie', 'maro']
>>> glue="hoss"
>>> glue.join(sequence)
'heyhosstherehossbessiehossmaro'
>>>
Upper(),lower(), replace(argument string,argument new string)
randstr="i whis i had no sausage"
>>> randstr.lower()
'i whis i had no sausage'
>>> truth="I love old women"
>>> truth.upper()
'I LOVE OLD WOMEN'
>>> truth.replace("love","hate")
'I hate old women'
DICTIONARIES
-
Are used to associate values with values (similar to an array look at example below)
>>> book={"dad":"bob", "mom":"lisa", "Bro":"Joe"}
>>> book
{'dad': 'bob', 'mom': 'lisa', 'Bro': 'Joe'}
>>> book["Dad"]
Traceback (most recent call last):
File "<pyshell#89>", line 1, in <module>
book["Dad"]
KeyError: 'Dad'
>>> book["dad"]
'bob'
>>> book.clear() // to clear the book (array has no elements)
IF STATEMENTS
Syntax:
If variable logical_operator another_variable: logic
-elif
elif:logic
-else
else: logic
example including all of the above:
>>> if name=="mark": print("dobro ime")
elif name=="ted": print("dobro ime")
else: print("dobro ime")
Nested if statements (example explains everything)
thing ="animal"
animal="cat"
if thing=="animal":
if animal=="cat":
print ("this is a cat")
else:
print("i dont know what that animal is")
else:
print("i dont know what that thing is")
COMPARISON OPERATORS
-All the same except in python there are „in“ and „is “ operators which are pretty
straight forward. Is operator will return true only if the two object are the same in the
memories. If the two object s aren t the same and hold equal values you will get false.
With the in operator you can search for a specific character for example. Let s say you ve got a string
named pizza and this string holds „pizzahut“ and if you declare the folowing code :'s' in pizza you will
get false because of no s in the variable value pizzahut.
Example:
p="pizza"
if 'z' in p:
print("there is a letter z in pizza") // prints out
else:
print ("no letter in pizza")
-AND  and ,, OR – or (use only lowercase letters, python is 99% lowercase)
LOOPS
WHILE LOOP
Syntax:
while condition: logic (don t forget to increment/decrement)
-infinite loop (setting a loop to true always)
Example:
while 1:
name= input(„enter a name:“)
if name==“quit“ : break
FOR LOOP
Syntax:
for variable in collection: logic (no need to increment/decrement)
-
range()  allows you to set the range of the for loop from begining to end
EXAMPLE:
for var in range(1,10)
print (var)
EXAMPLE:
For var in range(10)
print (var)
we often use break and continue in loops, they are the same as in other programming languages
FUNCTIONS (custom functions)
Syntax:
def function_name(argument/no argument): logic
-
in python the function must go before the main exectuion!
Just place the functions abvove and the main function below (the call goes below)
example pyhton:
A RETURN TYPE FUNCTION:
def sum_two_numbers(a, b):
return a + b
x = sum_two_numbers(1,2)
print ("Suma iznosi "+str(x))
A VOID TYPE FUNCTION:
def sum_two_numbers():
print("printamo!")
sum_two_numbers(1,2)
TUPLES VS ARRAYS
Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple is immutable whereas a list is mutable.
1. You can't add elements to a tuple. Tuples have no append or extend method.
2. You can't remove elements from a tuple. Tuples have no remove or pop method.
3. You can find elements in a tuple, since this doesn’t change the tuple.
4. You can also use the in operator to check if an element exists in the tuple.
Converting string to array  list(array)
Some examples done in python
SOLVED PROBLEMS
1.zad
brojnik=input("Unesite brojnik\n")
nazivnik=raw_input("Unesite Nazivnik\n")
while nazivnik==0:
nazivnik=input("Uneseni nazinvik je nula, ponovni unos:\n")
rezultat=brojnik/float(nazivnik)
print("Rezulat iznosi"+str(rezultat))
2.zad
polje=[];
brojac_parnih=0;
for x in range(0,5):
z=input("Unesite broj\n")
if (z%2==0):
polje.append(z);
brojac_parnih=brojac_parnih+1
print("Ukupan broj parnih brojeva iznosi: "+str(brojac_parnih))
for x in polje:
print(x)
3.zad
sumpoz=0
sumneg=0
arsneg=0
arspoz=0
counterpoz=0
counterneg=0
while 1:
realni=input("Upisite realni broj:")
if realni==0 :break
elif realni>0:
sumpoz=sumpoz+realni
counterpoz=counterpoz+1
elif realni<0:
sumneg=sumneg+realni
counterneg=counterneg+1
if counterpoz!=0:
arspoz=sumpoz/float(counterpoz)
print("prosijek pozitvnih realnih brojeva je %f"%arspoz)
else:
print("nema unesenih pozitivnih brojeva")
if counterneg!=0:
arsneg= sumneg/float(counterneg)
print("prosijek negativnih realnih brojeva je %f"%arsneg)
else:
print("nema unesenih negativnih brojeva")
4.zad
a=input("Unesite prvu granicu")
b=input("Unesite drugu granicu")
suma=0
if (b<a):
for i in range(b+1,a):
suma=suma+i
elif b>a:
for x in range(a+1,b):
suma=suma+x
print ("Suma brojeva izmedu granica iznosi "+str(suma))
4.2
a=input("Unesite prvu granicu")
b=input("Unesite drugu granicu")
suma=0
if (b<a):
c=a
a=b
b=c
for x in range(a+1,b):
suma=suma+x
print ("Suma brojeva izmedu granica iznosi "+str(suma))
5.Summing digits of a number
number=input("Input a number please:")
rez=0
suma=0
while True:
rez=number%10
suma=suma+rez
number=number/10
if number==0:
break;
print("rezultat je :"+str(suma))
5. String to list conversion!
x=raw_input("Unesite neku recenicu")
polje=list(x);
for x in range(0,len(polje)):
if polje[x]=='a' or polje[x]=='e':
polje[x]='X'
for x in range(0,len(polje)):
print(polje[x])
6.PRIMARNI BROJEVI
sum = 0;
umnozak = 1
for broj in range (2,1001):
prime = True
for i in range(2,int(broj**0.5)+1):
if (broj%i==0):
prime = False; break
if prime:
sum=sum+broj
umnozak= umnozak*broj
print("suma tih brojeva iznosi :"+str(sum))
print("Umnozak iznosi:"+str(umnozak))
7.Unos,modifikacija,i i ispis polja
array=[];
for i in range(0,10):
x=input("Enter a integer number")
array.append(x);
for i in range(0,len(array)):
if (array[i]<0):
array[i]=0
for i in range (0,len(array)):
print(str(array[i]));
8. Counting letters in string
x=raw_input("Enter a string")
counter=len(x)-x.count(' ');
print(str(counter))