Python Codes


Python Codes


In this page i will collect some python codes as a references.

1 from collections import Counter
name=” apple orange apple Banana orange apple peach Blueberries”.split()
print (Counter(name))
Output:
a Dictionary with each fruits with its repetition.CHECK
2 One line code:
return[n for n in numbers if n > 0 and n % 2 == 0]
Output:
A list of positive even numbers in a given list called”numbers”
3 One line code:
num =101
while num >=100 : num=int(input(“Enter a number between (0,100)”))
Output:
Keep ask the user for a number until he enter a number less than 100.
4 names={‘Peter’:20,’Jack’:18,’jon’:33,’lusy’:25}
s_names=sorted(names.items(),key=lambda x: x[1], reverse=True)
Output:
s_names will be sorted names. CHECK
5 pair_number.extend((n1,n2))
Output:
Add multiple numbers to a list
6 for i in range (5):
print (f'{i} apple{“s” if i !=1 else “”}’)
Output:
add s to apple if count is singular/plural. CHECK
7 name=’lucy’
age=35
print (f'{name} your age is {age}’)
Output:
print the string with name,age vars
in positions. CHECK
8 num=15
divisors=[i for i in range(1,num+1) if num%i==0]

Output: A Dictionary of divisors of a gevin number (num).
9 digs=[]
for each in str(num):
digs.append(each)
Output:digs will contain each digit of the number num.
10 Factorial
def Factorial(num):
if (num == 0) :
return 1
else:
return num * Factorial(num-1)
Output: return the Factorial of a number
#
Output:
#
Output:
Advertisements
%d bloggers like this: